1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
147 #include <boost/archive/text_oarchive.hpp>
148 #include <boost/archive/text_iarchive.hpp>
149 #include <boost/serialization/list.hpp>
150 #include <boost/serialization/string.hpp>
153 using SMESH::TPythonDump;
156 #define NUM_TMP_FILES 2
159 static int MYDEBUG = 0;
161 static int MYDEBUG = 0;
164 // Static variables definition
165 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
166 CORBA::ORB_var SMESH_Gen_i::myOrb;
167 PortableServer::POA_var SMESH_Gen_i::myPoa;
168 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
169 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
170 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
173 const int nbElemPerDiagonal = 10;
175 //=============================================================================
177 * GetServant [ static ]
179 * Get servant of the CORBA object
181 //=============================================================================
183 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
185 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
188 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
191 catch (PortableServer::POA::ObjectNotActive &ex)
193 INFOS("GetServant: ObjectNotActive");
196 catch (PortableServer::POA::WrongAdapter &ex)
198 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
201 catch (PortableServer::POA::WrongPolicy &ex)
203 INFOS("GetServant: WrongPolicy");
208 INFOS( "GetServant - Unknown exception was caught!!!" );
213 //=============================================================================
215 * SObjectToObject [ static ]
217 * Get CORBA object corresponding to the SALOMEDS::SObject
219 //=============================================================================
221 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
223 SALOMEDS::GenericAttribute_wrap anAttr;
224 CORBA::Object_var anObj;
225 if ( !theSObject->_is_nil() ) {
227 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
228 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
229 CORBA::String_var aValue = anIOR->Value();
230 if( strcmp( aValue, "" ) != 0 )
231 anObj = GetORB()->string_to_object( aValue );
235 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
241 //=============================================================================
245 * Get SALOME_NamingService object
247 //=============================================================================
249 SALOME_NamingService* SMESH_Gen_i::GetNS()
251 if ( myNS == NULL ) {
252 myNS = SINGLETON_<SALOME_NamingService>::Instance();
253 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
254 myNS->init_orb( GetORB() );
259 //=============================================================================
263 * Get SALOME_LifeCycleCORBA object
265 //=============================================================================
267 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
269 if ( myLCC == NULL ) {
270 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
275 //=============================================================================
277 * GetGeomEngine [ static ]
279 * Get GEOM::GEOM_Gen reference
281 //=============================================================================
283 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( bool isShaper )
285 Engines::EngineComponent_ptr temp =
286 GetLCC()->FindOrLoad_Component( isShaper ? "FactoryServer" : "FactoryServer",
287 isShaper ? "SHAPERSTUDY" : "GEOM" );
288 myGeomGen = GEOM::GEOM_Gen::_narrow( temp );
293 //=============================================================================
295 * GetGeomEngine [ static ]
297 * Get GEOM::GEOM_Gen reference
299 //=============================================================================
301 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
303 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
304 if ( !CORBA::is_nil( go ))
309 //=============================================================================
311 * SMESH_Gen_i::SMESH_Gen_i
313 * Default constructor: not for use
315 //=============================================================================
317 SMESH_Gen_i::SMESH_Gen_i()
321 //=============================================================================
323 * SMESH_Gen_i::SMESH_Gen_i
325 * Standard constructor, used with Container
327 //=============================================================================
329 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
330 PortableServer::POA_ptr poa,
331 PortableServer::ObjectId* contId,
332 const char* instanceName,
333 const char* interfaceName,
335 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
338 myOrb = CORBA::ORB::_duplicate(orb);
339 myPoa = PortableServer::POA::_duplicate(poa);
342 _id = myPoa->activate_object( _thisObj );
344 myStudyContext = new StudyContext;
346 myIsEmbeddedMode = false;
347 myIsEnablePublish = true;
348 myShapeReader = NULL; // shape reader
350 myIsHistoricalPythonDump = true;
351 myToForgetMeshDataOnHypModif = false;
353 // set it in standalone mode only
354 //OSD::SetSignal( true );
356 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
357 // find out mode (embedded or standalone) here else
358 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
359 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
362 if ( SALOME_NamingService* ns = GetNS() )
364 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
365 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
366 if ( !session->_is_nil() )
368 CORBA::String_var str_host = session->getHostname();
369 CORBA::Long s_pid = session->getPID();
370 string my_host = Kernel_Utils::GetHostname();
372 long my_pid = (long)_getpid();
374 long my_pid = (long) getpid();
376 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
382 //=============================================================================
384 * SMESH_Gen_i::~SMESH_Gen_i
388 //=============================================================================
390 SMESH_Gen_i::~SMESH_Gen_i()
392 // delete hypothesis creators
393 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
394 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
396 // same creator can be mapped under different names
397 GenericHypothesisCreator_i* creator = (*itHyp).second;
401 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
402 if ( creator == (*itHyp2).second )
403 (*itHyp2).second = 0;
405 myHypCreatorMap.clear();
407 // Clear study contexts data
408 delete myStudyContext;
410 // delete shape reader
412 delete myShapeReader;
415 //=============================================================================
417 * SMESH_Gen_i::getHypothesisCreator
419 * Get hypothesis creator
421 //=============================================================================
423 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
424 const char* theLibName,
425 std::string& thePlatformLibName)
427 std::string aPlatformLibName;
428 /* It's Need to translate lib name for WIN32 or X platform */
429 if ( theLibName && theLibName[0] != '\0' )
431 int libNameLen = strlen(theLibName);
432 //check for old format "libXXXXXXX.so"
433 if (libNameLen > 7 &&
434 !strncmp( theLibName, "lib", 3 ) &&
435 !strcmp( theLibName+libNameLen-3, ".so" ))
439 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
440 #elif defined(__APPLE__)
441 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
443 aPlatformLibName = theLibName;
448 //try to use new format
450 aPlatformLibName = theLibName;
451 aPlatformLibName += ".dll";
452 #elif defined(__APPLE__)
453 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
455 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
459 thePlatformLibName = aPlatformLibName;
461 Unexpect aCatch(SALOME_SalomeException);
462 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
464 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
465 GenericHypothesisCreator_i* aCreator;
468 // check, if creator for this hypothesis type already exists
469 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
471 // load plugin library
472 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
475 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
477 const char* path = aPlatformLibName.c_str();
480 const char* path = aPlatformLibName.c_str();
482 LibHandle libHandle = LoadLib( path );
483 #if defined(WIN32) && defined(UNICODE)
488 // report any error, if occurred
490 const char* anError = dlerror();
491 throw(SALOME_Exception( anError ));
493 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
494 << aPlatformLibName));
498 // get method, returning hypothesis creator
499 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
500 GetHypothesisCreator procHandle =
501 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
504 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
505 << aPlatformLibName ));
506 UnLoadLib(libHandle);
509 // get hypothesis creator
510 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
511 aCreator = procHandle(theHypName);
514 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
515 << aPlatformLibName));
517 // map hypothesis creator to a hypothesis name
518 myHypCreatorMap[string(theHypName)] = aCreator;
523 return myHypCreatorMap[string(theHypName)];
526 catch (SALOME_Exception& S_ex)
528 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
533 //=============================================================================
535 * SMESH_Gen_i::createHypothesis
537 * Create hypothesis of given type
539 //=============================================================================
541 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
542 const char* theLibName)
544 SMESH_Hypothesis_i* myHypothesis_i = 0;
545 SMESH::SMESH_Hypothesis_var hypothesis_i;
546 std::string aPlatformLibName;
547 GenericHypothesisCreator_i* aCreator =
548 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
550 // create a new hypothesis object, store its ref. in studyContext
551 myHypothesis_i = aCreator->Create(myPoa, &myGen);
554 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
555 CORBA::String_var hypName = myHypothesis_i->GetName();
556 myHypCreatorMap[ hypName.in() ] = aCreator;
558 // activate the CORBA servant of hypothesis
559 hypothesis_i = myHypothesis_i->_this();
560 int nextId = RegisterObject( hypothesis_i );
561 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
562 else { (void)nextId; } // avoid "unused variable" warning in release mode
564 return hypothesis_i._retn();
567 //=============================================================================
569 * SMESH_Gen_i::createMesh
571 * Create empty mesh on shape
573 //=============================================================================
575 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
577 Unexpect aCatch(SALOME_SalomeException);
578 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
580 // Get or create the GEOM_Client instance
582 // create a new mesh object servant, store it in a map in study context
583 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
584 // create a new mesh object
585 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
586 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
588 // activate the CORBA servant of Mesh
589 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
590 int nextId = RegisterObject( mesh );
591 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
592 else { (void)nextId; } // avoid "unused variable" warning in release mode
595 catch (SALOME_Exception& S_ex) {
596 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
598 return SMESH::SMESH_Mesh::_nil();
601 //=============================================================================
603 * SMESH_Gen_i::GetShapeReader
607 //=============================================================================
609 GEOM_Client* SMESH_Gen_i::GetShapeReader()
611 // create shape reader if necessary
612 if ( !myShapeReader )
613 myShapeReader = new GEOM_Client(GetContainerRef());
614 ASSERT( myShapeReader );
615 return myShapeReader;
618 //=============================================================================
620 * SMESH_Gen_i::SetGeomEngine
622 * Set GEOM::GEOM_Gen reference
624 //=============================================================================
626 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
628 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
631 //=============================================================================
633 * SMESH_Gen_i::SetEmbeddedMode
637 //=============================================================================
639 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
641 myIsEmbeddedMode = theMode;
643 if ( !myIsEmbeddedMode ) {
644 //PAL10867: disable signals catching with "noexcepthandler" option
645 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
646 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
651 char* envDisableFPE = getenv("DISABLE_FPE");
652 if (envDisableFPE && atoi(envDisableFPE))
657 OSD::SetSignal( raiseFPE );
659 // else OSD::SetSignal() is called in GUI
663 //=============================================================================
665 * SMESH_Gen_i::IsEmbeddedMode
669 //=============================================================================
671 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
673 return myIsEmbeddedMode;
676 //=============================================================================
678 * SMESH_Gen_i::SetEnablePublish
680 * Set enable publishing in the study
682 //=============================================================================
684 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
686 myIsEnablePublish = theIsEnablePublish;
689 //=============================================================================
691 * SMESH_Gen_i::IsEnablePublish
693 * Check enable publishing
695 //=============================================================================
697 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
699 return myIsEnablePublish;
702 //=============================================================================
704 * SMESH_Gen_i::UpdateStudy
706 * Update study (needed at switching GEOM->SMESH)
708 //=============================================================================
710 void SMESH_Gen_i::UpdateStudy()
712 if ( !myStudyContext )
713 myStudyContext = new StudyContext;
715 SALOMEDS::Study_var aStudy = getStudyServant();
716 if ( !CORBA::is_nil( aStudy ) )
718 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
720 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
721 if( !GEOM_var->_is_nil() )
722 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
724 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
725 if( !GEOM_var->_is_nil() )
726 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
728 // NPAL16168, issue 0020210
729 // Let meshes update their data depending on GEOM groups that could change
730 CORBA::String_var compDataType = ComponentDataType();
731 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
732 if ( !me->_is_nil() ) {
733 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
734 for ( ; anIter->More(); anIter->Next() ) {
735 SALOMEDS::SObject_wrap so = anIter->Value();
736 CORBA::Object_var ior = SObjectToObject( so );
737 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
738 mesh->CheckGeomModif();
744 //================================================================================
746 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
748 //================================================================================
750 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
752 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
753 SALOMEDS::GenericAttribute_wrap attr;
754 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
756 SALOMEDS::AttributePixMap_wrap pm = attr;
757 CORBA::String_var ico = pm->GetPixMap();
758 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
763 //=================================================================================
764 // function : hasObjectInfo()
765 // purpose : shows if module provides information for its objects
766 //=================================================================================
768 bool SMESH_Gen_i::hasObjectInfo()
773 //=================================================================================
774 // function : getObjectInfo()
775 // purpose : returns an information for a given object by its entry
776 //=================================================================================
778 char* SMESH_Gen_i::getObjectInfo( const char* entry )
780 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
781 // for the rest, "module 'SMESH', ID=0:1:2:*"
785 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
786 CORBA::Object_var obj = SObjectToObject( so );
787 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
788 if ( isGeomModifIcon( mesh ))
790 txt << "The geometry was changed and the mesh needs to be recomputed";
795 CORBA::String_var compType = ComponentDataType();
796 txt << "module '" << compType << "', ID=" << entry;
798 return CORBA::string_dup( txt );
801 //=============================================================================
803 * SMESH_Gen_i::GetStudyContext
807 //=============================================================================
809 StudyContext* SMESH_Gen_i::GetStudyContext()
811 return myStudyContext;
814 //=============================================================================
816 * SMESH_Gen_i::CreateHypothesis
818 * Create hypothesis/algorithm of given type and publish it in the study
820 //=============================================================================
822 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
823 const char* theLibName )
825 Unexpect aCatch(SALOME_SalomeException);
826 // Create hypothesis/algorithm
827 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
829 // Publish hypothesis/algorithm in the study
830 if ( CanPublishInStudy( hyp ) ) {
831 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
832 if ( !aSO->_is_nil() ) {
833 // Update Python script
834 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
835 << theHypName << "', '" << theLibName << "')";
842 //================================================================================
844 * \brief Return a hypothesis initialized by given average length.
845 * \param theHypType - hypothesis type name
846 * \param theLibName - plugin library name
847 * \param theAverageLength - average length
848 * \param theQuadDominated - is quad-dominated flag
849 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
851 //================================================================================
853 SMESH::SMESH_Hypothesis_ptr
854 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
855 const char* theLibName,
856 CORBA::Double theAverageLength,
857 CORBA::Boolean theQuadDominated)
859 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
860 theAverageLength, theQuadDominated };
862 SMESH::SMESH_Hypothesis_var hyp =
863 GetHypothesisParameterValues( theHypType, theLibName,
864 SMESH::SMESH_Mesh::_nil(),
865 GEOM::GEOM_Object::_nil(),
867 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
869 TPythonDump() << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
870 << theHypType << "', '"
871 << theLibName << "', "
872 << theAverageLength << ", "
873 << theQuadDominated << " )";
878 //================================================================================
880 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
881 * existing on the given geometry or to size of the geometry.
882 * \param theHypType - hypothesis type name
883 * \param theLibName - plugin library name
884 * \param theMesh - The mesh of interest
885 * \param theGeom - The shape to get parameter values from
886 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
887 * in a study and used to compute the mesh, or a temporary one created just to pass
890 //================================================================================
892 SMESH::SMESH_Hypothesis_ptr
893 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
894 const char* theLibName,
895 SMESH::SMESH_Mesh_ptr theMesh,
896 GEOM::GEOM_Object_ptr theGeom,
897 const SMESH::HypInitParams& theParams)
899 Unexpect aCatch(SALOME_SalomeException);
901 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
902 if ( byMesh && CORBA::is_nil( theMesh ) )
903 return SMESH::SMESH_Hypothesis::_nil();
904 if ( byMesh && CORBA::is_nil( theGeom ) )
905 return SMESH::SMESH_Hypothesis::_nil();
907 // -----------------------------------------------
908 // find hypothesis used to mesh theGeom
909 // -----------------------------------------------
911 // get mesh and shape
912 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
913 TopoDS_Shape shape = GeomObjectToShape( theGeom );
914 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
915 return SMESH::SMESH_Hypothesis::_nil();
916 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
918 // create a temporary hypothesis to know its dimension
919 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
920 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
922 return SMESH::SMESH_Hypothesis::_nil();
923 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
926 // look for a hypothesis of theHypType used to mesh the shape
927 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
930 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
931 int nbLocalHyps = aHypList->length();
932 for ( int i = 0; i < nbLocalHyps; i++ ) {
933 CORBA::String_var hypName = aHypList[i]->GetName();
934 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
935 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
937 // check super shapes
938 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
939 while ( nbLocalHyps == 0 && itShape.More() ) {
940 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
941 if ( ! CORBA::is_nil( geomObj )) {
942 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
943 nbLocalHyps = aHypList->length();
944 for ( int i = 0; i < nbLocalHyps; i++ )
945 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
946 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
952 // let the temporary hypothesis find out somehow parameter values by mesh
953 if ( hyp->SetParametersByMesh( mesh, shape ))
954 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
958 ::SMESH_Hypothesis::TDefaults dflts;
959 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
960 dflts._nbSegments = myGen.GetDefaultNbSegments();
961 dflts._elemLength = theParams.averageLength;
962 dflts._quadDominated = theParams.quadDominated;
963 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
966 dflts._diagonal = mesh->GetShapeDiagonalSize();
968 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
969 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
970 dflts._shape = &shape;
973 // let the hypothesis initialize it's values
974 if ( hyp->SetParametersByDefaults( dflts, mesh ))
975 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
978 return SMESH::SMESH_Hypothesis::_nil();
981 //=============================================================================
983 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
984 * \param [in] theHyp - the hypothesis of interest
985 * \param [out] theMesh - the sole mesh using \a theHyp
986 * \param [out] theShape - the sole geometry \a theHyp is assigned to
987 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
989 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
990 * considered as SAME sub-mesh => result is \c true.
991 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
992 * a shape to which an hyp being edited is assigned.
994 //=============================================================================
996 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
997 SMESH::SMESH_Mesh_out theMesh,
998 GEOM::GEOM_Object_out theShape)
1000 if ( CORBA::is_nil( theHyp ))
1003 // get Mesh component SO
1004 CORBA::String_var compDataType = ComponentDataType();
1005 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1006 if ( CORBA::is_nil( comp ))
1009 // look for child SO of meshes
1010 SMESH::SMESH_Mesh_var foundMesh;
1011 TopoDS_Shape foundShape;
1013 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1014 for ( ; meshIter->More() && isSole; meshIter->Next() )
1016 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1017 CORBA::Object_var obj = SObjectToObject( curSO );
1018 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1022 // look for a sole shape where theHyp is assigned
1023 bool isHypFound = false;
1024 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1025 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1026 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1028 const THypList& hyps = s2hypsIt.Value();
1029 THypList::const_iterator h = hyps.begin();
1030 for ( ; h != hyps.end(); ++h )
1031 if ( (*h)->GetID() == theHyp->GetId() )
1033 if ( h != hyps.end()) // theHyp found
1036 if ( ! foundShape.IsNull() &&
1037 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1039 foundShape.Nullify();
1043 foundShape = s2hypsIt.Key();
1045 } // loop on assigned hyps
1047 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1049 if ( !foundMesh->_is_nil() ) // not a sole mesh
1051 if ( !foundMesh->HasShapeToMesh() ||
1052 !mesh_i ->HasShapeToMesh() )
1054 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1058 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1059 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1060 isSole = s1->IsSame( s2 );
1063 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1069 ! foundMesh->_is_nil() &&
1070 ! foundShape.IsNull() )
1072 theMesh = foundMesh._retn();
1073 theShape = ShapeToGeomObject( foundShape );
1074 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1079 //=============================================================================
1081 * Set number of segments per diagonal of boundary box of geometry by which
1082 * default segment length of appropriate 1D hypotheses is defined
1084 //=============================================================================
1086 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1088 if ( theNbSegments > 0 )
1089 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1091 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1094 //=============================================================================
1096 * \brief Set default number of segments per edge
1098 //=============================================================================
1100 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1102 if ( theNbSegments > 0 )
1103 myGen.SetDefaultNbSegments( int(theNbSegments) );
1105 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1108 //=============================================================================
1110 * Set an option value
1112 //=============================================================================
1114 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1116 if ( name && value && strlen( value ) > 0 )
1119 if ( strcmp(name, "historical_python_dump") == 0 )
1121 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1122 msgToGUI = "preferences/SMESH/historical_python_dump/";
1123 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1125 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1127 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1128 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1129 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1131 else if ( strcmp(name, "default_grp_color") == 0 )
1135 // color must be presented as a string of following form:
1136 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1137 str = str.substr(1);
1138 for ( size_t i = 0; i < str.length()/2; i++ )
1139 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1140 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1142 else if ( value ) { // rgb color ("255,170,0", for example)
1143 string tempValue( value );
1144 char* colorValue = strtok( &tempValue[0], "," );
1145 while ( colorValue != NULL ) {
1146 int c_value = atoi( colorValue );
1147 if ( c_value >= 0 && c_value <= 255 )
1148 color.push_back( c_value );
1149 colorValue = strtok( NULL, "," );
1152 if ( color.size() == 3 ) { // color must have three valid component
1153 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1154 myDefaultGroupColor = value;
1155 msgToGUI = "preferences/SMESH/default_grp_color/";
1160 // update preferences in case if SetOption() is invoked from python console
1161 if ( !msgToGUI.empty() )
1163 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1164 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1165 if ( !CORBA::is_nil( session ) )
1166 session->emitMessageOneWay(msgToGUI.c_str());
1171 //=============================================================================
1173 * Return an option value
1175 //=============================================================================
1177 char* SMESH_Gen_i::GetOption(const char* name)
1181 if ( strcmp(name, "historical_python_dump") == 0 )
1183 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1185 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1187 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1189 if ( strcmp(name, "default_grp_color") == 0 )
1191 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1194 return CORBA::string_dup( "" );
1197 //=============================================================================
1199 * SMESH_Gen_i::CreateMesh
1201 * Create empty mesh on a shape and publish it in the study
1203 //=============================================================================
1205 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1207 Unexpect aCatch(SALOME_SalomeException);
1208 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1210 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1212 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1213 ASSERT( meshServant );
1214 meshServant->SetShape( theShapeObject );
1216 // publish mesh in the study
1217 if ( CanPublishInStudy( mesh ) ) {
1218 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1219 aStudyBuilder->NewCommand(); // There is a transaction
1220 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1221 aStudyBuilder->CommitCommand();
1222 if ( !aSO->_is_nil() ) {
1223 // Update Python script
1224 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1228 return mesh._retn();
1231 //=============================================================================
1233 * SMESH_Gen_i::CreateEmptyMesh
1237 //=============================================================================
1239 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1241 Unexpect aCatch(SALOME_SalomeException);
1242 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1244 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1246 // publish mesh in the study
1247 if ( CanPublishInStudy( mesh ) ) {
1248 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1249 aStudyBuilder->NewCommand(); // There is a transaction
1250 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1251 aStudyBuilder->CommitCommand();
1252 if ( !aSO->_is_nil() ) {
1253 // Update Python script
1254 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1258 return mesh._retn();
1263 //================================================================================
1265 * \brief Throw an exception in case if the file can't be read
1267 //================================================================================
1269 void checkFileReadable( const char* theFileName )
1271 SMESH_File f ( theFileName );
1274 if ( !f.error().empty() )
1275 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1277 THROW_SALOME_CORBA_EXCEPTION
1278 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1279 SALOME::BAD_PARAM );
1284 //=============================================================================
1286 * SMESH_Gen_i::CreateMeshFromUNV
1288 * Create mesh and import data from UNV file
1290 //=============================================================================
1292 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1294 Unexpect aCatch(SALOME_SalomeException);
1296 checkFileReadable( theFileName );
1298 SMESH::SMESH_Mesh_var aMesh = createMesh();
1300 // publish mesh in the study
1301 if ( CanPublishInStudy( aMesh ) ) {
1302 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1303 aStudyBuilder->NewCommand(); // There is a transaction
1304 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1305 aStudyBuilder->CommitCommand();
1306 if ( !aSO->_is_nil() ) {
1307 // Update Python script
1308 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1312 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1314 aServant->ImportUNVFile( theFileName );
1316 // Dump creation of groups
1317 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1319 aServant->GetImpl().GetMeshDS()->Modified();
1320 return aMesh._retn();
1323 //=============================================================================
1325 * SMESH_Gen_i::CreateMeshFromMED
1327 * Create mesh and import data from MED file
1329 //=============================================================================
1331 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1332 SMESH::DriverMED_ReadStatus& theStatus,
1333 const char* theCommandNameForPython,
1334 const char* theFileNameForPython)
1337 char bname[ _MAX_FNAME ];
1338 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1339 string aFileName = bname;
1341 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1343 // Retrieve mesh names from the file
1344 DriverMED_R_SMESHDS_Mesh myReader;
1345 myReader.SetFile( theFileName );
1346 myReader.SetMeshId( -1 );
1347 Driver_Mesh::Status aStatus;
1348 list<string> aNames = myReader.GetMeshNames(aStatus);
1349 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1350 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1352 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1355 TPythonDump aPythonDump;
1356 aPythonDump << "([";
1358 if (theStatus == SMESH::DRS_OK) {
1359 SALOMEDS::StudyBuilder_var aStudyBuilder;
1360 aStudyBuilder = getStudyServant()->NewBuilder();
1361 aStudyBuilder->NewCommand(); // There is a transaction
1363 aResult->length( aNames.size() );
1366 // Iterate through all meshes and create mesh objects
1367 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1370 if (i > 0) aPythonDump << ", ";
1373 SMESH::SMESH_Mesh_var mesh = createMesh();
1375 // publish mesh in the study
1376 SALOMEDS::SObject_wrap aSO;
1377 if ( CanPublishInStudy( mesh ) )
1378 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1379 // - as names of meshes are stored in MED file, we use them for data publishing
1380 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1381 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1384 if ( !aSO->_is_nil() ) {
1387 aPythonDump << "mesh_" << i;
1390 // Read mesh data (groups are published automatically by ImportMEDFile())
1391 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1392 ASSERT( meshServant );
1393 SMESH::DriverMED_ReadStatus status1 =
1394 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1395 if (status1 > theStatus)
1396 theStatus = status1;
1398 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1399 meshServant->GetImpl().GetMeshDS()->Modified();
1401 if ( !aStudyBuilder->_is_nil() )
1402 aStudyBuilder->CommitCommand();
1405 // Update Python script
1406 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1408 // Dump creation of groups
1409 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1410 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1412 return aResult._retn();
1415 //================================================================================
1417 * \brief Create meshes by reading a MED file
1419 //================================================================================
1421 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1422 SMESH::DriverMED_ReadStatus& theStatus)
1424 Unexpect aCatch(SALOME_SalomeException);
1425 checkFileReadable( theFileName );
1427 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1428 "CreateMeshesFromMED", theFileName);
1432 //=============================================================================
1434 * SMESH_Gen_i::CreateMeshFromSAUV
1436 * Create mesh and import data from SAUV file
1438 //=============================================================================
1440 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1441 SMESH::DriverMED_ReadStatus& theStatus)
1443 Unexpect aCatch(SALOME_SalomeException);
1444 checkFileReadable( theFileName );
1446 std::string sauvfilename(theFileName);
1447 std::string medfilename(theFileName);
1448 medfilename += ".med";
1451 cmd = "%PYTHONBIN% ";
1456 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1458 system(cmd.c_str());
1459 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1461 "CreateMeshesFromSAUV",
1462 sauvfilename.c_str());
1464 cmd = "%PYTHONBIN% ";
1469 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1471 system(cmd.c_str());
1475 //=============================================================================
1477 * SMESH_Gen_i::CreateMeshFromSTL
1479 * Create mesh and import data from STL file
1481 //=============================================================================
1483 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1485 Unexpect aCatch(SALOME_SalomeException);
1486 checkFileReadable( theFileName );
1488 SMESH::SMESH_Mesh_var aMesh = createMesh();
1491 char bname[ _MAX_FNAME ];
1492 _splitpath( theFileName, NULL, NULL, bname, NULL );
1493 string aFileName = bname;
1495 string aFileName = basename( const_cast<char *>(theFileName) );
1497 // publish mesh in the study
1498 if ( CanPublishInStudy( aMesh ) ) {
1499 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1500 aStudyBuilder->NewCommand(); // There is a transaction
1501 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1502 aStudyBuilder->CommitCommand();
1503 if ( !aSO->_is_nil() ) {
1504 // Update Python script
1505 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1509 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1511 aServant->ImportSTLFile( theFileName );
1512 aServant->GetImpl().GetMeshDS()->Modified();
1513 return aMesh._retn();
1516 //================================================================================
1518 * \brief Create meshes and import data from the CGSN file
1520 //================================================================================
1522 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1523 SMESH::DriverMED_ReadStatus& theStatus)
1525 Unexpect aCatch(SALOME_SalomeException);
1526 checkFileReadable( theFileName );
1528 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1531 // Retrieve nb meshes from the file
1532 DriverCGNS_Read myReader;
1533 myReader.SetFile( theFileName );
1534 Driver_Mesh::Status aStatus;
1535 int nbMeshes = myReader.GetNbMeshes(aStatus);
1536 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1538 aResult->length( nbMeshes );
1540 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1543 TPythonDump aPythonDump;
1544 aPythonDump << "([";
1546 if (theStatus == SMESH::DRS_OK)
1548 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1549 aStudyBuilder->NewCommand(); // There is a transaction
1553 // Iterate through all meshes and create mesh objects
1554 for ( ; i < nbMeshes; ++i )
1557 if (i > 0) aPythonDump << ", ";
1560 SMESH::SMESH_Mesh_var mesh = createMesh();
1561 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1563 // Read mesh data (groups are published automatically by ImportMEDFile())
1564 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1565 ASSERT( meshServant );
1567 SMESH::DriverMED_ReadStatus status1 =
1568 meshServant->ImportCGNSFile( theFileName, i, meshName );
1569 if (status1 > theStatus)
1570 theStatus = status1;
1572 meshServant->GetImpl().GetMeshDS()->Modified();
1573 // publish mesh in the study
1574 SALOMEDS::SObject_wrap aSO;
1575 if ( CanPublishInStudy( mesh ) )
1576 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1579 if ( !aSO->_is_nil() ) {
1583 aPythonDump << "mesh_" << i;
1586 aStudyBuilder->CommitCommand();
1589 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1591 // Dump creation of groups
1592 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1593 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1595 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1598 return aResult._retn();
1601 //================================================================================
1603 * \brief Create a mesh and import data from a GMF file
1605 //================================================================================
1607 SMESH::SMESH_Mesh_ptr
1608 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1609 CORBA::Boolean theMakeRequiredGroups,
1610 SMESH::ComputeError_out theError)
1612 Unexpect aCatch(SALOME_SalomeException);
1613 checkFileReadable( theFileName );
1615 SMESH::SMESH_Mesh_var aMesh = createMesh();
1617 char bname[ _MAX_FNAME ];
1618 _splitpath( theFileName, NULL, NULL, bname, NULL );
1619 string aFileName = bname;
1621 string aFileName = basename( const_cast<char *>(theFileName) );
1623 // publish mesh in the study
1624 if ( CanPublishInStudy( aMesh ) ) {
1625 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1626 aStudyBuilder->NewCommand(); // There is a transaction
1627 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1628 aStudyBuilder->CommitCommand();
1629 if ( !aSO->_is_nil() ) {
1630 // Update Python script
1631 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1632 << theFileName << "', "
1633 << theMakeRequiredGroups << " )";
1636 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1638 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1639 aServant->GetImpl().GetMeshDS()->Modified();
1640 return aMesh._retn();
1644 //=============================================================================
1646 * SMESH_Gen_i::IsReadyToCompute
1648 * Return true if mesh contains enough data to be computed
1650 //=============================================================================
1652 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1653 GEOM::GEOM_Object_ptr theShapeObject )
1655 Unexpect aCatch(SALOME_SalomeException);
1656 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1658 if ( CORBA::is_nil( theShapeObject ) )
1659 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1660 SALOME::BAD_PARAM );
1661 if ( CORBA::is_nil( theMesh ) )
1662 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1663 SALOME::BAD_PARAM );
1666 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1667 ASSERT( meshServant );
1668 if ( meshServant ) {
1669 // get local TopoDS_Shape
1670 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1671 // call implementation
1672 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1673 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1676 catch ( SALOME_Exception& S_ex ) {
1677 INFOS( "catch exception "<< S_ex.what() );
1682 //================================================================================
1684 * \brief Find SObject for an algo
1686 //================================================================================
1688 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1691 SALOMEDS::Study_var aStudy = getStudyServant();
1692 if ( !aStudy->_is_nil() ) {
1693 // find algo in the study
1694 CORBA::String_var compDataType = ComponentDataType();
1695 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1696 if ( !father->_is_nil() ) {
1697 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1698 for ( ; itBig->More(); itBig->Next() ) {
1699 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1700 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1701 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1702 for ( ; algoIt->More(); algoIt->Next() ) {
1703 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1704 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1705 if ( !CORBA::is_nil( algoIOR )) {
1706 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1707 if ( impl && impl->GetImpl() == algo )
1708 return algoSO._retn();
1710 } // loop on algo SO's
1713 } // SMESH component iterator
1717 return SALOMEDS::SObject::_nil();
1720 //================================================================================
1722 * \brief Return errors of mesh computation
1724 //================================================================================
1726 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1727 GEOM::GEOM_Object_ptr theSubObject )
1729 Unexpect aCatch(SALOME_SalomeException);
1730 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1732 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1733 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1735 if ( CORBA::is_nil( theMesh ) )
1736 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1738 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1740 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1743 if(theMesh->HasShapeToMesh())
1744 shape = GeomObjectToShape( theSubObject );
1746 shape = SMESH_Mesh::PseudoShape();
1748 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1750 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1753 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1754 const bool includeSelf = true, complexShapeFirst = true;
1755 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1757 while ( smIt->more() )
1760 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1762 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1763 if ( error && !error->IsOK() )
1765 if ( !( error->myAlgo ) &&
1766 !( error->myAlgo = sm->GetAlgo() ))
1768 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1769 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1770 errStruct.comment = error->myComment.c_str();
1771 errStruct.subShapeID = sm->GetId();
1772 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1773 if ( !algoSO->_is_nil() ) {
1774 CORBA::String_var algoName = algoSO->GetName();
1775 errStruct.algoName = algoName;
1778 errStruct.algoName = error->myAlgo->GetName();
1780 errStruct.hasBadMesh = error->HasBadElems();
1783 error_array->length( nbErr );
1786 catch ( SALOME_Exception& S_ex ) {
1787 INFOS( "catch exception "<< S_ex.what() );
1790 return error_array._retn();
1793 //================================================================================
1795 * \brief Return mesh elements preventing computation of a subshape
1797 //================================================================================
1799 SMESH::MeshPreviewStruct*
1800 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1801 CORBA::Short theSubShapeID )
1803 Unexpect aCatch(SALOME_SalomeException);
1804 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1806 if ( CORBA::is_nil( theMesh ) )
1807 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1809 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1812 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1814 // mesh implementation
1815 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1816 // submesh by subshape id
1817 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1820 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1821 if ( error && error->HasBadElems() )
1823 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1824 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1826 // get nodes of elements and count elements
1827 TNode2LocalIDMap mapNode2LocalID;
1828 list< TNodeLocalID > connectivity;
1829 int i, nbElements = 0, nbConnNodes = 0;
1831 const list<const SMDS_MeshElement*>& badElems =
1832 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1833 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1834 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1835 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1837 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1838 while ( nIt->more() )
1839 connectivity.push_back
1840 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1842 // fill node coords and assign local ids to the nodes
1843 int nbNodes = mapNode2LocalID.size();
1844 result->nodesXYZ.length( nbNodes );
1845 TNodeLocalID node2ID = mapNode2LocalID.begin();
1846 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1847 node2ID->second = i;
1848 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1849 result->nodesXYZ[i].x = node->X();
1850 result->nodesXYZ[i].y = node->Y();
1851 result->nodesXYZ[i].z = node->Z();
1853 // fill connectivity
1854 result->elementConnectivities.length( nbConnNodes );
1855 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1856 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1857 result->elementConnectivities[i] = (*connIt)->second;
1859 // fill element types
1860 result->elementTypes.length( nbElements );
1861 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1863 const SMDS_MeshElement* elem = *elemIt;
1864 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1865 result->elementTypes[i].isPoly = elem->IsPoly();
1866 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1872 catch ( SALOME_Exception& S_ex ) {
1873 INFOS( "catch exception "<< S_ex.what() );
1876 return result._retn();
1879 //================================================================================
1881 * \brief Create a group of elements preventing computation of a sub-shape
1883 //================================================================================
1885 SMESH::ListOfGroups*
1886 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1887 CORBA::Short theSubShapeID,
1888 const char* theGroupName )
1890 Unexpect aCatch(SALOME_SalomeException);
1892 SMESH::ListOfGroups_var groups;
1894 if ( CORBA::is_nil( theMesh ) )
1895 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1898 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1900 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1901 TPythonDump() << groups << " = " << this
1902 << ".MakeGroupsOfBadInputElements( "
1903 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1906 catch ( SALOME_Exception& S_ex ) {
1907 INFOS( "catch exception "<< S_ex.what() );
1909 return groups._retn();
1912 //================================================================================
1914 * \brief Returns errors of hypotheses definition
1915 * \param theMesh - the mesh
1916 * \param theSubObject - the main or sub- shape
1917 * \retval SMESH::algo_error_array* - sequence of errors
1919 //================================================================================
1921 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1922 GEOM::GEOM_Object_ptr theSubObject )
1924 Unexpect aCatch(SALOME_SalomeException);
1925 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1927 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1928 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1930 if ( CORBA::is_nil( theMesh ) )
1931 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1933 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1935 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1936 ASSERT( meshServant );
1937 if ( meshServant ) {
1938 TopoDS_Shape myLocShape;
1939 if(theMesh->HasShapeToMesh())
1940 myLocShape = GeomObjectToShape( theSubObject );
1942 myLocShape = SMESH_Mesh::PseudoShape();
1944 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1945 list< ::SMESH_Gen::TAlgoStateError > error_list;
1946 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1947 // call ::SMESH_Gen::GetAlgoState()
1948 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1949 error_array->length( error_list.size() );
1951 for ( error = error_list.begin(); error != error_list.end(); ++error )
1953 // fill AlgoStateError structure
1954 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1955 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1956 errStruct.algoDim = error->_algoDim;
1957 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1958 errStruct.algoName = "";
1959 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1960 if ( !algoSO->_is_nil() ) {
1961 CORBA::String_var algoName = algoSO->GetName();
1962 errStruct.algoName = algoName.in();
1967 catch ( SALOME_Exception& S_ex ) {
1968 INFOS( "catch exception "<< S_ex.what() );
1970 return error_array._retn();
1973 //=============================================================================
1975 * SMESH_Gen_i::GetSubShapesId
1977 * Get sub-shapes unique ID's list
1979 //=============================================================================
1982 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1983 const SMESH::object_array& theListOfSubShapeObject )
1985 Unexpect aCatch(SALOME_SalomeException);
1986 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1988 SMESH::long_array_var shapesId = new SMESH::long_array;
1991 if ( CORBA::is_nil( theMainShapeObject ) )
1992 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1996 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1997 TopTools_IndexedMapOfShape myIndexToShape;
1998 TopExp::MapShapes(myMainShape,myIndexToShape);
2000 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
2002 GEOM::GEOM_Object_var aShapeObject
2003 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
2004 if ( CORBA::is_nil( aShapeObject ) )
2005 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
2006 SALOME::BAD_PARAM );
2008 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
2009 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2011 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2012 setId.insert(myIndexToShape.FindIndex(F));
2013 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2015 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2017 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2018 setId.insert(myIndexToShape.FindIndex(E));
2019 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2021 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2023 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2024 setId.insert(myIndexToShape.FindIndex(V));
2025 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2028 shapesId->length(setId.size());
2029 set<int>::iterator iind;
2031 for (iind = setId.begin(); iind != setId.end(); iind++)
2033 if(MYDEBUG) SCRUTE((*iind));
2034 shapesId[i] = (*iind);
2035 if(MYDEBUG) SCRUTE(shapesId[i]);
2039 catch (SALOME_Exception& S_ex)
2041 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2044 return shapesId._retn();
2047 //=============================================================================
2049 * SMESH_Gen_i::Compute
2051 * Compute mesh on a shape
2053 //=============================================================================
2055 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2056 GEOM::GEOM_Object_ptr theShapeObject )
2059 Unexpect aCatch(SALOME_SalomeException);
2060 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2062 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2063 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2064 SALOME::BAD_PARAM );
2066 if ( CORBA::is_nil( theMesh ) )
2067 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2068 SALOME::BAD_PARAM );
2070 // Update Python script
2071 TPythonDump() << "isDone = " << this << ".Compute( "
2072 << theMesh << ", " << theShapeObject << ")";
2076 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2077 ASSERT( meshServant );
2078 if ( meshServant ) {
2079 if ( isGeomModifIcon( theMesh ))
2080 meshServant->Clear();
2082 meshServant->Load();
2083 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2084 meshServant->CheckGeomModif();
2085 // get local TopoDS_Shape
2086 TopoDS_Shape myLocShape;
2087 if(theMesh->HasShapeToMesh())
2088 myLocShape = GeomObjectToShape( theShapeObject );
2090 myLocShape = SMESH_Mesh::PseudoShape();
2091 // call implementation compute
2092 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2093 myGen.PrepareCompute( myLocMesh, myLocShape );
2094 int how = ::SMESH_Gen::COMPACT_MESH;
2095 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2096 how |= ::SMESH_Gen::SHAPE_ONLY;
2097 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2098 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2099 myLocMesh.GetMeshDS()->Modified();
2100 UpdateIcons( theMesh );
2102 HighLightInvalid( theMesh, /*isInvalid=*/false );
2106 catch ( std::bad_alloc& ) {
2107 INFOS( "Compute(): lack of memory" );
2109 catch ( SALOME_Exception& S_ex ) {
2110 INFOS( "Compute(): catch exception "<< S_ex.what() );
2113 INFOS( "Compute(): unknown exception " );
2118 //=============================================================================
2120 * SMESH_Gen_i::CancelCompute
2122 * Cancel Compute mesh on a shape
2124 //=============================================================================
2126 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2127 GEOM::GEOM_Object_ptr theShapeObject )
2129 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2131 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2132 TopoDS_Shape myLocShape;
2133 if(theMesh->HasShapeToMesh())
2134 myLocShape = GeomObjectToShape( theShapeObject );
2136 myLocShape = SMESH_Mesh::PseudoShape();
2137 myGen.CancelCompute( myLocMesh, myLocShape);
2141 //=============================================================================
2143 * SMESH_Gen_i::Precompute
2145 * Compute mesh as preview till indicated dimension on shape
2147 //=============================================================================
2149 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2150 GEOM::GEOM_Object_ptr theShapeObject,
2151 SMESH::Dimension theDimension,
2152 SMESH::long_array& theShapesId)
2154 Unexpect aCatch(SALOME_SalomeException);
2155 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2157 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2158 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2159 SALOME::BAD_PARAM );
2161 if ( CORBA::is_nil( theMesh ) )
2162 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2163 SALOME::BAD_PARAM );
2165 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2168 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2169 meshServant->Load();
2170 ASSERT( meshServant );
2171 if ( meshServant ) {
2172 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2173 meshServant->CheckGeomModif();
2174 // get local TopoDS_Shape
2175 TopoDS_Shape myLocShape;
2176 if(theMesh->HasShapeToMesh())
2177 myLocShape = GeomObjectToShape( theShapeObject );
2179 return result._retn();
2181 // call implementation compute
2182 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2184 ::MeshDimension aDim = (MeshDimension)theDimension;
2185 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2187 int nbShapeId = shapeIds.size();
2188 theShapesId.length( nbShapeId );
2189 // iterates on shapes and collect mesh entities into mesh preview
2190 TSetOfInt::const_iterator idIt = shapeIds.begin();
2191 TSetOfInt::const_iterator idEnd = shapeIds.end();
2192 std::map< int, int > mapOfShIdNb;
2193 std::set< SMESH_TLink > setOfEdge;
2194 std::list< SMDSAbs_ElementType > listOfElemType;
2195 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2196 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2197 TNode2LocalIDMap mapNode2LocalID;
2198 list< TNodeLocalID > connectivity;
2199 int i, nbConnNodes = 0;
2200 std::set< const SMESH_subMesh* > setOfVSubMesh;
2201 // iterates on shapes
2202 for ( ; idIt != idEnd; idIt++ )
2204 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2206 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2207 if ( !sm || !sm->IsMeshComputed() )
2210 const TopoDS_Shape& aSh = sm->GetSubShape();
2211 const int shDim = myGen.GetShapeDim( aSh );
2212 if ( shDim < 1 || shDim > theDimension )
2215 mapOfShIdNb[ *idIt ] = 0;
2216 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2218 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2219 if ( !smDS ) continue;
2221 if ( theDimension == SMESH::DIM_2D )
2223 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2224 while ( faceIt->more() )
2226 const SMDS_MeshElement* face = faceIt->next();
2227 int aNbNode = face->NbNodes();
2229 aNbNode /= 2; // do not take into account additional middle nodes
2231 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2232 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2234 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2235 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2237 listOfElemType.push_back( SMDSAbs_Edge );
2238 connectivity.push_back
2239 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2240 connectivity.push_back
2241 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2247 else if ( theDimension == SMESH::DIM_1D )
2249 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2250 while ( nodeIt->more() )
2252 listOfElemType.push_back( SMDSAbs_Node );
2253 connectivity.push_back
2254 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2256 // add corner nodes by first vertex from edge
2257 SMESH_subMeshIteratorPtr edgeSmIt =
2258 sm->getDependsOnIterator(/*includeSelf*/false,
2259 /*complexShapeFirst*/false);
2260 while ( edgeSmIt->more() )
2262 SMESH_subMesh* vertexSM = edgeSmIt->next();
2263 // check that vertex is not already treated
2264 if ( !setOfVSubMesh.insert( vertexSM ).second )
2266 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2269 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2270 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2271 while ( nodeIt->more() )
2273 listOfElemType.push_back( SMDSAbs_Node );
2274 connectivity.push_back
2275 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2281 // fill node coords and assign local ids to the nodes
2282 int nbNodes = mapNode2LocalID.size();
2283 result->nodesXYZ.length( nbNodes );
2284 TNodeLocalID node2ID = mapNode2LocalID.begin();
2285 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2286 node2ID->second = i;
2287 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2288 result->nodesXYZ[i].x = node->X();
2289 result->nodesXYZ[i].y = node->Y();
2290 result->nodesXYZ[i].z = node->Z();
2292 // fill connectivity
2293 result->elementConnectivities.length( nbConnNodes );
2294 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2295 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2296 result->elementConnectivities[i] = (*connIt)->second;
2299 // fill element types
2300 result->elementTypes.length( listOfElemType.size() );
2301 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2302 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2303 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2305 SMDSAbs_ElementType elemType = *typeIt;
2306 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2307 result->elementTypes[i].isPoly = false;
2308 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2311 // correct number of shapes
2312 theShapesId.length( mapOfShIdNb.size() );
2316 catch ( std::bad_alloc& ) {
2317 INFOS( "Precompute(): lack of memory" );
2319 catch ( SALOME_Exception& S_ex ) {
2320 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2323 INFOS( "Precompute(): unknown exception " );
2325 return result._retn();
2329 //=============================================================================
2331 * SMESH_Gen_i::Evaluate
2333 * Evaluate mesh on a shape
2335 //=============================================================================
2337 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2338 GEOM::GEOM_Object_ptr theShapeObject)
2339 // SMESH::long_array& theNbElems)
2341 Unexpect aCatch(SALOME_SalomeException);
2342 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2344 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2345 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2347 if ( CORBA::is_nil( theMesh ) )
2348 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2350 SMESH::long_array_var nbels = new SMESH::long_array;
2351 nbels->length(SMESH::Entity_Last);
2352 int i = SMESH::Entity_Node;
2353 for (; i < SMESH::Entity_Last; i++)
2356 // Update Python script
2357 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2358 << theMesh << ", " << theShapeObject << ")";
2362 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2363 ASSERT( meshServant );
2364 if ( meshServant ) {
2365 meshServant->Load();
2366 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2367 meshServant->CheckGeomModif();
2368 // get local TopoDS_Shape
2369 TopoDS_Shape myLocShape;
2370 if(theMesh->HasShapeToMesh())
2371 myLocShape = GeomObjectToShape( theShapeObject );
2373 myLocShape = SMESH_Mesh::PseudoShape();
2374 // call implementation compute
2375 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2376 MapShapeNbElems aResMap;
2377 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2378 MapShapeNbElemsItr anIt = aResMap.begin();
2379 for(; anIt!=aResMap.end(); anIt++) {
2380 const vector<int>& aVec = (*anIt).second;
2381 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2382 int nbElem = aVec[i];
2383 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2385 SMESH_subMesh* sm = anIt->first;
2386 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2387 const SMESH_Algo* algo = sm->GetAlgo();
2388 if ( (algo && !error.get()) || error->IsOK() )
2389 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2393 nbels[i] += aVec[i];
2397 return nbels._retn();
2400 catch ( std::bad_alloc& ) {
2401 INFOS( "Evaluate(): lack of memory" );
2403 catch ( SALOME_Exception& S_ex ) {
2404 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2407 INFOS( "Evaluate(): unknown exception " );
2410 return nbels._retn();
2413 //================================================================================
2415 * \brief Return geometrical object the given element is built on
2416 * \param theMesh - the mesh the element is in
2417 * \param theElementID - the element ID
2418 * \param theGeomName - the name of the result geom object if it is not yet published
2419 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2421 //================================================================================
2423 GEOM::GEOM_Object_ptr
2424 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2425 CORBA::Long theElementID,
2426 const char* theGeomName)
2428 Unexpect aCatch(SALOME_SalomeException);
2430 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2431 if ( !geom->_is_nil() ) {
2432 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2433 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2435 // try to find the corresponding SObject
2436 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2437 if ( SObj->_is_nil() ) // submesh can be not found even if published
2439 // try to find published submesh
2440 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2441 if ( !geom->IsMainShape() && list->length() == 1 ) {
2442 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2443 SALOMEDS::ChildIterator_wrap it;
2444 if ( !mainSO->_is_nil() ) {
2445 it = getStudyServant()->NewChildIterator( mainSO );
2447 if ( !it->_is_nil() ) {
2448 for ( it->InitEx(true); it->More(); it->Next() ) {
2449 SALOMEDS::SObject_wrap so = it->Value();
2450 CORBA::Object_var obj = SObjectToObject( so );
2451 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2452 if ( !subGeom->_is_nil() ) {
2453 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2454 if ( subList->length() == 1 && list[0] == subList[0] ) {
2464 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2465 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2467 // return only published geometry
2468 if ( !SObj->_is_nil() ) {
2469 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2470 CORBA::Object_var obj = SObjectToObject( SObj );
2471 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2475 return GEOM::GEOM_Object::_nil();
2478 //================================================================================
2480 * \brief Return geometrical object the given element is built on.
2481 * \param theMesh - the mesh the element is in
2482 * \param theElementID - the element ID
2483 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2485 //================================================================================
2487 GEOM::GEOM_Object_ptr
2488 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2489 CORBA::Long theElementID)
2491 Unexpect aCatch(SALOME_SalomeException);
2492 if ( CORBA::is_nil( theMesh ) )
2493 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2495 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2496 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2498 // get a core mesh DS
2499 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2500 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2502 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2503 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2504 // find the element in mesh
2505 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2506 // find a shape id by the element
2507 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2508 // get a geom object by the shape id
2509 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2510 if ( geom->_is_nil() ) {
2511 // try to find a published sub-shape
2512 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2513 SALOMEDS::ChildIterator_wrap it;
2514 if ( !mainSO->_is_nil() ) {
2515 it = getStudyServant()->NewChildIterator( mainSO );
2517 if ( !it->_is_nil() ) {
2518 for ( it->InitEx(true); it->More(); it->Next() ) {
2519 SALOMEDS::SObject_wrap so = it->Value();
2520 CORBA::Object_var obj = SObjectToObject( so );
2521 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2522 if ( !subGeom->_is_nil() ) {
2523 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2524 if ( subList->length() == 1 && shapeID == subList[0] ) {
2532 if ( geom->_is_nil() ) {
2534 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2535 if ( !op->_is_nil() )
2536 geom = op->GetSubShape( mainShape, shapeID );
2541 if ( !geom->_is_nil() ) {
2542 GeomObjectToShape( geom ); // let geom client remember the found shape
2543 return geom._retn();
2548 return GEOM::GEOM_Object::_nil();
2551 //================================================================================
2553 * SMESH_Gen_i::Concatenate
2555 * Concatenate the given meshes into one mesh
2557 //================================================================================
2559 SMESH::SMESH_Mesh_ptr
2560 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2561 CORBA::Boolean theUniteIdenticalGroups,
2562 CORBA::Boolean theMergeNodesAndElements,
2563 CORBA::Double theMergeTolerance,
2564 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2566 return ConcatenateCommon(theMeshesArray,
2567 theUniteIdenticalGroups,
2568 theMergeNodesAndElements,
2574 //================================================================================
2576 * SMESH_Gen_i::ConcatenateWithGroups
2578 * Concatenate the given meshes into one mesh
2579 * Create the groups of all elements from initial meshes
2581 //================================================================================
2583 SMESH::SMESH_Mesh_ptr
2584 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2585 CORBA::Boolean theUniteIdenticalGroups,
2586 CORBA::Boolean theMergeNodesAndElements,
2587 CORBA::Double theMergeTolerance,
2588 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2590 return ConcatenateCommon(theMeshesArray,
2591 theUniteIdenticalGroups,
2592 theMergeNodesAndElements,
2598 //================================================================================
2600 * SMESH_Gen_i::ConcatenateCommon
2602 * Concatenate the given meshes into one mesh
2604 //================================================================================
2606 SMESH::SMESH_Mesh_ptr
2607 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2608 CORBA::Boolean theUniteIdenticalGroups,
2609 CORBA::Boolean theMergeNodesAndElements,
2610 CORBA::Double theMergeTolerance,
2611 CORBA::Boolean theCommonGroups,
2612 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2614 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2615 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2617 // create mesh if theMeshToAppendTo not provided
2618 SMESH::SMESH_Mesh_var newMesh;
2619 if ( CORBA::is_nil( theMeshToAppendTo ))
2620 newMesh = CreateEmptyMesh();
2622 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2623 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2624 if ( !newImpl ) return newMesh._retn();
2627 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2628 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2630 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2631 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2632 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2633 TGroupsMap groupsMap;
2634 TListOfNewGroups listOfNewGroups;
2636 if ( !CORBA::is_nil( theMeshToAppendTo ))
2638 // fill groupsMap with existing groups
2639 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2640 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2642 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2643 if ( !group->_is_nil() )
2645 CORBA::String_var name = group->GetName();
2646 SMESH::ElementType type = group->GetType();
2647 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2652 ::SMESH_MeshEditor newEditor( &locMesh );
2653 ::SMESH_MeshEditor::ElemFeatures elemType;
2655 // loop on sub-meshes
2656 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2658 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2659 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2660 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2661 if ( !initImpl ) continue;
2662 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2666 // assure that IDs increment by one during iteration
2667 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2668 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2669 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2670 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2672 initMeshDS->Modified();
2673 initMeshDS->CompactMesh();
2676 // remember nb of elements before filling in
2677 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2681 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2682 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2683 while ( elemIt->more() )
2685 SMESH_NodeXYZ node = elemIt->next();
2686 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2691 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2692 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2694 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2695 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2696 while ( elemIt->more() )
2698 const SMDS_MeshElement* elem = elemIt->next();
2699 elemType.myNodes.resize( elem->NbNodes() );
2701 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2702 for ( int k = 0; itNodes->more(); k++)
2704 const SMDS_MeshNode* node = itNodes->next();
2705 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2708 // creates a corresponding element on existent nodes in new mesh
2709 newElems[ elem->GetID() ] =
2710 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2712 newEditor.ClearLastCreated(); // forget the history
2715 // create groups of just added elements
2716 SMESH::SMESH_Group_var newGroup;
2717 SMESH::ElementType groupType;
2718 if ( theCommonGroups )
2721 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2722 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2723 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2724 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2727 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2729 for( groupType = SMESH::NODE;
2730 groupType < SMESH::NB_ELEMENT_TYPES;
2731 groupType = (SMESH::ElementType)( groupType + 1 ))
2733 if ( curState[ groupType ] <= prevState[ groupType ])
2734 continue; // no elements of groupType added from the i-th mesh
2736 // make a group name
2737 std::string groupName = "Gr";
2738 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2740 CORBA::String_var name = meshSO->GetName();
2744 groupName += typeNames[ groupType ];
2746 // make and fill a group
2747 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2748 std::vector< const SMDS_MeshElement* > & elemVec =
2749 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2750 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2752 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2754 for ( size_t j = 0; j < elemVec.size(); ++j )
2756 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2757 grpDS->Add( elemVec[j] );
2761 listOfNewGroups.clear();
2762 listOfNewGroups.push_back( newGroup );
2763 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2768 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2772 SMESH::SMESH_GroupBase_ptr group;
2773 CORBA::String_var groupName;
2774 SMESH::long_array_var newIDs = new SMESH::long_array();
2776 // loop on groups of a source mesh
2777 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2778 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2780 group = listOfGroups[iG];
2781 groupType = group->GetType();
2782 groupName = group->GetName();
2783 std::string name = groupName.in();
2785 // convert a list of IDs
2786 newIDs->length( group->Size() );
2787 std::vector< const SMDS_MeshElement* > & elemVec =
2788 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2789 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2791 while ( itGrElems->more() )
2793 const SMDS_MeshElement* elem = itGrElems->next();
2794 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2796 newIDs[ nbElems++ ] = newElem->GetID();
2798 newIDs->length( nbElems );
2800 // check that a current group name and type don't have identical ones in final mesh
2801 listOfNewGroups.clear();
2802 TNameAndType nameAndType( name, groupType );
2803 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2804 if ( anIter == groupsMap.end() )
2806 // add a new group in the mesh
2807 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2808 newGroup->Add( newIDs );
2810 listOfNewGroups.push_back( newGroup );
2811 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2813 else if ( theUniteIdenticalGroups )
2815 // unite identical groups
2816 TListOfNewGroups& aNewGroups = anIter->second;
2817 aNewGroups.front()->Add( newIDs );
2821 // rename identical groups
2822 newGroup = newImpl->CreateGroup( groupType, groupName );
2823 newGroup->Add( newIDs );
2825 TListOfNewGroups& newGroups = anIter->second;
2826 std::string newGroupName;
2827 if ( newGroups.size() == 1 )
2829 newGroupName = name + "_1";
2830 newGroups.front()->SetName( newGroupName.c_str() );
2832 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2833 newGroup->SetName( newGroupName.c_str() );
2834 newGroups.push_back( newGroup );
2837 } // if an IDSource is a mesh
2840 if ( theMergeNodesAndElements ) // merge nodes
2842 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2843 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2844 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2845 /*SeparateCornersAndMedium=*/ false );
2846 newEditor.MergeNodes( groupsOfNodes );
2848 newEditor.MergeEqualElements();
2851 // Update Python script
2852 pythonDump << newMesh << " = " << this
2853 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2854 << theMeshesArray << ", "
2855 << theUniteIdenticalGroups << ", "
2856 << theMergeNodesAndElements << ", "
2857 << TVar( theMergeTolerance ) << ", "
2858 << theMeshToAppendTo << " )";
2860 pPythonDump.reset(); // enable python dump from GetGroups()
2862 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2863 if ( !newMesh->_is_nil() )
2865 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2868 // IPAL21468 Change icon of compound because it need not be computed.
2869 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2870 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2872 newMeshDS->Modified();
2874 return newMesh._retn();
2877 //================================================================================
2879 * \brief Create a mesh by copying a part of another mesh
2880 * \param meshPart - a part of mesh to copy
2881 * \param toCopyGroups - to create in the new mesh groups
2882 * the copied elements belongs to
2883 * \param toKeepIDs - to preserve IDs of the copied elements or not
2884 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2886 //================================================================================
2888 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2889 const char* meshName,
2890 CORBA::Boolean toCopyGroups,
2891 CORBA::Boolean toKeepIDs)
2893 Unexpect aCatch(SALOME_SalomeException);
2895 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2896 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2898 // 1. Get source mesh
2900 if ( CORBA::is_nil( meshPart ))
2901 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2903 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2904 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2906 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2908 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2910 // 2. Make a new mesh
2912 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2913 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2915 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2916 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2917 if ( !meshSO->_is_nil() )
2919 SetName( meshSO, meshName, "Mesh" );
2920 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2922 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2923 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2924 ::SMESH_MeshEditor::ElemFeatures elemType;
2926 // 3. Get elements to copy
2928 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2929 TIDSortedElemSet srcElems;
2930 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2931 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2934 srcElemIt = srcMeshDS->elementsIterator();
2935 srcNodeIt = srcMeshDS->nodesIterator();
2939 SMESH::long_array_var ids = meshPart->GetIDs();
2940 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2942 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2943 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2944 srcElems.insert( elem );
2948 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2949 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2950 srcElems.insert( elem );
2952 if ( srcElems.empty() )
2953 return newMesh._retn();
2955 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2956 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2961 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2962 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2963 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2965 const SMDS_MeshNode *nSrc, *nTgt;
2966 vector< const SMDS_MeshNode* > nodes;
2967 while ( srcElemIt->more() )
2969 const SMDS_MeshElement * elem = srcElemIt->next();
2971 nodes.resize( elem->NbNodes());
2972 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2974 for ( iN = 0; nIt->more(); ++iN )
2976 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2977 nTgt = newMeshDS->FindNode( nSrc->GetID());
2979 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2984 for ( iN = 0; nIt->more(); ++iN )
2986 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2987 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2989 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2990 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2994 if ( elem->GetType() != SMDSAbs_Node )
2996 elemType.Init( elem, /*basicOnly=*/false );
2997 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2999 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3000 if ( toCopyGroups && !toKeepIDs )
3001 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3003 } // while ( srcElemIt->more() )
3005 // 4(b). Copy free nodes
3007 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3009 while ( srcNodeIt->more() )
3011 nSrc = srcNodeIt->next();
3012 if ( nSrc->NbInverseElements() == 0 )
3015 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3017 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3024 int nbNewGroups = 0;
3027 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3028 while ( gIt->more() )
3030 SMESH_Group* group = gIt->next();
3031 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3033 // Check group type. We copy nodal groups containing nodes of copied element
3034 SMDSAbs_ElementType groupType = groupDS->GetType();
3035 if ( groupType != SMDSAbs_Node &&
3036 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3037 continue; // group type differs from types of meshPart
3039 // Find copied elements in the group
3040 vector< const SMDS_MeshElement* > groupElems;
3041 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3044 const SMDS_MeshElement* foundElem;
3045 if ( groupType == SMDSAbs_Node )
3047 while ( eIt->more() )
3048 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3049 groupElems.push_back( foundElem );
3053 while ( eIt->more() )
3054 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3055 groupElems.push_back( foundElem );
3060 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3061 if ( e2eMap.empty() ) continue;
3062 int minID = e2eMap.begin()->first->GetID();
3063 int maxID = e2eMap.rbegin()->first->GetID();
3064 TE2EMap::iterator e2e;
3065 while ( eIt->more() && groupElems.size() < e2eMap.size())
3067 const SMDS_MeshElement* e = eIt->next();
3068 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3069 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3070 groupElems.push_back( e2e->second );
3074 if ( !groupElems.empty() )
3076 SMESH::SMESH_Group_var newGroupObj =
3077 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3078 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3080 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3081 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3082 for ( unsigned i = 0; i < groupElems.size(); ++i )
3083 smdsGroup.Add( groupElems[i] );
3091 newMeshDS->Modified();
3093 *pyDump << newMesh << " = " << this
3094 << ".CopyMesh( " << meshPart << ", "
3095 << "'" << meshName << "', "
3096 << toCopyGroups << ", "
3097 << toKeepIDs << ")";
3099 pyDumpDeleter.reset(); // allow dump in GetGroups()
3101 if ( nbNewGroups > 0 ) // dump created groups
3102 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3104 return newMesh._retn();
3108 namespace // utils for CopyMeshWithGeom()
3110 typedef std::map< std::string, std::string > TStr2StrMap;
3111 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3112 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3113 typedef std::map< std::string, int > TName2IndexMap;
3115 //================================================================================
3117 * \brief Return a new sub-shape corresponding to an old one
3119 //================================================================================
3123 SMESH_Mesh_i* mySrcMesh_i;
3124 SMESH_Mesh_i* myNewMesh_i;
3125 SMESH_Gen_i* myGen_i;
3129 TStr2StrMap myOld2NewEntryMap; // map of study entries
3131 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3132 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3133 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3136 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3138 // not directly relating to shape search
3139 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3141 //================================================================================
3143 * \brief Constructor
3145 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3146 SMESH_Mesh_i* newMesh_i,
3147 SMESH_Gen_i* smeshGen_i )
3148 : mySrcMesh_i( srcMesh_i ),
3149 myNewMesh_i( newMesh_i ),
3150 myGen_i ( smeshGen_i ),
3151 myToPublish( smeshGen_i->IsEnablePublish() ),
3152 myGIPMapDone( false )
3154 // retrieve from the study shape mapping made thanks to
3155 // "Set presentation parameters and sub-shapes from arguments" option
3157 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3158 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3159 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3160 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3161 if ( newSO->_is_nil() )
3163 myToPublish = false;
3166 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3168 CORBA::String_var oldEntry = oldSO->GetID();
3169 CORBA::String_var newEntry = newSO->GetID();
3170 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3171 std::string( newEntry.in() )));
3172 std::string newMainEntry = newEntry.in();
3174 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3175 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3176 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3177 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3178 /*groupsOnly=*/false );
3179 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3181 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3182 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3183 bool refFound = false;
3184 for ( ; anIter->More(); anIter->Next() )
3186 SALOMEDS::SObject_wrap so = anIter->Value();
3187 if ( so->ReferencedObject( oldSO.inout() ))
3189 oldEntry = oldSO->GetID();
3190 newEntry = newSO->GetID();
3191 if (( refFound = ( newMainEntry != oldEntry.in() )))
3192 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3193 std::string( newEntry.in() )));
3198 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3199 if ( father->_is_equivalent( mainShapeNew ))
3201 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3202 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3203 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3204 CORBA::String_var name = newSO->GetName();
3206 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3212 //================================================================================
3214 * \brief Find a new sub-shape corresponding to an old one
3216 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3219 return GEOM::GEOM_Object::_duplicate( oldShape );
3221 GEOM::GEOM_Object_var newShape;
3223 if ( CORBA::is_nil( oldShape ))
3224 return newShape._retn();
3226 if ( !isChildOfOld( oldShape ))
3227 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3229 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3230 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3232 // try to find by entry or name
3235 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3236 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3237 if ( o2nID != myOld2NewEntryMap.end() )
3239 newShape = getShapeByEntry( o2nID->second );
3241 if ( newShape->_is_nil() )
3243 CORBA::String_var name = oldShape->GetName();
3244 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3245 if ( n2ind != myName2SubshapeIndex.end() )
3247 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3248 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3249 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3250 if ( oldIndices->length() == 0 ||
3251 newIndices->length() == 0 ||
3252 getShapeType( myNewMesh_i, newIndices[0] ) !=
3253 getShapeType( mySrcMesh_i, oldIndices[0] ))
3254 newShape = GEOM::GEOM_Object::_nil();
3259 if ( newShape->_is_nil() )
3261 // try to construct a new sub-shape using myGIPMap
3263 std::vector< int > newIndices;
3264 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3265 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3267 findNewIDs( oldIndices[i], newIndices );
3269 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3272 newShape = getInPlace( oldShape );
3274 if ( !newIndices.empty() && newShape->_is_nil() )
3276 // search for a sub-shape with same ids
3277 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3278 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3279 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3280 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3282 if ( newShape->_is_nil() )
3285 // create a new shape
3286 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3288 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3290 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3291 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3293 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3294 newIndicesList->length( newIndices.size() );
3295 for ( size_t i = 0; i < newIndices.size(); ++i )
3296 newIndicesList[ i ] = newIndices[ i ];
3297 grOp->UnionIDs( newShape, newIndicesList );
3301 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3302 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3311 if ( !newShape->_is_nil() && myToPublish )
3313 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3314 if ( !newEntry.in() || !newEntry.in()[0] )
3316 CORBA::String_var name = oldShape->GetName();
3317 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3318 newEntry = newShape->GetStudyEntry();
3319 oldEntry = oldShape->GetStudyEntry();
3320 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3321 std::string( newEntry.in() )));
3325 return newShape._retn();
3328 //================================================================================
3330 * \brief Return a study entry of a new shape by study entry of the old one
3332 std::string FindNew( const std::string & oldEntry )
3337 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3338 if ( o2nID != myOld2NewEntryMap.end() )
3339 return o2nID->second;
3341 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3342 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3345 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3346 if ( newShape->_is_nil() )
3347 return std::string();
3349 CORBA::String_var newEntry = newShape->GetStudyEntry();
3350 return newEntry.in();
3353 //================================================================================
3355 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3356 * Return zero if not found or there are more than one new ID
3358 int FindNew( int oldID )
3367 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3369 if ( myGIPMap[ oldID ].length() == 1 )
3371 newID = myGIPMap[ oldID ][ 0 ];
3373 else if ( myGIPMap[ oldID ].length() > 1 &&
3374 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3376 // select a meshed VERTEX
3377 SMESH_subMesh* newSM;
3378 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3379 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3380 ( !newSM->IsEmpty() ))
3381 newID = myGIPMap[ oldID ][ i ];
3387 //================================================================================
3389 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3390 * Return zero if the old shape is not kept as is in the new shape.
3392 int FindNewNotChanged( SMESH_subMesh* oldSM )
3395 return oldSM->GetId();
3397 int newID = FindNew( oldSM->GetId() );
3401 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3405 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3406 // one new sub-shape of the same type.
3408 if ( oldSM->DependsOn().size() !=
3409 newSM->DependsOn().size() )
3412 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3413 while ( srcSMIt->more() )
3415 oldSM = srcSMIt->next();
3416 int newSubID = FindNew( oldSM->GetId() );
3417 if ( getShapeType( myNewMesh_i, newSubID ) !=
3418 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3424 //================================================================================
3426 * \brief Return shape by study entry
3428 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3430 GEOM::GEOM_Object_var shape;
3431 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3432 if ( !so->_is_nil() )
3434 CORBA::Object_var obj = so->GetObject();
3435 shape = GEOM::GEOM_Object::_narrow( obj );
3437 return shape._retn();
3440 //================================================================================
3442 * \brief Fill myGIPMap by calling GetInPlaceMap()
3446 if ( !myGIPMapDone )
3448 myGIPMapDone = true;
3450 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3451 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3452 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3453 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3456 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3460 myGIPMap = new GEOM::ListOfListOfLong();
3465 //================================================================================
3467 * \brief Get new sub-shape by calling GetInPlace()
3469 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3471 GEOM::GEOM_Object_var newShape;
3473 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3474 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3475 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3478 newShape = op->GetInPlace( mainShapeNew, oldShape );
3483 return newShape._retn();
3486 //================================================================================
3488 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3489 * number of found IDs
3491 int findNewIDs( int oldID, std::vector< int >& newIDs )
3493 size_t prevNbIDs = newIDs.size();
3495 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3497 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3498 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3500 return newIDs.size() - prevNbIDs;
3503 //================================================================================
3505 * \brief Check if an object relates to the old shape
3507 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3509 if ( CORBA::is_nil( oldShape ))
3511 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3512 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3513 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3514 mainShapeOld1->_is_equivalent( oldShape ));
3517 //================================================================================
3519 * \brief Return shape type by shape ID
3521 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3523 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3524 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3525 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3528 //================================================================================
3530 * \brief Store a source sub-shape for which a counterpart not found and
3531 * a smesh object invalid due to that
3533 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3534 SALOMEDS::SObject_wrap smeshSO )
3536 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3537 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3539 CORBA::String_var smeshEntry = smeshSO->GetID();
3540 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3544 //================================================================================
3546 * \brief Store a source sub-shape for which a counterpart not found and
3547 * a smesh object invalid due to that
3549 void AddInvalid( std::string geomEntry,
3550 SALOMEDS::SObject_wrap smeshSO )
3552 if ( !geomEntry.empty() )
3554 CORBA::String_var smeshEntry = smeshSO->GetID();
3555 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3559 //================================================================================
3561 * \brief Store a source sub-shape for which a counterpart not found and
3562 * a smesh object invalid due to that
3564 void AddInvalid( int oldGeomID,
3565 SALOMEDS::SObject_wrap smeshSO )
3567 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3568 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3571 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3572 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3574 SMESH_Comment geomName( typeName[ shapeType ]);
3575 geomName << " #" << oldGeomID;
3577 CORBA::String_var smeshEntry = smeshSO->GetID();
3578 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3581 //================================================================================
3583 * \brief Return entries of a source sub-shape for which a counterpart not found and
3584 * of smesh objects invalid due to that
3586 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3587 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3590 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3591 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3593 nbSO += 1 + entry2entrySet->second.size();
3595 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3596 theInvalidEntries->length ( nbSO );
3597 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3599 entry2entrySet = myInvalidMap.begin();
3600 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3602 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3604 std::set< std::string > & entrySet = entry2entrySet->second;
3605 std::set< std::string >::iterator entry = entrySet.begin();
3606 for ( ; entry != entrySet.end(); ++entry )
3608 theInvalidEntries[ iEntry++ ] = entry->c_str();
3610 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3611 if ( !so->_is_nil() )
3612 theInvalidMeshSObjects[ iSO++ ] = so;
3617 }; // struct ShapeMapper
3619 //================================================================================
3621 * \brief Append an item to a CORBA sequence
3623 template < class CORBA_seq, class ITEM >
3624 void append( CORBA_seq& seq, ITEM item )
3626 if ( !CORBA::is_nil( item ))
3628 seq->length( 1 + seq->length() );
3629 seq[ seq->length() - 1 ] = item;
3632 } // namespace // utils for CopyMeshWithGeom()
3634 //================================================================================
3636 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3637 * \param [in] sourceMesh - a mesh to copy
3638 * \param [in] newGeometry - a new geometry
3639 * \param [in] toCopyGroups - to create groups in the new mesh
3640 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3641 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3642 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3643 * \param [out] newMesh - return a new mesh
3644 * \param [out] newGroups - return new groups
3645 * \param [out] newSubmeshes - return new sub-meshes
3646 * \param [out] newHypotheses - return new algorithms and hypotheses
3647 * \param [out] invalidEntries - return study entries of objects whose
3648 * counterparts are not found in the newGeometry, followed by entries
3649 * of mesh sub-objects that are invalid because they depend on a not found
3650 * preceding sub-shape
3651 * \return CORBA::Boolean - is a success
3653 //================================================================================
3655 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3656 GEOM::GEOM_Object_ptr theNewGeometry,
3657 const char* theMeshName,
3658 CORBA::Boolean theToCopyGroups,
3659 CORBA::Boolean theToReuseHypotheses,
3660 CORBA::Boolean theToCopyElements,
3661 SMESH::SMESH_Mesh_out theNewMesh,
3662 SMESH::ListOfGroups_out theNewGroups,
3663 SMESH::submesh_array_out theNewSubmeshes,
3664 SMESH::ListOfHypothesis_out theNewHypotheses,
3665 SMESH::string_array_out theInvalidEntries)
3667 if ( CORBA::is_nil( theSourceMesh ) ||
3668 CORBA::is_nil( theNewGeometry ))
3669 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3671 if ( !theSourceMesh->HasShapeToMesh() )
3672 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3677 TPythonDump pyDump; // prevent dump from CreateMesh()
3679 theNewMesh = CreateMesh( theNewGeometry );
3680 theNewGroups = new SMESH::ListOfGroups();
3681 theNewSubmeshes = new SMESH::submesh_array();
3682 theNewHypotheses = new SMESH::ListOfHypothesis();
3683 theInvalidEntries = new SMESH::string_array();
3685 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3687 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3688 GEOM::GEOM_Object_var geom, newGeom;
3689 SALOMEDS::SObject_wrap so;
3691 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3692 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3695 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3697 // treat hypotheses of mesh and sub-meshes
3698 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3699 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3701 bool isSubMesh = ( iSM < smList->length() );
3704 // create a new sub-mesh
3705 SMESH::SMESH_subMesh_var newSM;
3706 geom = smList[iSM]->GetSubShape();
3707 so = ObjectToSObject( smList[iSM] );
3708 CORBA::String_var name;
3709 if ( !so->_is_nil() )
3710 name = so->GetName();
3711 newGeom = shapeMapper.FindNew( geom );
3712 if ( newGeom->_is_nil() )
3714 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3715 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3720 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3722 append( theNewSubmeshes, newSM );
3724 if ( newGeom->_is_nil() )
3725 continue; // don't assign hypotheses
3729 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3731 so = ObjectToSObject( theNewMesh );
3732 SetName( so, theMeshName, "Mesh" );
3735 // assign hypotheses
3736 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3737 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3739 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3740 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3742 // get geometry hyp depends on
3743 std::vector< std::string > entryArray;
3744 std::vector< int > subIDArray;
3745 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3747 if ( !theToReuseHypotheses || dependsOnGeom )
3749 // create a new hypothesis
3750 CORBA::String_var type = hyp->GetName();
3751 CORBA::String_var lib = hyp->GetLibName();
3752 CORBA::String_var data = hyp_i->SaveTo();
3755 hyp = CreateHypothesis( type, lib );
3756 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3757 hyp_i->LoadFrom( data.in() );
3758 append( theNewHypotheses, hyp );
3762 // update geometry hyp depends on
3763 if ( dependsOnGeom )
3765 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3767 if ( !entryArray[ iGeo ].empty() )
3769 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3770 if ( newEntry.empty() )
3773 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3774 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3776 entryArray[ iGeo ] = newEntry;
3779 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3781 if ( subIDArray[ iGeo ] > 0 )
3783 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3787 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3788 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3790 subIDArray[ iGeo ] = newID;
3793 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3797 CORBA::String_var errorText;
3798 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3799 if ( errorText.in()[0] )
3802 } // loop on hypotheses
3803 } // loop on sub-meshes and mesh
3806 // copy mesh elements, keeping IDs
3807 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3808 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3810 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3811 ::SMESH_MeshEditor::ElemFeatures elemData;
3813 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3814 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3815 /*vertexLast=*/false);
3816 while ( srcSMIt->more() )
3818 SMESH_subMesh* srcSM = srcSMIt->next();
3819 if ( srcSM->IsEmpty() )
3820 continue; // not yet computed
3821 int newID = shapeMapper.FindNewNotChanged( srcSM );
3825 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3826 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3827 while ( nIt->more() )
3829 SMESH_NodeXYZ node( nIt->next() );
3830 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3832 const SMDS_PositionPtr pos = node->GetPosition();
3833 const double* uv = pos->GetParameters();
3834 switch ( pos->GetTypeOfPosition() )
3836 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3837 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3838 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3839 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3843 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3844 while( eIt->more() )
3846 const SMDS_MeshElement* e = eIt->next();
3847 elemData.Init( e, /*basicOnly=*/false );
3848 elemData.SetID( e->GetID() );
3849 elemData.myNodes.resize( e->NbNodes() );
3850 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3852 for ( iN = 0; nnIt->more(); ++iN )
3854 const SMDS_MeshNode* srcNode = nnIt->next();
3855 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3856 if ( !elemData.myNodes[ iN ])
3859 if ( iN == elemData.myNodes.size() )
3860 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3861 newMeshDS->SetMeshElementOnShape( newElem, newID );
3863 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3864 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3867 newMeshDS->Modified();
3873 TStr2StrMap old2newGroupMap;
3875 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3877 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3878 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3879 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3881 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3882 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3883 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3885 CORBA::String_var name = groups[ i ]->GetName();
3886 SMESH::ElementType elemType = groups[ i ]->GetType();
3888 SMESH::SMESH_GroupBase_var newGroup;
3890 if ( !stdlGroup->_is_nil() )
3892 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3894 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3895 const bool isElem = ( elemType != SMESH::NODE );
3896 CORBA::ULong iE = 0;
3897 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3898 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3900 if ( iE < elemIDs->length() )
3902 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3903 stdlGroup->Add( elemIDs );
3904 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3908 else if ( !geomGroup->_is_nil() )
3910 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3911 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3912 if ( newGeom->_is_nil() )
3914 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3915 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3920 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3923 else if ( !fltrGroup->_is_nil() )
3925 // replace geometry in a filter
3926 SMESH::Filter_var filter = fltrGroup->GetFilter();
3927 SMESH::Filter::Criteria_var criteria;
3928 filter->GetCriteria( criteria.out() );
3930 bool isMissingGroup = false;
3931 std::vector< std::string > badEntries;
3933 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3935 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3936 switch ( criteria[ iCr ].Type )
3938 case SMESH::FT_BelongToMeshGroup:
3940 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3941 btgg->SetGroupID( thresholdID );
3942 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3943 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3944 if ( refGroupSO->_is_nil() )
3946 CORBA::String_var refID = refGroupSO->GetID();
3947 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3948 if ( o2nID == old2newGroupMap.end() )
3950 isMissingGroup = true; // corresponding new group not yet created
3953 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3955 if ( o2nID->second.empty() ) // new referred group is invalid
3956 badEntries.push_back( refID.in() );
3959 case SMESH::FT_BelongToGeom:
3960 case SMESH::FT_BelongToPlane:
3961 case SMESH::FT_BelongToCylinder:
3962 case SMESH::FT_BelongToGenSurface:
3963 case SMESH::FT_LyingOnGeom:
3965 std::string newID = shapeMapper.FindNew( thresholdID );
3966 criteria[ iCr ].ThresholdID = newID.c_str();
3967 if ( newID.empty() )
3968 badEntries.push_back( thresholdID );
3971 case SMESH::FT_ConnectedElements:
3973 if ( thresholdID && thresholdID[0] )
3975 std::string newID = shapeMapper.FindNew( thresholdID );
3976 criteria[ iCr ].ThresholdID = newID.c_str();
3977 if ( newID.empty() )
3978 badEntries.push_back( thresholdID );
3984 } // loop on criteria
3986 if ( isMissingGroup && i < nbGroups )
3988 // to treat the group again
3989 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3993 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3994 newFilter->SetCriteria( criteria );
3996 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3997 newFilter->UnRegister();
3999 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4000 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4001 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4003 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4005 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4008 if ( !badEntries.empty() )
4011 } // treat a group on filter
4013 append( theNewGroups, newGroup );
4015 // fill old2newGroupMap
4016 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4017 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4018 if ( !srcSO->_is_nil() )
4020 CORBA::String_var srcID, newID("");
4021 srcID = srcSO->GetID();
4022 if ( !newSO->_is_nil() )
4023 newID = newSO->GetID();
4024 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4025 std::string( newID.in() )));
4028 if ( newGroup->_is_nil() )
4033 newMeshDS->CompactMesh();
4036 if ( !theMeshName || !theMeshName[0] )
4038 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4039 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4040 CORBA::String_var oldName = soOld->GetName();
4041 SetName( soNew, oldName.in(), "Mesh" );
4043 // mark invalid objects
4044 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4046 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4047 highLightInvalid( invalidSObjects[i].in(), true );
4050 << theNewMesh << ", "
4051 << theNewGroups << ", "
4052 << *theNewSubmeshes.ptr() << ", "
4053 << *theNewHypotheses.ptr() << ", "
4054 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4055 << theSourceMesh << ", "
4056 << theNewGeometry << ", "
4057 << "'" << theMeshName << "', "
4058 << theToCopyGroups << ", "
4059 << theToReuseHypotheses << ", "
4060 << theToCopyElements << " )";
4062 SMESH_CATCH( SMESH::throwCorbaException );
4067 //================================================================================
4069 * \brief Get version of MED format being used.
4071 //================================================================================
4073 char* SMESH_Gen_i::GetMEDFileVersion()
4075 MED::TInt majeur, mineur, release;
4076 majeur = mineur = release = 0;
4077 MED::GetVersionRelease(majeur, mineur, release);
4078 std::ostringstream version;
4079 version << majeur << "." << mineur << "." << release;
4080 return CORBA::string_dup( version.str().c_str() );
4083 //================================================================================
4085 * SMESH_Gen_i::GetMEDVersion
4087 * Get MED version of the file by its name
4089 //================================================================================
4091 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4093 std::string version = MED::GetMEDVersion( theFileName );
4094 return CORBA::string_dup( version.c_str() );
4097 //================================================================================
4099 * SMESH_Gen_i::CheckCompatibility
4101 * Check compatibility of file with MED format being used, read only.
4103 //================================================================================
4105 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4107 return MED::CheckCompatibility( theFileName );
4110 //================================================================================
4112 * SMESH_Gen_i::CheckWriteCompatibility
4114 * Check compatibility of file with MED format being used, for append on write.
4116 //================================================================================
4118 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4120 return MED::CheckCompatibility( theFileName, true );
4123 //================================================================================
4125 * SMESH_Gen_i::GetMeshNames
4127 * Get names of meshes defined in file with the specified name
4129 //================================================================================
4130 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4133 SMESH::string_array_var aResult = new SMESH::string_array();
4134 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4136 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4138 aResult->length( aNbMeshes );
4139 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4140 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4141 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4144 return aResult._retn();
4147 //=============================================================================
4151 * Save SMESH module's data
4153 //=============================================================================
4155 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4160 Kernel_Utils::Localizer loc;
4162 if (!myStudyContext)
4165 // Store study contents as a set of python commands
4168 SALOMEDS::Study_var aStudy = getStudyServant();
4170 // Declare a byte stream
4171 SALOMEDS::TMPFile_var aStreamFile;
4173 // Obtain a temporary dir
4174 TCollection_AsciiString tmpDir =
4175 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4177 // Create a sequence of files processed
4178 SALOMEDS_Tool::ListOfFiles aFileSeq;
4179 aFileSeq.reserve( NUM_TMP_FILES );
4181 TCollection_AsciiString aStudyName( "" );
4183 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4185 // Set names of temporary files
4186 TCollection_AsciiString filename =
4187 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4188 TCollection_AsciiString meshfile =
4189 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4190 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4191 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4192 filename = tmpDir + filename;
4193 meshfile = tmpDir + meshfile;
4196 HDFdataset* aDataset;
4197 HDFgroup* aTopGroup;
4199 HDFgroup* aSubGroup;
4200 HDFgroup* aSubSubGroup;
4201 hdf_size aSize[ 1 ];
4204 //Remove the files if they exist: BugID: 11225
4205 #ifndef WIN32 /* unix functionality */
4206 TCollection_AsciiString cmd("rm -f \"");
4208 TCollection_AsciiString cmd("del /F \"");
4218 system(cmd.ToCString());
4220 // MED writer to be used by storage process
4221 DriverMED_W_SMESHDS_Mesh myWriter;
4222 myWriter.SetFile( meshfile.ToCString() );
4225 // SetStoreName() to groups before storing hypotheses to let them refer to
4226 // groups using "store name", which is "Group <group_persistent_id>"
4228 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4229 for ( ; itBig->More(); itBig->Next() ) {
4230 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4231 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4232 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4233 if ( !CORBA::is_nil( anObject ) ) {
4234 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4235 if ( !myMesh->_is_nil() ) {
4236 myMesh->Load(); // load from study file if not yet done
4237 TPythonDump pd; // not to dump GetGroups()
4238 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4239 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4241 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4244 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4245 int anId = myStudyContext->findId( string( objStr.in() ) );
4247 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4248 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4249 aGrpBaseDS->SetStoreName( grpName );
4259 // ---> create HDF file
4260 aFile = new HDFfile( (char*) filename.ToCString() );
4261 aFile->CreateOnDisk();
4263 // --> iterator for top-level objects
4264 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4265 for ( ; itBig->More(); itBig->Next() ) {
4266 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4268 // --> hypotheses root branch (only one for the study)
4269 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4270 // create hypotheses root HDF group
4271 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4272 aTopGroup->CreateOnDisk();
4274 // iterator for all hypotheses
4275 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4276 for ( ; it->More(); it->Next() ) {
4277 SALOMEDS::SObject_wrap mySObject = it->Value();
4278 CORBA::Object_var anObject = SObjectToObject( mySObject );
4279 if ( !CORBA::is_nil( anObject ) ) {
4280 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4281 if ( !myHyp->_is_nil() ) {
4282 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4284 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4285 std::string hypname = hn.in();
4286 std::string libname = ln.in();
4288 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4289 // WIN32 and ".so" for X-system) must be deleted
4290 int libname_len = libname.length();
4292 if( libname_len > 4 )
4293 libname.resize( libname_len - 4 );
4295 // PAL17753 (Regression: missing hypothesis in restored study)
4296 // "lib" also should be removed from the beginning
4297 if( libname_len > 6 )
4298 libname = libname.substr( 3, libname_len - 3 - 3 );
4300 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4301 CORBA::String_var hypdata = myImpl->SaveTo();
4302 int id = myStudyContext->findId( string( objStr.in() ));
4304 // for each hypothesis create HDF group basing on its id
4305 char hypGrpName[30];
4306 sprintf( hypGrpName, "Hypothesis %d", id );
4307 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4308 aGroup->CreateOnDisk();
4309 // --> type name of hypothesis
4310 aSize[ 0 ] = hypname.length() + 1;
4311 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4312 aDataset->CreateOnDisk();
4313 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4314 aDataset->CloseOnDisk();
4315 // --> server plugin library name of hypothesis
4316 aSize[ 0 ] = libname.length() + 1;
4317 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4318 aDataset->CreateOnDisk();
4319 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4320 aDataset->CloseOnDisk();
4321 // --> persistent data of hypothesis
4322 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4323 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4324 aDataset->CreateOnDisk();
4325 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4326 aDataset->CloseOnDisk();
4327 // close hypothesis HDF group
4328 aGroup->CloseOnDisk();
4333 // close hypotheses root HDF group
4334 aTopGroup->CloseOnDisk();
4336 // --> algorithms root branch (only one for the study)
4337 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4338 // create algorithms root HDF group
4339 aTopGroup = new HDFgroup( "Algorithms", aFile );
4340 aTopGroup->CreateOnDisk();
4342 // iterator for all algorithms
4343 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4344 for ( ; it->More(); it->Next() ) {
4345 SALOMEDS::SObject_wrap mySObject = it->Value();
4346 CORBA::Object_var anObject = SObjectToObject( mySObject );
4347 if ( !CORBA::is_nil( anObject ) ) {
4348 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4349 if ( !myHyp->_is_nil() ) {
4350 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4352 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4353 std::string hypname = hn.in();
4354 std::string libname = ln.in();
4356 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4357 // WIN32 and ".so" for X-system) must be deleted
4358 int libname_len = libname.length();
4360 if( libname_len > 4 )
4361 libname.resize( libname_len - 4 );
4363 // PAL17753 (Regression: missing hypothesis in restored study)
4364 // "lib" also should be removed from the beginning
4365 if( libname_len > 6 )
4366 libname = libname.substr( 3, libname_len - 3 - 3 );
4368 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4369 CORBA::String_var hypdata = myImpl->SaveTo();
4370 int id = myStudyContext->findId( string( objStr.in() ) );
4372 // for each algorithm create HDF group basing on its id
4373 char hypGrpName[30];
4374 sprintf( hypGrpName, "Algorithm %d", id );
4375 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4376 aGroup->CreateOnDisk();
4377 // --> type name of algorithm
4378 aSize[0] = hypname.length() + 1;
4379 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4380 aDataset->CreateOnDisk();
4381 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4382 aDataset->CloseOnDisk();
4383 // --> server plugin library name of hypothesis
4384 aSize[0] = libname.length() + 1;
4385 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4386 aDataset->CreateOnDisk();
4387 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4388 aDataset->CloseOnDisk();
4389 // --> persistent data of algorithm
4390 aSize[0] = strlen( hypdata.in() ) + 1;
4391 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4392 aDataset->CreateOnDisk();
4393 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4394 aDataset->CloseOnDisk();
4395 // close algorithm HDF group
4396 aGroup->CloseOnDisk();
4401 // close algorithms root HDF group
4402 aTopGroup->CloseOnDisk();
4404 // --> mesh objects roots branches
4405 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4406 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4407 if ( !CORBA::is_nil( anObject ) ) {
4408 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4409 if ( !myMesh->_is_nil() ) {
4410 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4412 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4413 int id = myStudyContext->findId( string( objStr.in() ) );
4414 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4415 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4416 bool hasShape = myLocMesh.HasShapeToMesh();
4418 // for each mesh open the HDF group basing on its id
4419 char meshGrpName[ 30 ];
4420 sprintf( meshGrpName, "Mesh %d", id );
4421 aTopGroup = new HDFgroup( meshGrpName, aFile );
4422 aTopGroup->CreateOnDisk();
4424 // --> put dataset to hdf file which is a flag that mesh has data
4425 string strHasData = "0";
4426 // check if the mesh is not empty
4427 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4428 // write mesh data to med file
4429 myWriter.SetMesh( mySMESHDSMesh );
4430 myWriter.SetMeshId( id );
4433 aSize[ 0 ] = strHasData.length() + 1;
4434 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4435 aDataset->CreateOnDisk();
4436 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4437 aDataset->CloseOnDisk();
4440 // for each mesh open the HDF group basing on its auto color parameter
4441 char meshAutoColorName[ 30 ];
4442 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4444 anAutoColor[0] = myImpl->GetAutoColor();
4446 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4447 aDataset->CreateOnDisk();
4448 aDataset->WriteOnDisk( anAutoColor );
4449 aDataset->CloseOnDisk();
4451 // issue 0020693. Store _isModified flag
4452 int isModified = myLocMesh.GetIsModified();
4454 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4455 aDataset->CreateOnDisk();
4456 aDataset->WriteOnDisk( &isModified );
4457 aDataset->CloseOnDisk();
4459 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4460 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4462 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4463 aDataset->CreateOnDisk();
4464 aDataset->WriteOnDisk( &meshPersistentId );
4465 aDataset->CloseOnDisk();
4467 // Store SMESH_Mesh_i::_mainShapeTick
4468 int shapeTick = myImpl->MainShapeTick();
4470 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4471 aDataset->CreateOnDisk();
4472 aDataset->WriteOnDisk( &shapeTick );
4473 aDataset->CloseOnDisk();
4475 // write reference on a shape if exists
4476 SALOMEDS::SObject_wrap myRef;
4477 bool shapeRefFound = false;
4478 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4480 SALOMEDS::SObject_wrap myShape;
4481 bool ok = myRef->ReferencedObject( myShape.inout() );
4483 CORBA::Object_var shapeObj = myShape->GetObject();
4484 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4485 CORBA::String_var myRefOnObject = myShape->GetID();
4486 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4487 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4488 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4489 aDataset->CreateOnDisk();
4490 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4491 aDataset->CloseOnDisk();
4497 std::string info = myImpl->FileInfoToString();
4498 if ( !info.empty() )
4500 aSize[ 0 ] = info.size();
4501 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4502 aDataset->CreateOnDisk();
4503 aDataset->WriteOnDisk( (char*) info.data() );
4504 aDataset->CloseOnDisk();
4507 // write applied hypotheses if exist
4508 SALOMEDS::SObject_wrap myHypBranch;
4509 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4510 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4511 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4513 if ( found && (shapeRefFound || !hasShape) ) {
4514 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4515 aGroup->CreateOnDisk();
4517 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4519 for ( ; it->More(); it->Next() ) {
4520 SALOMEDS::SObject_wrap mySObject = it->Value();
4521 SALOMEDS::SObject_wrap myRefOnHyp;
4522 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4524 // san - it is impossible to recover applied hypotheses
4525 // using their entries within Load() method,
4526 // for there are no AttributeIORs in the study when Load() is working.
4527 // Hence, it is better to store persistent IDs of hypotheses as references to them
4529 //string myRefOnObject = myRefOnHyp->GetID();
4530 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4531 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4532 int id = myStudyContext->findId( string( objStr.in() ) );
4533 //if ( myRefOnObject.length() > 0 ) {
4534 //aSize[ 0 ] = myRefOnObject.length() + 1;
4535 char hypName[ 30 ], hypId[ 30 ];
4536 sprintf( hypName, "Hyp %d", ++hypNb );
4537 sprintf( hypId, "%d", id );
4538 aSize[ 0 ] = strlen( hypId ) + 1;
4539 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4540 aDataset->CreateOnDisk();
4541 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4542 aDataset->WriteOnDisk( hypId );
4543 aDataset->CloseOnDisk();
4547 aGroup->CloseOnDisk();
4550 // write applied algorithms if exist
4551 SALOMEDS::SObject_wrap myAlgoBranch;
4552 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4553 myAlgoBranch.inout() );
4554 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4555 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4557 if ( found && (shapeRefFound || !hasShape)) {
4558 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4559 aGroup->CreateOnDisk();
4561 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4563 for ( ; it->More(); it->Next() ) {
4564 SALOMEDS::SObject_wrap mySObject = it->Value();
4565 SALOMEDS::SObject_wrap myRefOnAlgo;
4566 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4568 // san - it is impossible to recover applied algorithms
4569 // using their entries within Load() method,
4570 // for there are no AttributeIORs in the study when Load() is working.
4571 // Hence, it is better to store persistent IDs of algorithms as references to them
4573 //string myRefOnObject = myRefOnAlgo->GetID();
4574 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4575 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4576 int id = myStudyContext->findId( string( objStr.in() ) );
4577 //if ( myRefOnObject.length() > 0 ) {
4578 //aSize[ 0 ] = myRefOnObject.length() + 1;
4579 char algoName[ 30 ], algoId[ 30 ];
4580 sprintf( algoName, "Algo %d", ++algoNb );
4581 sprintf( algoId, "%d", id );
4582 aSize[ 0 ] = strlen( algoId ) + 1;
4583 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4584 aDataset->CreateOnDisk();
4585 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4586 aDataset->WriteOnDisk( algoId );
4587 aDataset->CloseOnDisk();
4591 aGroup->CloseOnDisk();
4594 // --> submesh objects sub-branches
4596 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4597 SALOMEDS::SObject_wrap mySubmeshBranch;
4598 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4600 if ( found ) // check if there is shape reference in submeshes
4602 bool hasShapeRef = false;
4603 SALOMEDS::ChildIterator_wrap itSM =
4604 aStudy->NewChildIterator( mySubmeshBranch );
4605 for ( ; itSM->More(); itSM->Next() ) {
4606 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4607 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4608 mySubRef->ReferencedObject( myShape.inout() );
4609 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4612 { // remove one submesh
4613 if ( shapeRefFound )
4614 { // unassign hypothesis
4615 SMESH::SMESH_subMesh_var mySubMesh =
4616 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4617 if ( !mySubMesh->_is_nil() ) {
4618 int shapeID = mySubMesh->GetId();
4619 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4620 const list<const SMESHDS_Hypothesis*>& hypList =
4621 mySMESHDSMesh->GetHypothesis( S );
4622 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4623 while ( hyp != hypList.end() ) {
4624 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4625 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4629 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4631 } // loop on submeshes of a type
4632 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4633 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4636 } // end check if there is shape reference in submeshes
4638 char name_meshgroup[ 30 ];
4639 if ( i == GetSubMeshOnVertexTag() )
4640 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4641 else if ( i == GetSubMeshOnEdgeTag() )
4642 strcpy( name_meshgroup, "SubMeshes On Edge" );
4643 else if ( i == GetSubMeshOnWireTag() )
4644 strcpy( name_meshgroup, "SubMeshes On Wire" );
4645 else if ( i == GetSubMeshOnFaceTag() )
4646 strcpy( name_meshgroup, "SubMeshes On Face" );
4647 else if ( i == GetSubMeshOnShellTag() )
4648 strcpy( name_meshgroup, "SubMeshes On Shell" );
4649 else if ( i == GetSubMeshOnSolidTag() )
4650 strcpy( name_meshgroup, "SubMeshes On Solid" );
4651 else if ( i == GetSubMeshOnCompoundTag() )
4652 strcpy( name_meshgroup, "SubMeshes On Compound" );
4654 // for each type of submeshes create container HDF group
4655 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4656 aGroup->CreateOnDisk();
4658 // iterator for all submeshes of given type
4659 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4660 for ( ; itSM->More(); itSM->Next() ) {
4661 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4662 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4663 if ( !CORBA::is_nil( anSubObject ))
4665 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4666 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4667 int subid = myStudyContext->findId( string( objStr.in() ) );
4669 // for each mesh open the HDF group basing on its id
4670 char submeshGrpName[ 30 ];
4671 sprintf( submeshGrpName, "SubMesh %d", subid );
4672 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4673 aSubGroup->CreateOnDisk();
4675 // write reference on a shape, already checked if it exists
4676 SALOMEDS::SObject_wrap mySubRef, myShape;
4677 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4678 mySubRef->ReferencedObject( myShape.inout() );
4679 string myRefOnObject = myShape->GetID();
4680 if ( myRefOnObject.length() > 0 ) {
4681 aSize[ 0 ] = myRefOnObject.length() + 1;
4682 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4683 aDataset->CreateOnDisk();
4684 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4685 aDataset->CloseOnDisk();
4688 // write applied hypotheses if exist
4689 SALOMEDS::SObject_wrap mySubHypBranch;
4690 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4691 mySubHypBranch.inout() );
4693 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4694 aSubSubGroup->CreateOnDisk();
4696 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4698 for ( ; it->More(); it->Next() ) {
4699 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4700 SALOMEDS::SObject_wrap myRefOnHyp;
4701 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4703 //string myRefOnObject = myRefOnHyp->GetID();
4704 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4705 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4706 int id = myStudyContext->findId( string( objStr.in() ) );
4707 //if ( myRefOnObject.length() > 0 ) {
4708 //aSize[ 0 ] = myRefOnObject.length() + 1;
4709 char hypName[ 30 ], hypId[ 30 ];
4710 sprintf( hypName, "Hyp %d", ++hypNb );
4711 sprintf( hypId, "%d", id );
4712 aSize[ 0 ] = strlen( hypId ) + 1;
4713 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4714 aDataset->CreateOnDisk();
4715 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4716 aDataset->WriteOnDisk( hypId );
4717 aDataset->CloseOnDisk();
4721 aSubSubGroup->CloseOnDisk();
4724 // write applied algorithms if exist
4725 SALOMEDS::SObject_wrap mySubAlgoBranch;
4726 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4727 mySubAlgoBranch.inout() );
4729 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4730 aSubSubGroup->CreateOnDisk();
4732 SALOMEDS::ChildIterator_wrap it =
4733 aStudy->NewChildIterator( mySubAlgoBranch );
4735 for ( ; it->More(); it->Next() ) {
4736 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4737 SALOMEDS::SObject_wrap myRefOnAlgo;
4738 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4740 //string myRefOnObject = myRefOnAlgo->GetID();
4741 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4742 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4743 int id = myStudyContext->findId( string( objStr.in() ) );
4744 //if ( myRefOnObject.length() > 0 ) {
4745 //aSize[ 0 ] = myRefOnObject.length() + 1;
4746 char algoName[ 30 ], algoId[ 30 ];
4747 sprintf( algoName, "Algo %d", ++algoNb );
4748 sprintf( algoId, "%d", id );
4749 aSize[ 0 ] = strlen( algoId ) + 1;
4750 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4751 aDataset->CreateOnDisk();
4752 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4753 aDataset->WriteOnDisk( algoId );
4754 aDataset->CloseOnDisk();
4758 aSubSubGroup->CloseOnDisk();
4760 // close submesh HDF group
4761 aSubGroup->CloseOnDisk();
4764 // close container of submeshes by type HDF group
4765 aGroup->CloseOnDisk();
4769 // store submesh order if any
4770 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4771 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4772 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4773 char order_list[ 30 ];
4774 strcpy( order_list, "Mesh Order" );
4775 // count number of submesh ids
4777 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4778 for ( ; idIt != theOrderIds.end(); idIt++ )
4779 nbIDs += (*idIt).size();
4780 // number of values = number of IDs +
4781 // number of lists (for separators) - 1
4782 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4783 idIt = theOrderIds.begin();
4784 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4785 const TListOfInt& idList = *idIt;
4786 if (idIt != theOrderIds.begin()) // not first list
4787 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4788 // dump submesh ids from current list
4789 TListOfInt::const_iterator id_smId = idList.begin();
4790 for( ; id_smId != idList.end(); id_smId++ )
4791 smIDs[ i++ ] = *id_smId;
4794 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4796 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4797 aDataset->CreateOnDisk();
4798 aDataset->WriteOnDisk( smIDs );
4799 aDataset->CloseOnDisk();
4803 if ( !theOrderIds.empty() && isNewOrederVersion )
4805 // convert ids to entries
4806 std::list< std::list< std::string > > orderEntryLists;
4807 for ( const TListOfInt& idList : theOrderIds )
4809 orderEntryLists.emplace_back();
4810 std::list< std::string > & entryList = orderEntryLists.back();
4811 for ( const int& id : idList )
4813 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4814 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4815 SALOMEDS::SObject_var so = ObjectToSObject( go );
4816 if ( !so->_is_nil() )
4818 CORBA::String_var entry = so->GetID();
4819 entryList.emplace_back( entry.in() );
4823 // convert orderEntryLists to string
4824 std::ostringstream ostream;
4825 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4826 std::string orderEntryString = ostream.str();
4829 aSize[ 0 ] = orderEntryString.size() + 1;
4830 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4831 aDataset->CreateOnDisk();
4832 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4833 aDataset->CloseOnDisk();
4836 // groups root sub-branch
4837 SALOMEDS::SObject_wrap myGroupsBranch;
4838 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4839 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4841 char name_group[ 30 ];
4842 if ( i == GetNodeGroupsTag() )
4843 strcpy( name_group, "Groups of Nodes" );
4844 else if ( i == GetEdgeGroupsTag() )
4845 strcpy( name_group, "Groups of Edges" );
4846 else if ( i == GetFaceGroupsTag() )
4847 strcpy( name_group, "Groups of Faces" );
4848 else if ( i == GetVolumeGroupsTag() )
4849 strcpy( name_group, "Groups of Volumes" );
4850 else if ( i == Get0DElementsGroupsTag() )
4851 strcpy( name_group, "Groups of 0D Elements" );
4852 else if ( i == GetBallElementsGroupsTag() )
4853 strcpy( name_group, "Groups of Balls" );
4855 aGroup = new HDFgroup( name_group, aTopGroup );
4856 aGroup->CreateOnDisk();
4858 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4859 for ( ; it->More(); it->Next() ) {
4860 SALOMEDS::SObject_wrap mySObject = it->Value();
4861 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4862 if ( !CORBA::is_nil( aSubObject ) ) {
4863 SMESH_GroupBase_i* myGroupImpl =
4864 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4867 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4871 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4872 int anId = myStudyContext->findId( string( objStr.in() ) );
4874 // For each group, create a dataset named "Group <group_persistent_id>"
4875 // and store the group's user name into it
4876 const char* grpName = aGrpBaseDS->GetStoreName();
4877 CORBA::String_var aUserName = myGroupImpl->GetName();
4878 aSize[ 0 ] = strlen( aUserName ) + 1;
4880 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4881 aDataset->CreateOnDisk();
4882 aDataset->WriteOnDisk( aUserName );
4883 aDataset->CloseOnDisk();
4886 // For each group, create a dataset named "Group <group_persistent_id> Color"
4887 // and store the group's color into it
4888 char grpColorName[ 30 ];
4889 sprintf( grpColorName, "ColorGroup %d", anId );
4890 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4892 anRGB[ 0 ] = aColor.R;
4893 anRGB[ 1 ] = aColor.G;
4894 anRGB[ 2 ] = aColor.B;
4896 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4897 aDataset->CreateOnDisk();
4898 aDataset->WriteOnDisk( anRGB );
4899 aDataset->CloseOnDisk();
4901 // Pass SMESHDS_Group to MED writer
4902 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4904 myWriter.AddGroup( aGrpDS );
4906 // write reference on a shape if exists
4907 SMESHDS_GroupOnGeom* aGeomGrp =
4908 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4910 SALOMEDS::SObject_wrap mySubRef, myShape;
4911 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4912 mySubRef->ReferencedObject( myShape.inout() ) &&
4913 !CORBA::is_nil( myShape->GetObject() ))
4915 CORBA::String_var myRefOnObject = myShape->GetID();
4916 if ( myRefOnObject.in()[0] ) {
4917 char aRefName[ 30 ];
4918 sprintf( aRefName, "Ref on shape %d", anId);
4919 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4920 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4921 aDataset->CreateOnDisk();
4922 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4923 aDataset->CloseOnDisk();
4926 else // shape ref is invalid:
4928 // save a group on geometry as ordinary group
4929 myWriter.AddGroup( aGeomGrp );
4932 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4933 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4935 std::string str = aFilterGrp_i->FilterToString();
4936 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4937 aSize[ 0 ] = str.length() + 1;
4938 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4939 aDataset->CreateOnDisk();
4940 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4941 aDataset->CloseOnDisk();
4945 aGroup->CloseOnDisk();
4949 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4951 // Flush current mesh information into MED file
4954 // save info on nb of elements
4955 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4957 // maybe a shape was deleted in the study
4958 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4959 TopoDS_Shape nullShape;
4960 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4963 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4968 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4969 aGroup->CreateOnDisk();
4971 // each element belongs to one or none submesh,
4972 // so for each node/element, we store a submesh ID
4974 // Store submesh IDs
4975 for ( int isNode = 0; isNode < 2; ++isNode )
4977 SMDS_ElemIteratorPtr eIt =
4978 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4979 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4982 std::vector<int> smIDs; smIDs.reserve( nbElems );
4983 while ( eIt->more() )
4984 if ( const SMDS_MeshElement* e = eIt->next())
4985 smIDs.push_back( e->getshapeId() );
4987 aSize[ 0 ] = nbElems;
4988 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4989 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4990 aDataset->CreateOnDisk();
4991 aDataset->WriteOnDisk( & smIDs[0] );
4992 aDataset->CloseOnDisk();
4995 aGroup->CloseOnDisk();
4997 // Store node positions on sub-shapes (SMDS_Position):
4998 // ----------------------------------------------------
5000 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5001 aGroup->CreateOnDisk();
5003 // in aGroup, create 5 datasets to contain:
5004 // "Nodes on Edges" - ID of node on edge
5005 // "Edge positions" - U parameter on node on edge
5006 // "Nodes on Faces" - ID of node on face
5007 // "Face U positions" - U parameter of node on face
5008 // "Face V positions" - V parameter of node on face
5010 // Find out nb of nodes on edges and faces
5011 // Collect corresponding sub-meshes
5012 int nbEdgeNodes = 0, nbFaceNodes = 0;
5013 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5014 // loop on SMESHDS_SubMesh'es
5015 while ( smIt->more() )
5017 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5018 if ( aSubMesh->IsComplexSubmesh() )
5019 continue; // submesh containing other submeshs
5020 int nbNodes = aSubMesh->NbNodes();
5021 if ( nbNodes == 0 ) continue;
5023 int aShapeID = aSubMesh->GetID();
5024 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5026 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5027 // write only SMDS_FacePosition and SMDS_EdgePosition
5028 switch ( aShapeType ) {
5030 nbFaceNodes += nbNodes;
5031 aFaceSM.push_back( aSubMesh );
5034 nbEdgeNodes += nbNodes;
5035 aEdgeSM.push_back( aSubMesh );
5041 // Treat positions on edges or faces
5042 for ( int onFace = 0; onFace < 2; onFace++ )
5044 // Create arrays to store in datasets
5045 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5046 if (!nbNodes) continue;
5047 int* aNodeIDs = new int [ nbNodes ];
5048 double* aUPos = new double [ nbNodes ];
5049 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5052 // loop on sub-meshes
5053 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5054 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5055 for ( ; itSM != pListSM->end(); itSM++ )
5057 SMESHDS_SubMesh* aSubMesh = (*itSM);
5059 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5060 // loop on nodes in aSubMesh
5061 while ( itNode->more() )
5064 const SMDS_MeshNode* node = itNode->next();
5065 aNodeIDs [ iNode ] = node->GetID();
5068 const SMDS_PositionPtr pos = node->GetPosition();
5069 if ( onFace ) { // on FACE
5070 SMDS_FacePositionPtr fPos = pos;
5072 aUPos[ iNode ] = fPos->GetUParameter();
5073 aVPos[ iNode ] = fPos->GetVParameter();
5080 SMDS_EdgePositionPtr ePos = pos;
5082 aUPos[ iNode ] = ePos->GetUParameter();
5088 } // loop on nodes in aSubMesh
5089 } // loop on sub-meshes
5094 aSize[ 0 ] = nbNodes;
5096 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5097 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5098 aDataset->CreateOnDisk();
5099 aDataset->WriteOnDisk( aNodeIDs );
5100 aDataset->CloseOnDisk();
5103 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5104 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5105 aDataset->CreateOnDisk();
5106 aDataset->WriteOnDisk( aUPos );
5107 aDataset->CloseOnDisk();
5110 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5111 aDataset->CreateOnDisk();
5112 aDataset->WriteOnDisk( aVPos );
5113 aDataset->CloseOnDisk();
5118 if ( aVPos ) delete [] aVPos;
5120 } // treat positions on edges or faces
5122 // close "Node Positions" group
5123 aGroup->CloseOnDisk();
5125 } // if ( there are submeshes in SMESHDS_Mesh )
5128 // close mesh HDF group
5129 aTopGroup->CloseOnDisk();
5137 aFile->CloseOnDisk();
5140 // Convert temporary files to stream
5141 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5143 // Remove temporary files and directory
5145 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5147 return aStreamFile._retn();
5150 //=============================================================================
5152 * SMESH_Gen_i::SaveASCII
5154 * Save SMESH module's data in ASCII format
5156 //=============================================================================
5158 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5160 bool isMultiFile ) {
5161 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5162 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5163 return aStreamFile._retn();
5165 //after usual saving needs to encipher binary to text string
5166 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5167 int size = aStreamFile.in().length();
5168 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5169 for ( int i = 0; i < size; i++ )
5170 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5172 buffer[size * 3] = '\0';
5174 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5176 return anAsciiStreamFile._retn();
5179 //=============================================================================
5183 * Load SMESH module's data
5185 //=============================================================================
5187 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5188 const SALOMEDS::TMPFile& theStream,
5192 UpdateStudy(); // load geom data
5193 Kernel_Utils::Localizer loc;
5195 SALOMEDS::Study_var aStudy = getStudyServant();
5197 // Get temporary files location
5198 TCollection_AsciiString tmpDir =
5199 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5201 // Convert the stream into sequence of files to process
5202 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5205 TCollection_AsciiString aStudyName( "" );
5206 if ( isMultiFile ) {
5207 CORBA::WString_var url = aStudy->URL();
5208 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5210 // Set names of temporary files
5211 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5212 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5216 HDFdataset* aDataset;
5217 HDFgroup* aTopGroup;
5219 HDFgroup* aSubGroup;
5220 HDFgroup* aSubSubGroup;
5223 // ---> open HDF file
5224 aFile = new HDFfile( (char*) filename.ToCString() );
5226 aFile->OpenOnDisk( HDF_RDONLY );
5228 catch ( HDFexception ) {
5229 INFOS( "Load(): " << filename << " not found!" );
5233 TPythonDump pd; // prevent dump during loading
5235 // For PAL13473 ("Repetitive mesh") implementation.
5236 // New dependencies between SMESH objects are established:
5237 // now hypotheses can refer to meshes, shapes and other hypotheses.
5238 // To keep data consistent, the following order of data restoration
5240 // 1. Create hypotheses
5241 // 2. Create all meshes
5242 // 3. Load hypotheses' data
5245 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5246 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5247 list< SMESH::Filter_var > filters;
5249 // get total number of top-level groups
5250 int aNbGroups = aFile->nInternalObjects();
5251 if ( aNbGroups > 0 ) {
5252 // --> in first turn we should read&create hypotheses
5253 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5254 // open hypotheses root HDF group
5255 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5256 aTopGroup->OpenOnDisk();
5258 // get number of hypotheses
5259 int aNbObjects = aTopGroup->nInternalObjects();
5260 for ( int j = 0; j < aNbObjects; j++ ) {
5261 // try to identify hypothesis
5262 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5263 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5265 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5266 // open hypothesis group
5267 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5268 aGroup->OpenOnDisk();
5270 // --> get hypothesis id
5271 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5276 // get number of datasets
5277 int aNbSubObjects = aGroup->nInternalObjects();
5278 for ( int k = 0; k < aNbSubObjects; k++ ) {
5280 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5281 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5282 // --> get hypothesis name
5283 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5284 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5285 aDataset->OpenOnDisk();
5286 size = aDataset->GetSize();
5287 char* hypname_str = new char[ size ];
5288 aDataset->ReadFromDisk( hypname_str );
5289 hypname = string( hypname_str );
5290 delete [] hypname_str;
5291 aDataset->CloseOnDisk();
5293 // --> get hypothesis plugin library name
5294 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5295 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5296 aDataset->OpenOnDisk();
5297 size = aDataset->GetSize();
5298 char* libname_str = new char[ size ];
5299 aDataset->ReadFromDisk( libname_str );
5300 if(MYDEBUG) SCRUTE( libname_str );
5301 libname = string( libname_str );
5302 delete [] libname_str;
5303 aDataset->CloseOnDisk();
5305 // --> get hypothesis data
5306 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5307 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5308 aDataset->OpenOnDisk();
5309 size = aDataset->GetSize();
5310 char* hypdata_str = new char[ size ];
5311 aDataset->ReadFromDisk( hypdata_str );
5312 hypdata = string( hypdata_str );
5313 delete [] hypdata_str;
5314 aDataset->CloseOnDisk();
5317 // close hypothesis HDF group
5318 aGroup->CloseOnDisk();
5320 // --> restore hypothesis from data
5321 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5322 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5323 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5324 SMESH::SMESH_Hypothesis_var myHyp;
5326 try { // protect persistence mechanism against exceptions
5327 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5330 INFOS( "Exception during hypothesis creation" );
5333 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5335 // myImpl->LoadFrom( hypdata.c_str() );
5336 hypDataList.push_back( make_pair( myImpl, hypdata ));
5337 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5338 int newId = myStudyContext->findId( iorString.in() );
5339 myStudyContext->mapOldToNew( id, newId );
5342 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5346 // close hypotheses root HDF group
5347 aTopGroup->CloseOnDisk();
5351 // --> then we should read&create algorithms
5352 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5353 // open algorithms root HDF group
5354 aTopGroup = new HDFgroup( "Algorithms", aFile );
5355 aTopGroup->OpenOnDisk();
5357 // get number of algorithms
5358 int aNbObjects = aTopGroup->nInternalObjects();
5359 for ( int j = 0; j < aNbObjects; j++ ) {
5360 // try to identify algorithm
5361 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5362 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5364 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5365 // open algorithm group
5366 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5367 aGroup->OpenOnDisk();
5369 // --> get algorithm id
5370 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5375 // get number of datasets
5376 int aNbSubObjects = aGroup->nInternalObjects();
5377 for ( int k = 0; k < aNbSubObjects; k++ ) {
5379 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5380 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5381 // --> get algorithm name
5382 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5383 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5384 aDataset->OpenOnDisk();
5385 size = aDataset->GetSize();
5386 char* hypname_str = new char[ size ];
5387 aDataset->ReadFromDisk( hypname_str );
5388 hypname = string( hypname_str );
5389 delete [] hypname_str;
5390 aDataset->CloseOnDisk();
5392 // --> get algorithm plugin library name
5393 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5394 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5395 aDataset->OpenOnDisk();
5396 size = aDataset->GetSize();
5397 char* libname_str = new char[ size ];
5398 aDataset->ReadFromDisk( libname_str );
5399 if(MYDEBUG) SCRUTE( libname_str );
5400 libname = string( libname_str );
5401 delete [] libname_str;
5402 aDataset->CloseOnDisk();
5404 // --> get algorithm data
5405 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5406 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5407 aDataset->OpenOnDisk();
5408 size = aDataset->GetSize();
5409 char* hypdata_str = new char[ size ];
5410 aDataset->ReadFromDisk( hypdata_str );
5411 if(MYDEBUG) SCRUTE( hypdata_str );
5412 hypdata = string( hypdata_str );
5413 delete [] hypdata_str;
5414 aDataset->CloseOnDisk();
5417 // close algorithm HDF group
5418 aGroup->CloseOnDisk();
5420 // --> restore algorithm from data
5421 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5422 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5423 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5424 SMESH::SMESH_Hypothesis_var myHyp;
5426 try { // protect persistence mechanism against exceptions
5427 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5429 catch( SALOME::SALOME_Exception& ex )
5431 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5434 INFOS( "Exception during hypothesis creation" );
5437 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5439 //myImpl->LoadFrom( hypdata.c_str() );
5440 hypDataList.push_back( make_pair( myImpl, hypdata ));
5441 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5442 int newId = myStudyContext->findId( iorString.in() );
5443 myStudyContext->mapOldToNew( id, newId );
5446 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5450 // close algorithms root HDF group
5451 aTopGroup->CloseOnDisk();
5455 // --> the rest groups should be meshes
5456 for ( int i = 0; i < aNbGroups; i++ ) {
5457 // identify next group
5458 char meshName[ HDF_NAME_MAX_LEN+1 ];
5459 aFile->InternalObjectIndentify( i, meshName );
5461 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5463 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5467 // open mesh HDF group
5468 aTopGroup = new HDFgroup( meshName, aFile );
5469 aTopGroup->OpenOnDisk();
5471 // get number of child HDF objects
5472 int aNbObjects = aTopGroup->nInternalObjects();
5473 if ( aNbObjects > 0 ) {
5475 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5476 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5477 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5478 if ( !myNewMeshImpl )
5480 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5482 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5483 int newId = myStudyContext->findId( iorString.in() );
5484 myStudyContext->mapOldToNew( id, newId );
5487 // try to read and set auto color flag
5488 char aMeshAutoColorName[ 30 ];
5489 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5490 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5492 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5493 aDataset->OpenOnDisk();
5494 size = aDataset->GetSize();
5495 int* anAutoColor = new int[ size ];
5496 aDataset->ReadFromDisk( anAutoColor );
5497 aDataset->CloseOnDisk();
5498 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5499 delete [] anAutoColor;
5502 // try to read and set reference to shape
5503 GEOM::GEOM_Object_var aShapeObject;
5504 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5505 // load mesh "Ref on shape" - it's an entry to SObject
5506 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5507 aDataset->OpenOnDisk();
5508 size = aDataset->GetSize();
5509 char* refFromFile = new char[ size ];
5510 aDataset->ReadFromDisk( refFromFile );
5511 aDataset->CloseOnDisk();
5512 if ( strlen( refFromFile ) > 0 ) {
5513 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5514 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5515 if ( !CORBA::is_nil( shapeObject ) ) {
5516 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5517 if ( !aShapeObject->_is_nil() )
5518 myNewMeshImpl->SetShape( aShapeObject );
5521 delete [] refFromFile;
5524 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5525 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5527 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5528 aDataset->OpenOnDisk();
5529 size = aDataset->GetSize();
5530 int* meshPersistentId = new int[ size ];
5531 aDataset->ReadFromDisk( meshPersistentId );
5532 aDataset->CloseOnDisk();
5533 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5534 delete [] meshPersistentId;
5537 // Restore SMESH_Mesh_i::_mainShapeTick
5538 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5540 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5541 aDataset->OpenOnDisk();
5542 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5543 aDataset->ReadFromDisk( shapeTick );
5544 aDataset->CloseOnDisk();
5547 // Restore file info
5548 if ( aTopGroup->ExistInternalObject( "file info" ))
5550 aDataset = new HDFdataset( "file info", aTopGroup );
5551 aDataset->OpenOnDisk();
5552 size = aDataset->GetSize();
5553 std::string info( size, ' ');
5554 aDataset->ReadFromDisk( (char*) info.data() );
5555 aDataset->CloseOnDisk();
5556 myNewMeshImpl->FileInfoFromString( info );
5562 // As all object that can be referred by hypothesis are created,
5563 // we can restore hypothesis data
5565 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5566 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5568 SMESH_Hypothesis_i* hyp = hyp_data->first;
5569 string & data = hyp_data->second;
5570 hyp->LoadFrom( data.c_str() );
5573 // Restore the rest mesh data
5575 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5576 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5578 aTopGroup = meshi_group->second;
5579 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5581 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5582 bool hasData = false;
5585 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5586 int newId = myStudyContext->findId( iorString.in() );
5587 int meshOldId = myStudyContext->getOldId( newId );
5589 // try to find mesh data dataset
5590 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5591 // load mesh "has data" flag
5592 aDataset = new HDFdataset( "Has data", aTopGroup );
5593 aDataset->OpenOnDisk();
5594 size = aDataset->GetSize();
5595 char* strHasData = new char[ size ];
5596 aDataset->ReadFromDisk( strHasData );
5597 aDataset->CloseOnDisk();
5598 if ( strcmp( strHasData, "1") == 0 ) {
5601 delete [] strHasData;
5604 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5605 // nodes and elements are not yet put into sub-meshes)
5606 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5607 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5608 aGroup->OpenOnDisk();
5609 // get number of applied algorithms
5610 int aNbSubObjects = aGroup->nInternalObjects();
5611 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5612 for ( int j = 0; j < aNbSubObjects; j++ ) {
5613 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5614 aGroup->InternalObjectIndentify( j, name_dataset );
5615 // check if it is an algorithm
5616 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5617 aDataset = new HDFdataset( name_dataset, aGroup );
5618 aDataset->OpenOnDisk();
5619 size = aDataset->GetSize();
5620 char* refFromFile = new char[ size ];
5621 aDataset->ReadFromDisk( refFromFile );
5622 aDataset->CloseOnDisk();
5623 // san - it is impossible to recover applied algorithms using their entries within Load() method
5624 int id = atoi( refFromFile );
5625 delete [] refFromFile;
5626 string anIOR = myStudyContext->getIORbyOldId( id );
5627 if ( !anIOR.empty() ) {
5628 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5629 if ( !CORBA::is_nil( hypObject ) ) {
5630 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5631 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5632 || !myNewMeshImpl->HasShapeToMesh()) )
5633 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5638 aGroup->CloseOnDisk();
5641 // try to get applied hypotheses
5642 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5643 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5644 aGroup->OpenOnDisk();
5645 // get number of applied hypotheses
5646 int aNbSubObjects = aGroup->nInternalObjects();
5647 for ( int j = 0; j < aNbSubObjects; j++ ) {
5648 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5649 aGroup->InternalObjectIndentify( j, name_dataset );
5650 // check if it is a hypothesis
5651 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5652 aDataset = new HDFdataset( name_dataset, aGroup );
5653 aDataset->OpenOnDisk();
5654 size = aDataset->GetSize();
5655 char* refFromFile = new char[ size ];
5656 aDataset->ReadFromDisk( refFromFile );
5657 aDataset->CloseOnDisk();
5658 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5659 int id = atoi( refFromFile );
5660 delete [] refFromFile;
5661 string anIOR = myStudyContext->getIORbyOldId( id );
5662 if ( !anIOR.empty() ) {
5663 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5664 if ( !CORBA::is_nil( hypObject ) ) {
5665 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5666 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5667 || !myNewMeshImpl->HasShapeToMesh()) )
5668 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5673 aGroup->CloseOnDisk();
5676 // --> try to find SUB-MESHES containers for each type of submesh
5677 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5678 const char* name_meshgroup = 0;
5679 if ( j == GetSubMeshOnVertexTag() )
5680 name_meshgroup = "SubMeshes On Vertex";
5681 else if ( j == GetSubMeshOnEdgeTag() )
5682 name_meshgroup = "SubMeshes On Edge";
5683 else if ( j == GetSubMeshOnWireTag() )
5684 name_meshgroup = "SubMeshes On Wire";
5685 else if ( j == GetSubMeshOnFaceTag() )
5686 name_meshgroup = "SubMeshes On Face";
5687 else if ( j == GetSubMeshOnShellTag() )
5688 name_meshgroup = "SubMeshes On Shell";
5689 else if ( j == GetSubMeshOnSolidTag() )
5690 name_meshgroup = "SubMeshes On Solid";
5691 else if ( j == GetSubMeshOnCompoundTag() )
5692 name_meshgroup = "SubMeshes On Compound";
5694 // try to get submeshes container HDF group
5695 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5696 // open submeshes containers HDF group
5697 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5698 aGroup->OpenOnDisk();
5700 // get number of submeshes
5701 int aNbSubMeshes = aGroup->nInternalObjects();
5702 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5704 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5705 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5706 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5707 // --> get submesh id
5708 int subid = atoi( name_submeshgroup + 7 );
5711 // open submesh HDF group
5712 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5713 aSubGroup->OpenOnDisk();
5715 // try to read and set reference to subshape
5716 GEOM::GEOM_Object_var aSubShapeObject;
5717 SMESH::SMESH_subMesh_var aSubMesh;
5719 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5720 // load submesh "Ref on shape" - it's an entry to SObject
5721 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5722 aDataset->OpenOnDisk();
5723 size = aDataset->GetSize();
5724 char* refFromFile = new char[ size ];
5725 aDataset->ReadFromDisk( refFromFile );
5726 aDataset->CloseOnDisk();
5727 if ( strlen( refFromFile ) > 0 ) {
5728 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5729 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5730 if ( !CORBA::is_nil( subShapeObject ) ) {
5731 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5732 if ( !aSubShapeObject->_is_nil() )
5733 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5734 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5735 if ( aSubMesh->_is_nil() )
5737 string iorSubString = GetORB()->object_to_string( aSubMesh );
5738 int newSubId = myStudyContext->findId( iorSubString );
5739 myStudyContext->mapOldToNew( subid, newSubId );
5742 delete [] refFromFile;
5745 if ( aSubMesh->_is_nil() )
5748 // try to get applied algorithms
5749 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5750 // open "applied algorithms" HDF group
5751 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5752 aSubSubGroup->OpenOnDisk();
5753 // get number of applied algorithms
5754 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5755 for ( int l = 0; l < aNbSubObjects; l++ ) {
5756 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5757 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5758 // check if it is an algorithm
5759 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5760 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5761 aDataset->OpenOnDisk();
5762 size = aDataset->GetSize();
5763 char* refFromFile = new char[ size ];
5764 aDataset->ReadFromDisk( refFromFile );
5765 aDataset->CloseOnDisk();
5767 int id = atoi( refFromFile );
5768 string anIOR = myStudyContext->getIORbyOldId( id );
5769 if ( !anIOR.empty() ) {
5770 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5771 if ( !CORBA::is_nil( hypObject ) ) {
5772 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5773 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5774 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5777 delete [] refFromFile;
5780 // close "applied algorithms" HDF group
5781 aSubSubGroup->CloseOnDisk();
5784 // try to get applied hypotheses
5785 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5786 // open "applied hypotheses" HDF group
5787 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5788 aSubSubGroup->OpenOnDisk();
5789 // get number of applied hypotheses
5790 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5791 for ( int l = 0; l < aNbSubObjects; l++ ) {
5792 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5793 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5794 // check if it is a hypothesis
5795 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5796 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5797 aDataset->OpenOnDisk();
5798 size = aDataset->GetSize();
5799 char* refFromFile = new char[ size ];
5800 aDataset->ReadFromDisk( refFromFile );
5801 aDataset->CloseOnDisk();
5803 int id = atoi( refFromFile );
5804 string anIOR = myStudyContext->getIORbyOldId( id );
5805 if ( !anIOR.empty() ) {
5806 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5807 if ( !CORBA::is_nil( hypObject ) ) {
5808 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5809 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5810 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5813 delete [] refFromFile;
5816 // close "APPLIED HYPOTHESES" hdf group
5817 aSubSubGroup->CloseOnDisk();
5820 // close SUB-MESH hdf group
5821 aSubGroup->CloseOnDisk();
5824 // close SUB-MESHES containers hdf group
5825 aGroup->CloseOnDisk();
5829 // try to get GROUPS
5830 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5831 char name_group[ 30 ];
5832 if ( ii == GetNodeGroupsTag() )
5833 strcpy( name_group, "Groups of Nodes" );
5834 else if ( ii == GetEdgeGroupsTag() )
5835 strcpy( name_group, "Groups of Edges" );
5836 else if ( ii == GetFaceGroupsTag() )
5837 strcpy( name_group, "Groups of Faces" );
5838 else if ( ii == GetVolumeGroupsTag() )
5839 strcpy( name_group, "Groups of Volumes" );
5840 else if ( ii == Get0DElementsGroupsTag() )
5841 strcpy( name_group, "Groups of 0D Elements" );
5842 else if ( ii == GetBallElementsGroupsTag() )
5843 strcpy( name_group, "Groups of Balls" );
5845 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5846 aGroup = new HDFgroup( name_group, aTopGroup );
5847 aGroup->OpenOnDisk();
5848 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5849 // within aGroup->ExistInternalObject( name )
5850 std::vector< std::string > subNames;
5851 TColStd_MapOfAsciiString mapOfNames;
5852 aGroup->GetAllObjects( subNames );
5853 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5854 mapOfNames.Add( subNames[ iN ].c_str() );
5856 for ( size_t j = 0; j < subNames.size(); j++ ) {
5857 const std::string& name_dataset = subNames[ j ];
5858 // check if it is a group
5859 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5862 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5865 int groupID = -1; // group local ID (also persistent)
5867 groupID = atoi( endptr + 1 );
5868 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5869 aDataset->OpenOnDisk();
5871 // Retrieve actual group name
5872 size = aDataset->GetSize();
5873 char* nameFromFile = new char[ size ];
5874 aDataset->ReadFromDisk( nameFromFile );
5875 aDataset->CloseOnDisk();
5877 // Try to find a shape reference
5878 TopoDS_Shape aShape;
5879 char aRefName[ 30 ];
5880 sprintf( aRefName, "Ref on shape %d", subid);
5881 if ( mapOfNames.Contains( aRefName ))
5883 // load mesh "Ref on shape" - it's an entry to SObject
5884 aDataset = new HDFdataset( aRefName, aGroup );
5885 aDataset->OpenOnDisk();
5886 size = aDataset->GetSize();
5887 char* refFromFile = new char[ size ];
5888 aDataset->ReadFromDisk( refFromFile );
5889 aDataset->CloseOnDisk();
5890 if ( strlen( refFromFile ) > 0 ) {
5891 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5892 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5893 if ( !CORBA::is_nil( shapeObject ) ) {
5894 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5895 if ( !aShapeObject->_is_nil() )
5896 aShape = GeomObjectToShape( aShapeObject );
5899 delete [] refFromFile;
5901 // Try to read a filter of SMESH_GroupOnFilter
5902 SMESH::Filter_var filter;
5903 SMESH_PredicatePtr predicate;
5904 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5905 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5907 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5908 aDataset->OpenOnDisk();
5909 size = aDataset->GetSize();
5910 char* persistStr = new char[ size ];
5911 aDataset->ReadFromDisk( persistStr );
5912 aDataset->CloseOnDisk();
5913 if ( strlen( persistStr ) > 0 ) {
5914 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5915 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5916 filters.push_back( filter );
5918 delete [] persistStr;
5921 // Create group servant
5922 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5923 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5924 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5925 delete [] nameFromFile;
5926 // Obtain a SMESHDS_Group object
5927 if ( aNewGroup->_is_nil() )
5930 string iorSubString = GetORB()->object_to_string( aNewGroup );
5931 int newSubId = myStudyContext->findId( iorSubString );
5932 myStudyContext->mapOldToNew( subid, newSubId );
5934 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5938 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5939 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5941 aFilterGroup->SetFilter( filter );
5942 filter->UnRegister();
5944 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5945 if ( !aGroupBaseDS )
5948 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5951 // Read color of the group
5952 char aGroupColorName[ 30 ];
5953 sprintf( aGroupColorName, "ColorGroup %d", subid);
5954 if ( mapOfNames.Contains( aGroupColorName ))
5956 aDataset = new HDFdataset( aGroupColorName, aGroup );
5957 aDataset->OpenOnDisk();
5958 size = aDataset->GetSize();
5959 double* anRGB = new double[ size ];
5960 aDataset->ReadFromDisk( anRGB );
5961 aDataset->CloseOnDisk();
5962 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5963 aGroupBaseDS->SetColor( aColor );
5968 aGroup->CloseOnDisk();
5972 // instead of reading mesh data, we read only brief information of all
5973 // objects: mesh, groups, sub-meshes (issue 0021208)
5976 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5977 meshfile.ToCString(), filename.ToCString(),
5981 // read Sub-Mesh ORDER if any
5982 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5983 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5984 aDataset->OpenOnDisk();
5985 size = aDataset->GetSize();
5986 int* smIDs = new int[ size ];
5987 aDataset->ReadFromDisk( smIDs );
5988 aDataset->CloseOnDisk();
5989 TListOfListOfInt anOrderIds;
5990 anOrderIds.push_back( TListOfInt() );
5991 for ( int i = 0; i < size; i++ )
5992 if ( smIDs[ i ] < 0 ) // is separator
5993 anOrderIds.push_back( TListOfInt() );
5995 anOrderIds.back().push_back(smIDs[ i ]);
5997 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6000 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6002 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6003 aDataset->OpenOnDisk();
6004 size = aDataset->GetSize();
6005 std::string dataString; dataString.resize( size );
6006 aDataset->ReadFromDisk((char*) dataString.data() );
6007 aDataset->CloseOnDisk();
6009 std::istringstream istream( dataString.data() );
6010 boost::archive::text_iarchive archive( istream );
6011 std::list< std::list< std::string > > orderEntryLists;
6013 archive >> orderEntryLists;
6017 TListOfListOfInt anOrderIds;
6018 for ( const std::list< std::string >& entryList : orderEntryLists )
6020 anOrderIds.emplace_back();
6021 for ( const std::string & entry : entryList )
6023 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6024 TopoDS_Shape shape = GeomObjectToShape( go );
6025 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6026 anOrderIds.back().emplace_back( sm->GetId() );
6029 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6033 // update hyps needing full mesh data restored (issue 20918)
6034 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6036 SMESH_Hypothesis_i* hyp = hyp_data->first;
6037 hyp->UpdateAsMeshesRestored();
6040 // notify algos on completed restoration to set sub-mesh event listeners
6041 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6043 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6044 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6046 TopoDS_Shape myLocShape;
6047 if(myLocMesh.HasShapeToMesh())
6048 myLocShape = myLocMesh.GetShapeToMesh();
6050 myLocShape = SMESH_Mesh::PseudoShape();
6052 myLocMesh.GetSubMesh(myLocShape)->
6053 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6056 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6057 list< SMESH::Filter_var >::iterator f = filters.begin();
6058 for ( ; f != filters.end(); ++f )
6059 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6060 fi->FindBaseObjects();
6065 aTopGroup->CloseOnDisk();
6068 aFile->CloseOnDisk();
6071 // Remove temporary files created from the stream
6074 SMESH_File meshFile( meshfile.ToCString() );
6075 if ( !meshFile ) // no meshfile exists
6077 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6081 Engines::Container_var container = GetContainerRef();
6082 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6084 container_i->registerTemporaryFile( filename.ToCString() );
6085 container_i->registerTemporaryFile( meshfile.ToCString() );
6086 container_i->registerTemporaryFile( tmpDir.ToCString() );
6091 // creation of tree nodes for all data objects in the study
6092 // to support tree representation customization and drag-n-drop:
6093 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6094 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6095 useCaseBuilder->SetRootCurrent();
6096 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6097 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6098 for (it->InitEx(true); it->More(); it->Next()) {
6099 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6106 //=============================================================================
6108 * SMESH_Gen_i::LoadASCII
6110 * Load SMESH module's data in ASCII format
6112 //=============================================================================
6114 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6115 const SALOMEDS::TMPFile& theStream,
6117 bool isMultiFile ) {
6118 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6119 return Load( theComponent, theStream, theURL, isMultiFile );
6121 //before call main ::Load method it's need for decipher text format to
6122 //binary ( "|xx" => x' )
6123 int size = theStream.length();
6124 if ( int((size / 3 )*3) != size ) //error size of buffer
6127 int real_size = int(size / 3);
6129 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6132 unsigned int c = -1;
6133 for ( int i = 0; i < real_size; i++ )
6135 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6136 sscanf( tmp, "%x", &c );
6137 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6140 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6142 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6145 //=============================================================================
6147 * SMESH_Gen_i::Close
6149 * Clears study-connected data when it is closed
6151 //=============================================================================
6153 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6155 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6157 // Clear study contexts data
6158 myStudyContext->Clear();
6160 // remove the tmp files meshes are loaded from
6161 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6163 // Clean trace of API methods calls
6169 //=============================================================================
6171 * SMESH_Gen_i::ComponentDataType
6173 * Get component data type
6175 //=============================================================================
6177 char* SMESH_Gen_i::ComponentDataType()
6179 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6180 return CORBA::string_dup( "SMESH" );
6184 //=============================================================================
6186 * SMESH_Gen_i::IORToLocalPersistentID
6188 * Transform data from transient form to persistent
6190 //=============================================================================
6192 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6193 const char* IORString,
6194 CORBA::Boolean /*isMultiFile*/,
6195 CORBA::Boolean /*isASCII*/ )
6197 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6199 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6200 int anId = myStudyContext->findId( IORString );
6202 if(MYDEBUG) MESSAGE( "VSR " << anId )
6204 sprintf( strId, "%d", anId );
6205 return CORBA::string_dup( strId );
6208 return CORBA::string_dup( "" );
6211 //=============================================================================
6213 * SMESH_Gen_i::LocalPersistentIDToIOR
6215 * Transform data from persistent form to transient
6217 //=============================================================================
6219 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6220 const char* aLocalPersistentID,
6221 CORBA::Boolean /*isMultiFile*/,
6222 CORBA::Boolean /*isASCII*/ )
6224 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6226 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6227 int anId = atoi( aLocalPersistentID );
6228 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6230 return CORBA::string_dup( "" );
6233 //=======================================================================
6234 //function : RegisterObject
6236 //=======================================================================
6238 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6240 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6241 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6242 return myStudyContext->addObject( string( iorString.in() ) );
6247 //================================================================================
6249 * \brief Return id of registered object
6250 * \param theObject - the Object
6251 * \retval int - Object id
6253 //================================================================================
6255 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6257 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6258 string iorString = GetORB()->object_to_string( theObject );
6259 return myStudyContext->findId( iorString );
6264 //=============================================================================
6266 * SMESH_Gen_i::SetName
6268 * Set a new object name
6270 //=============================================================================
6272 void SMESH_Gen_i::SetName(const char* theIOR,
6273 const char* theName)
6275 if ( theIOR && strcmp( theIOR, "" ) ) {
6276 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6277 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6278 if ( !aSO->_is_nil() ) {
6279 SetName( aSO, theName );
6284 // Version information
6285 char* SMESH_Gen_i::getVersion()
6287 #if SMESH_DEVELOPMENT
6288 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6290 return CORBA::string_dup(SMESH_VERSION_STR);
6294 //=================================================================================
6295 // function : Move()
6296 // purpose : Moves objects to the specified position.
6297 // Is used in the drag-n-drop functionality.
6298 //=================================================================================
6300 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6301 SALOMEDS::SObject_ptr where,
6304 if ( CORBA::is_nil( where ) ) return;
6306 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6307 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6308 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6309 std::string dataType = father->ComponentDataType();
6310 if ( dataType != "SMESH" ) return; // not a SMESH component
6312 SALOMEDS::SObject_var objAfter;
6313 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6314 // insert at given row -> find insertion position
6315 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6317 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6318 if ( i == row && useCaseIt->More() ) {
6319 objAfter = useCaseIt->Value();
6323 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6324 SALOMEDS::SObject_var sobj = what[i];
6325 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6326 // insert the object to the use case tree
6327 if ( !CORBA::is_nil( objAfter ) )
6328 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6330 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6333 //================================================================================
6335 * \brief Returns true if algorithm can be used to mesh a given geometry
6336 * \param [in] theAlgoType - the algorithm type
6337 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6338 * \param [in] theGeomObject - the geometry to mesh
6339 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6340 * else, returns \c True if at least one shape is meshable
6341 * \return CORBA::Boolean - can or can't
6343 //================================================================================
6345 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6346 const char* theLibName,
6347 GEOM::GEOM_Object_ptr theGeomObject,
6348 CORBA::Boolean toCheckAll)
6352 std::string aPlatformLibName;
6353 GenericHypothesisCreator_i* aCreator =
6354 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6357 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6358 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6359 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6366 SMESH_CATCH( SMESH::doNothing );
6369 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6374 //================================================================================
6376 * \brief Collect indices of elements, which are located inside the sphere
6378 //================================================================================
6380 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6381 SMESH::ElementType theElemType,
6387 SMESH::long_array_var aResult = new SMESH::long_array();
6388 if ( meshPart->_is_nil() )
6389 return aResult._retn();
6391 // 1. Create geometrical object
6392 gp_Pnt aP( theX, theY, theZ );
6393 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6395 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6397 if ( lst.size() > 0 ) {
6398 aResult->length( lst.size() );
6399 for ( size_t i = 0; i < lst.size(); i++ ) {
6400 aResult[i] = lst[i];
6403 return aResult._retn();
6406 //================================================================================
6408 * \brief Collect indices of elements, which are located inside the box
6410 //================================================================================
6412 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6413 SMESH::ElementType theElemType,
6414 CORBA::Double theX1,
6415 CORBA::Double theY1,
6416 CORBA::Double theZ1,
6417 CORBA::Double theX2,
6418 CORBA::Double theY2,
6419 CORBA::Double theZ2)
6421 SMESH::long_array_var aResult = new SMESH::long_array();
6422 if( meshPart->_is_nil() )
6423 return aResult._retn();
6425 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6426 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6428 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6430 if( lst.size() > 0 ) {
6431 aResult->length( lst.size() );
6432 for ( size_t i = 0; i < lst.size(); i++ ) {
6433 aResult[i] = lst[i];
6436 return aResult._retn();
6439 //================================================================================
6441 * \brief Collect indices of elements, which are located inside the cylinder
6443 //================================================================================
6445 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6446 SMESH::ElementType theElemType,
6450 CORBA::Double theDX,
6451 CORBA::Double theDY,
6452 CORBA::Double theDZ,
6454 CORBA::Double theR )
6456 SMESH::long_array_var aResult = new SMESH::long_array();
6457 if( meshPart->_is_nil() )
6458 return aResult._retn();
6460 gp_Pnt aP( theX, theY, theZ );
6461 gp_Vec aV( theDX, theDY, theDZ );
6462 gp_Ax2 anAxes (aP, aV);
6464 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6466 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6468 if( lst.size() > 0 ) {
6469 aResult->length( lst.size() );
6470 for ( size_t i = 0; i < lst.size(); i++ ) {
6471 aResult[i] = lst[i];
6474 return aResult._retn();
6477 //================================================================================
6479 * \brief Collect indices of elements, which are located inside the geom object
6481 //================================================================================
6483 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6484 SMESH::ElementType theElemType,
6485 GEOM::GEOM_Object_ptr theGeom,
6486 CORBA::Double theTolerance )
6488 SMESH::long_array_var aResult = new SMESH::long_array();
6489 if( meshPart->_is_nil() || theGeom->_is_nil() )
6490 return aResult._retn();
6492 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6494 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6496 if( lst.size() > 0 ) {
6497 aResult->length( lst.size() );
6498 for ( size_t i = 0; i < lst.size(); i++ ) {
6499 aResult[i] = lst[i];
6502 return aResult._retn();
6505 //================================================================================
6507 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6509 //================================================================================
6511 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6512 SMESH::ElementType theElemType,
6513 const TopoDS_Shape& theShape,
6514 double* theTolerance) {
6516 std::vector<long> res;
6517 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6519 if ( mesh->_is_nil() )
6522 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6526 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6531 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6532 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6533 anElementsOnShape->SetAllNodes( true );
6534 anElementsOnShape->SetMesh( meshDS );
6535 anElementsOnShape->SetShape( theShape, aType );
6538 anElementsOnShape->SetTolerance(*theTolerance);
6540 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6541 if ( !msource->_is_nil() ) { // Mesh case
6542 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6544 while ( elemIt->more() ) {
6545 const SMDS_MeshElement* anElem = elemIt->next();
6546 long anId = anElem->GetID();
6547 if ( anElementsOnShape->IsSatisfy( anId ) )
6548 res.push_back( anId );
6552 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6553 if ( !gsource->_is_nil() ) {
6554 if(theElemType == SMESH::NODE) {
6555 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6556 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6557 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6558 long anId = node->GetID();
6559 if ( anElementsOnShape->IsSatisfy( anId ) )
6560 res.push_back( anId );
6563 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6564 SMESH::long_array_var elems = gsource->GetListOfID();
6565 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6566 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6567 long anId = elem->GetID();
6568 if ( anElementsOnShape->IsSatisfy( anId ) )
6569 res.push_back( anId );
6574 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6575 if ( !smsource->_is_nil() ) {
6576 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6577 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6578 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6580 long anId = elem->GetID();
6581 if ( anElementsOnShape->IsSatisfy( anId ) )
6582 res.push_back( anId );
6589 //=============================================================================
6591 * SMESHEngine_factory
6593 * C factory, accessible with dlsym, after dlopen
6595 //=============================================================================
6599 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6600 PortableServer::POA_ptr poa,
6601 PortableServer::ObjectId* contId,
6602 const char* instanceName,
6603 const char* interfaceName )
6605 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6606 if(MYDEBUG) SCRUTE(interfaceName);
6607 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6608 return aSMESHGen->getId() ;