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;
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 )
334 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
337 myOrb = CORBA::ORB::_duplicate(orb);
338 myPoa = PortableServer::POA::_duplicate(poa);
341 _id = myPoa->activate_object( _thisObj );
343 myStudyContext = new StudyContext;
345 myIsEmbeddedMode = false;
346 myIsEnablePublish = true;
347 myShapeReader = NULL; // shape reader
349 myIsHistoricalPythonDump = true;
350 myToForgetMeshDataOnHypModif = false;
352 // set it in standalone mode only
353 //OSD::SetSignal( true );
355 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
356 // find out mode (embedded or standalone) here else
357 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
358 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
359 if ( SALOME_NamingService* ns = GetNS() )
361 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
362 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
363 if ( !session->_is_nil() )
365 CORBA::String_var str_host = session->getHostname();
366 CORBA::Long s_pid = session->getPID();
367 string my_host = Kernel_Utils::GetHostname();
369 long my_pid = (long)_getpid();
371 long my_pid = (long) getpid();
373 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
378 //=============================================================================
380 * SMESH_Gen_i::~SMESH_Gen_i
384 //=============================================================================
386 SMESH_Gen_i::~SMESH_Gen_i()
388 // delete hypothesis creators
389 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
390 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
392 // same creator can be mapped under different names
393 GenericHypothesisCreator_i* creator = (*itHyp).second;
397 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
398 if ( creator == (*itHyp2).second )
399 (*itHyp2).second = 0;
401 myHypCreatorMap.clear();
403 // Clear study contexts data
404 delete myStudyContext;
406 // delete shape reader
408 delete myShapeReader;
411 //=============================================================================
413 * SMESH_Gen_i::getHypothesisCreator
415 * Get hypothesis creator
417 //=============================================================================
419 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
420 const char* theLibName,
421 std::string& thePlatformLibName)
422 throw (SALOME::SALOME_Exception)
424 std::string aPlatformLibName;
425 /* It's Need to translate lib name for WIN32 or X platform */
426 if ( theLibName && theLibName[0] != '\0' )
428 int libNameLen = strlen(theLibName);
429 //check for old format "libXXXXXXX.so"
430 if (libNameLen > 7 &&
431 !strncmp( theLibName, "lib", 3 ) &&
432 !strcmp( theLibName+libNameLen-3, ".so" ))
436 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
437 #elif defined(__APPLE__)
438 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
440 aPlatformLibName = theLibName;
445 //try to use new format
447 aPlatformLibName = theLibName;
448 aPlatformLibName += ".dll";
449 #elif defined(__APPLE__)
450 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
452 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
456 thePlatformLibName = aPlatformLibName;
458 Unexpect aCatch(SALOME_SalomeException);
459 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
461 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
462 GenericHypothesisCreator_i* aCreator;
465 // check, if creator for this hypothesis type already exists
466 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
468 // load plugin library
469 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
472 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
474 const char* path = aPlatformLibName.c_str();
477 const char* path = aPlatformLibName.c_str();
479 LibHandle libHandle = LoadLib( path );
480 #if defined(WIN32) && defined(UNICODE)
485 // report any error, if occurred
487 const char* anError = dlerror();
488 throw(SALOME_Exception( anError ));
490 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
491 << aPlatformLibName));
495 // get method, returning hypothesis creator
496 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
497 GetHypothesisCreator procHandle =
498 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
501 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
502 << aPlatformLibName ));
503 UnLoadLib(libHandle);
506 // get hypothesis creator
507 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
508 aCreator = procHandle(theHypName);
511 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
512 << aPlatformLibName));
514 // map hypothesis creator to a hypothesis name
515 myHypCreatorMap[string(theHypName)] = aCreator;
520 return myHypCreatorMap[string(theHypName)];
523 catch (SALOME_Exception& S_ex)
525 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
530 //=============================================================================
532 * SMESH_Gen_i::createHypothesis
534 * Create hypothesis of given type
536 //=============================================================================
538 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
539 const char* theLibName)
541 SMESH_Hypothesis_i* myHypothesis_i = 0;
542 SMESH::SMESH_Hypothesis_var hypothesis_i;
543 std::string aPlatformLibName;
544 GenericHypothesisCreator_i* aCreator =
545 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
547 // create a new hypothesis object, store its ref. in studyContext
548 myHypothesis_i = aCreator->Create(myPoa, &myGen);
551 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
552 CORBA::String_var hypName = myHypothesis_i->GetName();
553 myHypCreatorMap[ hypName.in() ] = aCreator;
555 // activate the CORBA servant of hypothesis
556 hypothesis_i = myHypothesis_i->_this();
557 int nextId = RegisterObject( hypothesis_i );
558 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
559 else { nextId = 0; } // avoid "unused variable" warning in release mode
561 return hypothesis_i._retn();
564 //=============================================================================
566 * SMESH_Gen_i::createMesh
568 * Create empty mesh on shape
570 //=============================================================================
572 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
573 throw ( SALOME::SALOME_Exception )
575 Unexpect aCatch(SALOME_SalomeException);
576 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
578 // Get or create the GEOM_Client instance
580 // create a new mesh object servant, store it in a map in study context
581 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
582 // create a new mesh object
583 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
584 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
586 // activate the CORBA servant of Mesh
587 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
588 int nextId = RegisterObject( mesh );
589 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
590 else { nextId = 0; } // avoid "unused variable" warning in release mode
593 catch (SALOME_Exception& S_ex) {
594 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
596 return SMESH::SMESH_Mesh::_nil();
599 //=============================================================================
601 * SMESH_Gen_i::GetShapeReader
605 //=============================================================================
607 GEOM_Client* SMESH_Gen_i::GetShapeReader()
609 // create shape reader if necessary
610 if ( !myShapeReader )
611 myShapeReader = new GEOM_Client(GetContainerRef());
612 ASSERT( myShapeReader );
613 return myShapeReader;
616 //=============================================================================
618 * SMESH_Gen_i::SetGeomEngine
620 * Set GEOM::GEOM_Gen reference
622 //=============================================================================
624 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
626 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
629 //=============================================================================
631 * SMESH_Gen_i::SetEmbeddedMode
635 //=============================================================================
637 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
639 myIsEmbeddedMode = theMode;
641 if ( !myIsEmbeddedMode ) {
642 //PAL10867: disable signals catching with "noexcepthandler" option
643 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
644 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
649 char* envDisableFPE = getenv("DISABLE_FPE");
650 if (envDisableFPE && atoi(envDisableFPE))
655 OSD::SetSignal( raiseFPE );
657 // else OSD::SetSignal() is called in GUI
661 //=============================================================================
663 * SMESH_Gen_i::IsEmbeddedMode
667 //=============================================================================
669 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
671 return myIsEmbeddedMode;
674 //=============================================================================
676 * SMESH_Gen_i::SetEnablePublish
678 * Set enable publishing in the study
680 //=============================================================================
682 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
684 myIsEnablePublish = theIsEnablePublish;
687 //=============================================================================
689 * SMESH_Gen_i::IsEnablePublish
691 * Check enable publishing
693 //=============================================================================
695 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
697 return myIsEnablePublish;
700 //=============================================================================
702 * SMESH_Gen_i::UpdateStudy
704 * Update study (needed at switching GEOM->SMESH)
706 //=============================================================================
708 void SMESH_Gen_i::UpdateStudy()
710 if ( !myStudyContext )
711 myStudyContext = new StudyContext;
713 SALOMEDS::Study_var aStudy = getStudyServant();
714 if ( !CORBA::is_nil( aStudy ) )
716 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
718 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
719 if( !GEOM_var->_is_nil() )
720 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
722 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
723 if( !GEOM_var->_is_nil() )
724 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
726 // NPAL16168, issue 0020210
727 // Let meshes update their data depending on GEOM groups that could change
728 CORBA::String_var compDataType = ComponentDataType();
729 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
730 if ( !me->_is_nil() ) {
731 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
732 for ( ; anIter->More(); anIter->Next() ) {
733 SALOMEDS::SObject_wrap so = anIter->Value();
734 CORBA::Object_var ior = SObjectToObject( so );
735 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
736 mesh->CheckGeomModif();
742 //================================================================================
744 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
746 //================================================================================
748 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
750 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
751 SALOMEDS::GenericAttribute_wrap attr;
752 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
754 SALOMEDS::AttributePixMap_wrap pm = attr;
755 CORBA::String_var ico = pm->GetPixMap();
756 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
761 //=================================================================================
762 // function : hasObjectInfo()
763 // purpose : shows if module provides information for its objects
764 //=================================================================================
766 bool SMESH_Gen_i::hasObjectInfo()
771 //=================================================================================
772 // function : getObjectInfo()
773 // purpose : returns an information for a given object by its entry
774 //=================================================================================
776 char* SMESH_Gen_i::getObjectInfo( const char* entry )
778 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
779 // for the rest, "module 'SMESH', ID=0:1:2:*"
783 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
784 CORBA::Object_var obj = SObjectToObject( so );
785 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
786 if ( isGeomModifIcon( mesh ))
788 txt << "The geometry was changed and the mesh needs to be recomputed";
793 CORBA::String_var compType = ComponentDataType();
794 txt << "module '" << compType << "', ID=" << entry;
796 return CORBA::string_dup( txt );
799 //=============================================================================
801 * SMESH_Gen_i::GetStudyContext
805 //=============================================================================
807 StudyContext* SMESH_Gen_i::GetStudyContext()
809 return myStudyContext;
812 //=============================================================================
814 * SMESH_Gen_i::CreateHypothesis
816 * Create hypothesis/algorithm of given type and publish it in the study
818 //=============================================================================
820 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
821 const char* theLibName )
822 throw ( SALOME::SALOME_Exception )
824 Unexpect aCatch(SALOME_SalomeException);
825 // Create hypothesis/algorithm
826 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
828 // Publish hypothesis/algorithm in the study
829 if ( CanPublishInStudy( hyp ) ) {
830 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
831 if ( !aSO->_is_nil() ) {
832 // Update Python script
833 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
834 << theHypName << "', '" << theLibName << "')";
841 //================================================================================
843 * \brief Return a hypothesis initialized by given average length.
844 * \param theHypType - hypothesis type name
845 * \param theLibName - plugin library name
846 * \param theAverageLength - average length
847 * \param theQuadDominated - is quad-dominated flag
848 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
850 //================================================================================
852 SMESH::SMESH_Hypothesis_ptr
853 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
854 const char* theLibName,
855 CORBA::Double theAverageLength,
856 CORBA::Boolean theQuadDominated)
857 throw ( SALOME::SALOME_Exception )
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)
898 throw ( SALOME::SALOME_Exception )
900 Unexpect aCatch(SALOME_SalomeException);
902 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
903 if ( byMesh && CORBA::is_nil( theMesh ) )
904 return SMESH::SMESH_Hypothesis::_nil();
905 if ( byMesh && CORBA::is_nil( theGeom ) )
906 return SMESH::SMESH_Hypothesis::_nil();
908 // -----------------------------------------------
909 // find hypothesis used to mesh theGeom
910 // -----------------------------------------------
912 // get mesh and shape
913 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
914 TopoDS_Shape shape = GeomObjectToShape( theGeom );
915 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
916 return SMESH::SMESH_Hypothesis::_nil();
917 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
919 // create a temporary hypothesis to know its dimension
920 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
921 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
923 return SMESH::SMESH_Hypothesis::_nil();
924 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
927 // look for a hypothesis of theHypType used to mesh the shape
928 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
931 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
932 int nbLocalHyps = aHypList->length();
933 for ( int i = 0; i < nbLocalHyps; i++ ) {
934 CORBA::String_var hypName = aHypList[i]->GetName();
935 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
936 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
938 // check super shapes
939 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
940 while ( nbLocalHyps == 0 && itShape.More() ) {
941 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
942 if ( ! CORBA::is_nil( geomObj )) {
943 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
944 nbLocalHyps = aHypList->length();
945 for ( int i = 0; i < nbLocalHyps; i++ )
946 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
947 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
953 // let the temporary hypothesis find out somehow parameter values by mesh
954 if ( hyp->SetParametersByMesh( mesh, shape ))
955 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
959 ::SMESH_Hypothesis::TDefaults dflts;
960 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
961 dflts._nbSegments = myGen.GetDefaultNbSegments();
962 dflts._elemLength = theParams.averageLength;
963 dflts._quadDominated = theParams.quadDominated;
964 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
967 dflts._diagonal = mesh->GetShapeDiagonalSize();
969 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
970 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
971 dflts._shape = &shape;
974 // let the hypothesis initialize it's values
975 if ( hyp->SetParametersByDefaults( dflts, mesh ))
976 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
979 return SMESH::SMESH_Hypothesis::_nil();
982 //=============================================================================
984 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
985 * \param [in] theHyp - the hypothesis of interest
986 * \param [out] theMesh - the sole mesh using \a theHyp
987 * \param [out] theShape - the sole geometry \a theHyp is assigned to
988 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
990 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
991 * considered as SAME sub-mesh => result is \c true.
992 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
993 * a shape to which an hyp being edited is assigned.
995 //=============================================================================
997 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
998 SMESH::SMESH_Mesh_out theMesh,
999 GEOM::GEOM_Object_out theShape)
1001 if ( CORBA::is_nil( theHyp ))
1004 // get Mesh component SO
1005 CORBA::String_var compDataType = ComponentDataType();
1006 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1007 if ( CORBA::is_nil( comp ))
1010 // look for child SO of meshes
1011 SMESH::SMESH_Mesh_var foundMesh;
1012 TopoDS_Shape foundShape;
1014 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1015 for ( ; meshIter->More() && isSole; meshIter->Next() )
1017 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1018 CORBA::Object_var obj = SObjectToObject( curSO );
1019 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1023 // look for a sole shape where theHyp is assigned
1024 bool isHypFound = false;
1025 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1026 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1027 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1029 const THypList& hyps = s2hypsIt.Value();
1030 THypList::const_iterator h = hyps.begin();
1031 for ( ; h != hyps.end(); ++h )
1032 if ( (*h)->GetID() == theHyp->GetId() )
1034 if ( h != hyps.end()) // theHyp found
1037 if ( ! foundShape.IsNull() &&
1038 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1040 foundShape.Nullify();
1044 foundShape = s2hypsIt.Key();
1046 } // loop on assigned hyps
1048 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1050 if ( !foundMesh->_is_nil() ) // not a sole mesh
1052 if ( !foundMesh->HasShapeToMesh() ||
1053 !mesh_i ->HasShapeToMesh() )
1055 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1059 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1060 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1061 isSole = s1->IsSame( s2 );
1064 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1070 ! foundMesh->_is_nil() &&
1071 ! foundShape.IsNull() )
1073 theMesh = foundMesh._retn();
1074 theShape = ShapeToGeomObject( foundShape );
1075 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1080 //=============================================================================
1082 * Set number of segments per diagonal of boundary box of geometry by which
1083 * default segment length of appropriate 1D hypotheses is defined
1085 //=============================================================================
1087 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1088 throw ( SALOME::SALOME_Exception )
1090 if ( theNbSegments > 0 )
1091 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1093 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1096 //=============================================================================
1098 * \brief Set default number of segments per edge
1100 //=============================================================================
1102 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1103 throw ( SALOME::SALOME_Exception )
1105 if ( theNbSegments > 0 )
1106 myGen.SetDefaultNbSegments( int(theNbSegments) );
1108 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1111 //=============================================================================
1113 * Set an option value
1115 //=============================================================================
1117 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1119 if ( name && value && strlen( value ) > 0 )
1122 if ( strcmp(name, "historical_python_dump") == 0 )
1124 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1125 msgToGUI = "preferences/SMESH/historical_python_dump/";
1126 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1128 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1130 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1131 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1132 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1134 else if ( strcmp(name, "default_grp_color") == 0 )
1138 // color must be presented as a string of following form:
1139 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1140 str = str.substr(1);
1141 for ( size_t i = 0; i < str.length()/2; i++ )
1142 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1143 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1145 else if ( value ) { // rgb color ("255,170,0", for example)
1146 string tempValue( value );
1147 char* colorValue = strtok( &tempValue[0], "," );
1148 while ( colorValue != NULL ) {
1149 int c_value = atoi( colorValue );
1150 if ( c_value >= 0 && c_value <= 255 )
1151 color.push_back( c_value );
1152 colorValue = strtok( NULL, "," );
1155 if ( color.size() == 3 ) { // color must have three valid component
1156 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1157 myDefaultGroupColor = value;
1158 msgToGUI = "preferences/SMESH/default_grp_color/";
1163 // update preferences in case if SetOption() is invoked from python console
1164 if ( !msgToGUI.empty() )
1166 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1167 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1168 if ( !CORBA::is_nil( session ) )
1169 session->emitMessageOneWay(msgToGUI.c_str());
1174 //=============================================================================
1176 * Return an option value
1178 //=============================================================================
1180 char* SMESH_Gen_i::GetOption(const char* name)
1184 if ( strcmp(name, "historical_python_dump") == 0 )
1186 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1188 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1190 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1192 if ( strcmp(name, "default_grp_color") == 0 )
1194 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1197 return CORBA::string_dup( "" );
1200 //=============================================================================
1202 * SMESH_Gen_i::CreateMesh
1204 * Create empty mesh on a shape and publish it in the study
1206 //=============================================================================
1208 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1209 throw ( SALOME::SALOME_Exception )
1211 Unexpect aCatch(SALOME_SalomeException);
1212 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1214 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1216 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1217 ASSERT( meshServant );
1218 meshServant->SetShape( theShapeObject );
1220 // publish mesh in the study
1221 if ( CanPublishInStudy( mesh ) ) {
1222 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1223 aStudyBuilder->NewCommand(); // There is a transaction
1224 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1225 aStudyBuilder->CommitCommand();
1226 if ( !aSO->_is_nil() ) {
1227 // Update Python script
1228 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1232 return mesh._retn();
1235 //=============================================================================
1237 * SMESH_Gen_i::CreateEmptyMesh
1241 //=============================================================================
1243 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1244 throw ( SALOME::SALOME_Exception )
1246 Unexpect aCatch(SALOME_SalomeException);
1247 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1249 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1251 // publish mesh in the study
1252 if ( CanPublishInStudy( mesh ) ) {
1253 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1254 aStudyBuilder->NewCommand(); // There is a transaction
1255 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1256 aStudyBuilder->CommitCommand();
1257 if ( !aSO->_is_nil() ) {
1258 // Update Python script
1259 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1263 return mesh._retn();
1268 //================================================================================
1270 * \brief Throw an exception in case if the file can't be read
1272 //================================================================================
1274 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1276 SMESH_File f ( theFileName );
1279 if ( !f.error().empty() )
1280 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1282 THROW_SALOME_CORBA_EXCEPTION
1283 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1284 SALOME::BAD_PARAM );
1289 //=============================================================================
1291 * SMESH_Gen_i::CreateMeshFromUNV
1293 * Create mesh and import data from UNV file
1295 //=============================================================================
1297 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1298 throw ( SALOME::SALOME_Exception )
1300 Unexpect aCatch(SALOME_SalomeException);
1302 checkFileReadable( theFileName );
1304 SMESH::SMESH_Mesh_var aMesh = createMesh();
1306 // publish mesh in the study
1307 if ( CanPublishInStudy( aMesh ) ) {
1308 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1309 aStudyBuilder->NewCommand(); // There is a transaction
1310 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1311 aStudyBuilder->CommitCommand();
1312 if ( !aSO->_is_nil() ) {
1313 // Update Python script
1314 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1318 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1320 aServant->ImportUNVFile( theFileName );
1322 // Dump creation of groups
1323 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1325 aServant->GetImpl().GetMeshDS()->Modified();
1326 return aMesh._retn();
1329 //=============================================================================
1331 * SMESH_Gen_i::CreateMeshFromMED
1333 * Create mesh and import data from MED file
1335 //=============================================================================
1337 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1338 SMESH::DriverMED_ReadStatus& theStatus,
1339 const char* theCommandNameForPython,
1340 const char* theFileNameForPython)
1343 char bname[ _MAX_FNAME ];
1344 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1345 string aFileName = bname;
1347 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1349 // Retrieve mesh names from the file
1350 DriverMED_R_SMESHDS_Mesh myReader;
1351 myReader.SetFile( theFileName );
1352 myReader.SetMeshId( -1 );
1353 Driver_Mesh::Status aStatus;
1354 list<string> aNames = myReader.GetMeshNames(aStatus);
1355 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1356 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1358 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1361 TPythonDump aPythonDump;
1362 aPythonDump << "([";
1364 if (theStatus == SMESH::DRS_OK) {
1365 SALOMEDS::StudyBuilder_var aStudyBuilder;
1366 aStudyBuilder = getStudyServant()->NewBuilder();
1367 aStudyBuilder->NewCommand(); // There is a transaction
1369 aResult->length( aNames.size() );
1372 // Iterate through all meshes and create mesh objects
1373 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1376 if (i > 0) aPythonDump << ", ";
1379 SMESH::SMESH_Mesh_var mesh = createMesh();
1381 // publish mesh in the study
1382 SALOMEDS::SObject_wrap aSO;
1383 if ( CanPublishInStudy( mesh ) )
1384 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1385 // - as names of meshes are stored in MED file, we use them for data publishing
1386 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1387 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1390 if ( !aSO->_is_nil() ) {
1393 aPythonDump << "mesh_" << i;
1396 // Read mesh data (groups are published automatically by ImportMEDFile())
1397 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1398 ASSERT( meshServant );
1399 SMESH::DriverMED_ReadStatus status1 =
1400 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1401 if (status1 > theStatus)
1402 theStatus = status1;
1404 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1405 meshServant->GetImpl().GetMeshDS()->Modified();
1407 if ( !aStudyBuilder->_is_nil() )
1408 aStudyBuilder->CommitCommand();
1411 // Update Python script
1412 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1414 // Dump creation of groups
1415 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1416 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1418 return aResult._retn();
1421 //================================================================================
1423 * \brief Create meshes by reading a MED file
1425 //================================================================================
1427 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1428 SMESH::DriverMED_ReadStatus& theStatus)
1429 throw ( SALOME::SALOME_Exception )
1431 Unexpect aCatch(SALOME_SalomeException);
1432 checkFileReadable( theFileName );
1434 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1435 "CreateMeshesFromMED", theFileName);
1439 //=============================================================================
1441 * SMESH_Gen_i::CreateMeshFromSAUV
1443 * Create mesh and import data from SAUV file
1445 //=============================================================================
1447 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1448 SMESH::DriverMED_ReadStatus& theStatus)
1449 throw ( SALOME::SALOME_Exception )
1451 Unexpect aCatch(SALOME_SalomeException);
1452 checkFileReadable( theFileName );
1454 std::string sauvfilename(theFileName);
1455 std::string medfilename(theFileName);
1456 medfilename += ".med";
1459 cmd = "%PYTHONBIN% ";
1464 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1466 system(cmd.c_str());
1467 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1469 "CreateMeshesFromSAUV",
1470 sauvfilename.c_str());
1472 cmd = "%PYTHONBIN% ";
1477 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1479 system(cmd.c_str());
1483 //=============================================================================
1485 * SMESH_Gen_i::CreateMeshFromSTL
1487 * Create mesh and import data from STL file
1489 //=============================================================================
1491 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1492 throw ( SALOME::SALOME_Exception )
1494 Unexpect aCatch(SALOME_SalomeException);
1495 checkFileReadable( theFileName );
1497 SMESH::SMESH_Mesh_var aMesh = createMesh();
1500 char bname[ _MAX_FNAME ];
1501 _splitpath( theFileName, NULL, NULL, bname, NULL );
1502 string aFileName = bname;
1504 string aFileName = basename( const_cast<char *>(theFileName) );
1506 // publish mesh in the study
1507 if ( CanPublishInStudy( aMesh ) ) {
1508 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1509 aStudyBuilder->NewCommand(); // There is a transaction
1510 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1511 aStudyBuilder->CommitCommand();
1512 if ( !aSO->_is_nil() ) {
1513 // Update Python script
1514 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1518 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1520 aServant->ImportSTLFile( theFileName );
1521 aServant->GetImpl().GetMeshDS()->Modified();
1522 return aMesh._retn();
1525 //================================================================================
1527 * \brief Create meshes and import data from the CGSN file
1529 //================================================================================
1531 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1532 SMESH::DriverMED_ReadStatus& theStatus)
1533 throw ( SALOME::SALOME_Exception )
1535 Unexpect aCatch(SALOME_SalomeException);
1536 checkFileReadable( theFileName );
1538 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1541 // Retrieve nb meshes from the file
1542 DriverCGNS_Read myReader;
1543 myReader.SetFile( theFileName );
1544 Driver_Mesh::Status aStatus;
1545 int nbMeshes = myReader.GetNbMeshes(aStatus);
1546 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1548 aResult->length( nbMeshes );
1550 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1553 TPythonDump aPythonDump;
1554 aPythonDump << "([";
1556 if (theStatus == SMESH::DRS_OK)
1558 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1559 aStudyBuilder->NewCommand(); // There is a transaction
1563 // Iterate through all meshes and create mesh objects
1564 for ( ; i < nbMeshes; ++i )
1567 if (i > 0) aPythonDump << ", ";
1570 SMESH::SMESH_Mesh_var mesh = createMesh();
1571 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1573 // Read mesh data (groups are published automatically by ImportMEDFile())
1574 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1575 ASSERT( meshServant );
1577 SMESH::DriverMED_ReadStatus status1 =
1578 meshServant->ImportCGNSFile( theFileName, i, meshName );
1579 if (status1 > theStatus)
1580 theStatus = status1;
1582 meshServant->GetImpl().GetMeshDS()->Modified();
1583 // publish mesh in the study
1584 SALOMEDS::SObject_wrap aSO;
1585 if ( CanPublishInStudy( mesh ) )
1586 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1589 if ( !aSO->_is_nil() ) {
1593 aPythonDump << "mesh_" << i;
1596 aStudyBuilder->CommitCommand();
1599 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1601 // Dump creation of groups
1602 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1603 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1605 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1608 return aResult._retn();
1611 //================================================================================
1613 * \brief Create a mesh and import data from a GMF file
1615 //================================================================================
1617 SMESH::SMESH_Mesh_ptr
1618 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1619 CORBA::Boolean theMakeRequiredGroups,
1620 SMESH::ComputeError_out theError)
1621 throw ( SALOME::SALOME_Exception )
1623 Unexpect aCatch(SALOME_SalomeException);
1624 checkFileReadable( theFileName );
1626 SMESH::SMESH_Mesh_var aMesh = createMesh();
1628 char bname[ _MAX_FNAME ];
1629 _splitpath( theFileName, NULL, NULL, bname, NULL );
1630 string aFileName = bname;
1632 string aFileName = basename( const_cast<char *>(theFileName) );
1634 // publish mesh in the study
1635 if ( CanPublishInStudy( aMesh ) ) {
1636 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1637 aStudyBuilder->NewCommand(); // There is a transaction
1638 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1639 aStudyBuilder->CommitCommand();
1640 if ( !aSO->_is_nil() ) {
1641 // Update Python script
1642 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1643 << theFileName << "', "
1644 << theMakeRequiredGroups << " )";
1647 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1649 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1650 aServant->GetImpl().GetMeshDS()->Modified();
1651 return aMesh._retn();
1655 //=============================================================================
1657 * SMESH_Gen_i::IsReadyToCompute
1659 * Return true if mesh contains enough data to be computed
1661 //=============================================================================
1663 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1664 GEOM::GEOM_Object_ptr theShapeObject )
1665 throw ( SALOME::SALOME_Exception )
1667 Unexpect aCatch(SALOME_SalomeException);
1668 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1670 if ( CORBA::is_nil( theShapeObject ) )
1671 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1672 SALOME::BAD_PARAM );
1673 if ( CORBA::is_nil( theMesh ) )
1674 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1675 SALOME::BAD_PARAM );
1678 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1679 ASSERT( meshServant );
1680 if ( meshServant ) {
1681 // get local TopoDS_Shape
1682 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1683 // call implementation
1684 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1685 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1688 catch ( SALOME_Exception& S_ex ) {
1689 INFOS( "catch exception "<< S_ex.what() );
1694 //================================================================================
1696 * \brief Find SObject for an algo
1698 //================================================================================
1700 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1703 SALOMEDS::Study_var aStudy = getStudyServant();
1704 if ( !aStudy->_is_nil() ) {
1705 // find algo in the study
1706 CORBA::String_var compDataType = ComponentDataType();
1707 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1708 if ( !father->_is_nil() ) {
1709 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1710 for ( ; itBig->More(); itBig->Next() ) {
1711 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1712 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1713 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1714 for ( ; algoIt->More(); algoIt->Next() ) {
1715 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1716 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1717 if ( !CORBA::is_nil( algoIOR )) {
1718 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1719 if ( impl && impl->GetImpl() == algo )
1720 return algoSO._retn();
1722 } // loop on algo SO's
1725 } // SMESH component iterator
1729 return SALOMEDS::SObject::_nil();
1732 //================================================================================
1734 * \brief Return errors of mesh computation
1736 //================================================================================
1738 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1739 GEOM::GEOM_Object_ptr theSubObject )
1740 throw ( SALOME::SALOME_Exception )
1742 Unexpect aCatch(SALOME_SalomeException);
1743 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1745 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1746 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1748 if ( CORBA::is_nil( theMesh ) )
1749 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1751 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1753 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1756 if(theMesh->HasShapeToMesh())
1757 shape = GeomObjectToShape( theSubObject );
1759 shape = SMESH_Mesh::PseudoShape();
1761 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1763 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1766 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1767 const bool includeSelf = true, complexShapeFirst = true;
1768 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1770 while ( smIt->more() )
1773 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1775 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1776 if ( error && !error->IsOK() )
1778 if ( !( error->myAlgo ) &&
1779 !( error->myAlgo = sm->GetAlgo() ))
1781 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1782 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1783 errStruct.comment = error->myComment.c_str();
1784 errStruct.subShapeID = sm->GetId();
1785 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1786 if ( !algoSO->_is_nil() ) {
1787 CORBA::String_var algoName = algoSO->GetName();
1788 errStruct.algoName = algoName;
1791 errStruct.algoName = error->myAlgo->GetName();
1793 errStruct.hasBadMesh = error->HasBadElems();
1796 error_array->length( nbErr );
1799 catch ( SALOME_Exception& S_ex ) {
1800 INFOS( "catch exception "<< S_ex.what() );
1803 return error_array._retn();
1806 //================================================================================
1808 * \brief Return mesh elements preventing computation of a subshape
1810 //================================================================================
1812 SMESH::MeshPreviewStruct*
1813 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1814 CORBA::Short theSubShapeID )
1815 throw ( SALOME::SALOME_Exception )
1817 Unexpect aCatch(SALOME_SalomeException);
1818 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1820 if ( CORBA::is_nil( theMesh ) )
1821 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1823 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1826 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1828 // mesh implementation
1829 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1830 // submesh by subshape id
1831 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1834 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1835 if ( error && error->HasBadElems() )
1837 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1838 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1840 // get nodes of elements and count elements
1841 TNode2LocalIDMap mapNode2LocalID;
1842 list< TNodeLocalID > connectivity;
1843 int i, nbElements = 0, nbConnNodes = 0;
1845 const list<const SMDS_MeshElement*>& badElems =
1846 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1847 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1848 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1849 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1851 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1852 while ( nIt->more() )
1853 connectivity.push_back
1854 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1856 // fill node coords and assign local ids to the nodes
1857 int nbNodes = mapNode2LocalID.size();
1858 result->nodesXYZ.length( nbNodes );
1859 TNodeLocalID node2ID = mapNode2LocalID.begin();
1860 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1861 node2ID->second = i;
1862 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1863 result->nodesXYZ[i].x = node->X();
1864 result->nodesXYZ[i].y = node->Y();
1865 result->nodesXYZ[i].z = node->Z();
1867 // fill connectivity
1868 result->elementConnectivities.length( nbConnNodes );
1869 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1870 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1871 result->elementConnectivities[i] = (*connIt)->second;
1873 // fill element types
1874 result->elementTypes.length( nbElements );
1875 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1877 const SMDS_MeshElement* elem = *elemIt;
1878 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1879 result->elementTypes[i].isPoly = elem->IsPoly();
1880 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1886 catch ( SALOME_Exception& S_ex ) {
1887 INFOS( "catch exception "<< S_ex.what() );
1890 return result._retn();
1893 //================================================================================
1895 * \brief Create a group of elements preventing computation of a sub-shape
1897 //================================================================================
1899 SMESH::ListOfGroups*
1900 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1901 CORBA::Short theSubShapeID,
1902 const char* theGroupName )
1903 throw ( SALOME::SALOME_Exception )
1905 Unexpect aCatch(SALOME_SalomeException);
1907 SMESH::ListOfGroups_var groups;
1909 if ( CORBA::is_nil( theMesh ) )
1910 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1913 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1915 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1916 TPythonDump() << groups << " = " << this
1917 << ".MakeGroupsOfBadInputElements( "
1918 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1921 catch ( SALOME_Exception& S_ex ) {
1922 INFOS( "catch exception "<< S_ex.what() );
1924 return groups._retn();
1927 //================================================================================
1929 * \brief Returns errors of hypotheses definition
1930 * \param theMesh - the mesh
1931 * \param theSubObject - the main or sub- shape
1932 * \retval SMESH::algo_error_array* - sequence of errors
1934 //================================================================================
1936 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1937 GEOM::GEOM_Object_ptr theSubObject )
1938 throw ( SALOME::SALOME_Exception )
1940 Unexpect aCatch(SALOME_SalomeException);
1941 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1943 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1944 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1946 if ( CORBA::is_nil( theMesh ) )
1947 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1949 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1951 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1952 ASSERT( meshServant );
1953 if ( meshServant ) {
1954 TopoDS_Shape myLocShape;
1955 if(theMesh->HasShapeToMesh())
1956 myLocShape = GeomObjectToShape( theSubObject );
1958 myLocShape = SMESH_Mesh::PseudoShape();
1960 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1961 list< ::SMESH_Gen::TAlgoStateError > error_list;
1962 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1963 // call ::SMESH_Gen::GetAlgoState()
1964 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1965 error_array->length( error_list.size() );
1967 for ( error = error_list.begin(); error != error_list.end(); ++error )
1969 // fill AlgoStateError structure
1970 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1971 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1972 errStruct.algoDim = error->_algoDim;
1973 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1974 errStruct.algoName = "";
1975 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1976 if ( !algoSO->_is_nil() ) {
1977 CORBA::String_var algoName = algoSO->GetName();
1978 errStruct.algoName = algoName.in();
1983 catch ( SALOME_Exception& S_ex ) {
1984 INFOS( "catch exception "<< S_ex.what() );
1986 return error_array._retn();
1989 //=============================================================================
1991 * SMESH_Gen_i::GetSubShapesId
1993 * Get sub-shapes unique ID's list
1995 //=============================================================================
1998 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1999 const SMESH::object_array& theListOfSubShapeObject )
2000 throw ( SALOME::SALOME_Exception )
2002 Unexpect aCatch(SALOME_SalomeException);
2003 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
2005 SMESH::long_array_var shapesId = new SMESH::long_array;
2008 if ( CORBA::is_nil( theMainShapeObject ) )
2009 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2013 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
2014 TopTools_IndexedMapOfShape myIndexToShape;
2015 TopExp::MapShapes(myMainShape,myIndexToShape);
2017 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
2019 GEOM::GEOM_Object_var aShapeObject
2020 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
2021 if ( CORBA::is_nil( aShapeObject ) )
2022 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
2023 SALOME::BAD_PARAM );
2025 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
2026 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2028 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2029 setId.insert(myIndexToShape.FindIndex(F));
2030 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2032 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2034 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2035 setId.insert(myIndexToShape.FindIndex(E));
2036 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2038 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2040 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2041 setId.insert(myIndexToShape.FindIndex(V));
2042 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2045 shapesId->length(setId.size());
2046 set<int>::iterator iind;
2048 for (iind = setId.begin(); iind != setId.end(); iind++)
2050 if(MYDEBUG) SCRUTE((*iind));
2051 shapesId[i] = (*iind);
2052 if(MYDEBUG) SCRUTE(shapesId[i]);
2056 catch (SALOME_Exception& S_ex)
2058 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2061 return shapesId._retn();
2064 //=============================================================================
2066 * SMESH_Gen_i::Compute
2068 * Compute mesh on a shape
2070 //=============================================================================
2072 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2073 GEOM::GEOM_Object_ptr theShapeObject )
2074 throw ( SALOME::SALOME_Exception )
2077 Unexpect aCatch(SALOME_SalomeException);
2078 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2080 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2081 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2082 SALOME::BAD_PARAM );
2084 if ( CORBA::is_nil( theMesh ) )
2085 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2086 SALOME::BAD_PARAM );
2088 // Update Python script
2089 TPythonDump() << "isDone = " << this << ".Compute( "
2090 << theMesh << ", " << theShapeObject << ")";
2094 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2095 ASSERT( meshServant );
2096 if ( meshServant ) {
2097 if ( isGeomModifIcon( theMesh ))
2098 meshServant->Clear();
2100 meshServant->Load();
2101 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2102 meshServant->CheckGeomModif();
2103 // get local TopoDS_Shape
2104 TopoDS_Shape myLocShape;
2105 if(theMesh->HasShapeToMesh())
2106 myLocShape = GeomObjectToShape( theShapeObject );
2108 myLocShape = SMESH_Mesh::PseudoShape();
2109 // call implementation compute
2110 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2111 myGen.PrepareCompute( myLocMesh, myLocShape );
2112 int how = ::SMESH_Gen::COMPACT_MESH;
2113 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2114 how |= ::SMESH_Gen::SHAPE_ONLY;
2115 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2116 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2117 myLocMesh.GetMeshDS()->Modified();
2118 UpdateIcons( theMesh );
2120 HighLightInvalid( theMesh, /*isInvalid=*/false );
2124 catch ( std::bad_alloc ) {
2125 INFOS( "Compute(): lack of memory" );
2127 catch ( SALOME_Exception& S_ex ) {
2128 INFOS( "Compute(): catch exception "<< S_ex.what() );
2131 INFOS( "Compute(): unknown exception " );
2136 //=============================================================================
2138 * SMESH_Gen_i::CancelCompute
2140 * Cancel Compute mesh on a shape
2142 //=============================================================================
2144 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2145 GEOM::GEOM_Object_ptr theShapeObject )
2147 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2149 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2150 TopoDS_Shape myLocShape;
2151 if(theMesh->HasShapeToMesh())
2152 myLocShape = GeomObjectToShape( theShapeObject );
2154 myLocShape = SMESH_Mesh::PseudoShape();
2155 myGen.CancelCompute( myLocMesh, myLocShape);
2159 //=============================================================================
2161 * SMESH_Gen_i::Precompute
2163 * Compute mesh as preview till indicated dimension on shape
2165 //=============================================================================
2167 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2168 GEOM::GEOM_Object_ptr theShapeObject,
2169 SMESH::Dimension theDimension,
2170 SMESH::long_array& theShapesId)
2171 throw ( SALOME::SALOME_Exception )
2173 Unexpect aCatch(SALOME_SalomeException);
2174 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2176 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2177 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2178 SALOME::BAD_PARAM );
2180 if ( CORBA::is_nil( theMesh ) )
2181 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2182 SALOME::BAD_PARAM );
2184 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2187 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2188 meshServant->Load();
2189 ASSERT( meshServant );
2190 if ( meshServant ) {
2191 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2192 meshServant->CheckGeomModif();
2193 // get local TopoDS_Shape
2194 TopoDS_Shape myLocShape;
2195 if(theMesh->HasShapeToMesh())
2196 myLocShape = GeomObjectToShape( theShapeObject );
2198 return result._retn();
2200 // call implementation compute
2201 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2203 ::MeshDimension aDim = (MeshDimension)theDimension;
2204 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2206 int nbShapeId = shapeIds.size();
2207 theShapesId.length( nbShapeId );
2208 // iterates on shapes and collect mesh entities into mesh preview
2209 TSetOfInt::const_iterator idIt = shapeIds.begin();
2210 TSetOfInt::const_iterator idEnd = shapeIds.end();
2211 std::map< int, int > mapOfShIdNb;
2212 std::set< SMESH_TLink > setOfEdge;
2213 std::list< SMDSAbs_ElementType > listOfElemType;
2214 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2215 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2216 TNode2LocalIDMap mapNode2LocalID;
2217 list< TNodeLocalID > connectivity;
2218 int i, nbConnNodes = 0;
2219 std::set< const SMESH_subMesh* > setOfVSubMesh;
2220 // iterates on shapes
2221 for ( ; idIt != idEnd; idIt++ )
2223 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2225 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2226 if ( !sm || !sm->IsMeshComputed() )
2229 const TopoDS_Shape& aSh = sm->GetSubShape();
2230 const int shDim = myGen.GetShapeDim( aSh );
2231 if ( shDim < 1 || shDim > theDimension )
2234 mapOfShIdNb[ *idIt ] = 0;
2235 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2237 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2238 if ( !smDS ) continue;
2240 if ( theDimension == SMESH::DIM_2D )
2242 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2243 while ( faceIt->more() )
2245 const SMDS_MeshElement* face = faceIt->next();
2246 int aNbNode = face->NbNodes();
2248 aNbNode /= 2; // do not take into account additional middle nodes
2250 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2251 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2253 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2254 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2256 listOfElemType.push_back( SMDSAbs_Edge );
2257 connectivity.push_back
2258 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2259 connectivity.push_back
2260 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2266 else if ( theDimension == SMESH::DIM_1D )
2268 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2269 while ( nodeIt->more() )
2271 listOfElemType.push_back( SMDSAbs_Node );
2272 connectivity.push_back
2273 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2275 // add corner nodes by first vertex from edge
2276 SMESH_subMeshIteratorPtr edgeSmIt =
2277 sm->getDependsOnIterator(/*includeSelf*/false,
2278 /*complexShapeFirst*/false);
2279 while ( edgeSmIt->more() )
2281 SMESH_subMesh* vertexSM = edgeSmIt->next();
2282 // check that vertex is not already treated
2283 if ( !setOfVSubMesh.insert( vertexSM ).second )
2285 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2288 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2289 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2290 while ( nodeIt->more() )
2292 listOfElemType.push_back( SMDSAbs_Node );
2293 connectivity.push_back
2294 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2300 // fill node coords and assign local ids to the nodes
2301 int nbNodes = mapNode2LocalID.size();
2302 result->nodesXYZ.length( nbNodes );
2303 TNodeLocalID node2ID = mapNode2LocalID.begin();
2304 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2305 node2ID->second = i;
2306 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2307 result->nodesXYZ[i].x = node->X();
2308 result->nodesXYZ[i].y = node->Y();
2309 result->nodesXYZ[i].z = node->Z();
2311 // fill connectivity
2312 result->elementConnectivities.length( nbConnNodes );
2313 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2314 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2315 result->elementConnectivities[i] = (*connIt)->second;
2318 // fill element types
2319 result->elementTypes.length( listOfElemType.size() );
2320 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2321 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2322 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2324 SMDSAbs_ElementType elemType = *typeIt;
2325 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2326 result->elementTypes[i].isPoly = false;
2327 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2330 // correct number of shapes
2331 theShapesId.length( mapOfShIdNb.size() );
2335 catch ( std::bad_alloc ) {
2336 INFOS( "Precompute(): lack of memory" );
2338 catch ( SALOME_Exception& S_ex ) {
2339 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2342 INFOS( "Precompute(): unknown exception " );
2344 return result._retn();
2348 //=============================================================================
2350 * SMESH_Gen_i::Evaluate
2352 * Evaluate mesh on a shape
2354 //=============================================================================
2356 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2357 GEOM::GEOM_Object_ptr theShapeObject)
2358 // SMESH::long_array& theNbElems)
2359 throw ( SALOME::SALOME_Exception )
2361 Unexpect aCatch(SALOME_SalomeException);
2362 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2364 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2365 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2367 if ( CORBA::is_nil( theMesh ) )
2368 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2370 SMESH::long_array_var nbels = new SMESH::long_array;
2371 nbels->length(SMESH::Entity_Last);
2372 int i = SMESH::Entity_Node;
2373 for (; i < SMESH::Entity_Last; i++)
2376 // Update Python script
2377 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2378 << theMesh << ", " << theShapeObject << ")";
2382 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2383 ASSERT( meshServant );
2384 if ( meshServant ) {
2385 meshServant->Load();
2386 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2387 meshServant->CheckGeomModif();
2388 // get local TopoDS_Shape
2389 TopoDS_Shape myLocShape;
2390 if(theMesh->HasShapeToMesh())
2391 myLocShape = GeomObjectToShape( theShapeObject );
2393 myLocShape = SMESH_Mesh::PseudoShape();
2394 // call implementation compute
2395 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2396 MapShapeNbElems aResMap;
2397 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2398 MapShapeNbElemsItr anIt = aResMap.begin();
2399 for(; anIt!=aResMap.end(); anIt++) {
2400 const vector<int>& aVec = (*anIt).second;
2401 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2402 int nbElem = aVec[i];
2403 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2405 SMESH_subMesh* sm = anIt->first;
2406 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2407 const SMESH_Algo* algo = sm->GetAlgo();
2408 if ( (algo && !error.get()) || error->IsOK() )
2409 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2413 nbels[i] += aVec[i];
2417 return nbels._retn();
2420 catch ( std::bad_alloc ) {
2421 INFOS( "Evaluate(): lack of memory" );
2423 catch ( SALOME_Exception& S_ex ) {
2424 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2427 INFOS( "Evaluate(): unknown exception " );
2430 return nbels._retn();
2433 //================================================================================
2435 * \brief Return geometrical object the given element is built on
2436 * \param theMesh - the mesh the element is in
2437 * \param theElementID - the element ID
2438 * \param theGeomName - the name of the result geom object if it is not yet published
2439 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2441 //================================================================================
2443 GEOM::GEOM_Object_ptr
2444 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2445 CORBA::Long theElementID,
2446 const char* theGeomName)
2447 throw ( SALOME::SALOME_Exception )
2449 Unexpect aCatch(SALOME_SalomeException);
2451 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2452 if ( !geom->_is_nil() ) {
2453 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2454 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2456 // try to find the corresponding SObject
2457 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2458 if ( SObj->_is_nil() ) // submesh can be not found even if published
2460 // try to find published submesh
2461 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2462 if ( !geom->IsMainShape() && list->length() == 1 ) {
2463 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2464 SALOMEDS::ChildIterator_wrap it;
2465 if ( !mainSO->_is_nil() ) {
2466 it = getStudyServant()->NewChildIterator( mainSO );
2468 if ( !it->_is_nil() ) {
2469 for ( it->InitEx(true); it->More(); it->Next() ) {
2470 SALOMEDS::SObject_wrap so = it->Value();
2471 CORBA::Object_var obj = SObjectToObject( so );
2472 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2473 if ( !subGeom->_is_nil() ) {
2474 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2475 if ( subList->length() == 1 && list[0] == subList[0] ) {
2485 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2486 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2488 // return only published geometry
2489 if ( !SObj->_is_nil() ) {
2490 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2491 CORBA::Object_var obj = SObjectToObject( SObj );
2492 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2496 return GEOM::GEOM_Object::_nil();
2499 //================================================================================
2501 * \brief Return geometrical object the given element is built on.
2502 * \param theMesh - the mesh the element is in
2503 * \param theElementID - the element ID
2504 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2506 //================================================================================
2508 GEOM::GEOM_Object_ptr
2509 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2510 CORBA::Long theElementID)
2511 throw ( SALOME::SALOME_Exception )
2513 Unexpect aCatch(SALOME_SalomeException);
2514 if ( CORBA::is_nil( theMesh ) )
2515 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2517 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2518 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2520 // get a core mesh DS
2521 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2522 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2524 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2525 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2526 // find the element in mesh
2527 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2528 // find a shape id by the element
2529 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2530 // get a geom object by the shape id
2531 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2532 if ( geom->_is_nil() ) {
2533 // try to find a published sub-shape
2534 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2535 SALOMEDS::ChildIterator_wrap it;
2536 if ( !mainSO->_is_nil() ) {
2537 it = getStudyServant()->NewChildIterator( mainSO );
2539 if ( !it->_is_nil() ) {
2540 for ( it->InitEx(true); it->More(); it->Next() ) {
2541 SALOMEDS::SObject_wrap so = it->Value();
2542 CORBA::Object_var obj = SObjectToObject( so );
2543 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2544 if ( !subGeom->_is_nil() ) {
2545 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2546 if ( subList->length() == 1 && shapeID == subList[0] ) {
2554 if ( geom->_is_nil() ) {
2556 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2557 if ( !op->_is_nil() )
2558 geom = op->GetSubShape( mainShape, shapeID );
2563 if ( !geom->_is_nil() ) {
2564 GeomObjectToShape( geom ); // let geom client remember the found shape
2565 return geom._retn();
2570 return GEOM::GEOM_Object::_nil();
2573 //================================================================================
2575 * SMESH_Gen_i::Concatenate
2577 * Concatenate the given meshes into one mesh
2579 //================================================================================
2581 SMESH::SMESH_Mesh_ptr
2582 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2583 CORBA::Boolean theUniteIdenticalGroups,
2584 CORBA::Boolean theMergeNodesAndElements,
2585 CORBA::Double theMergeTolerance,
2586 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2587 throw ( SALOME::SALOME_Exception )
2589 return ConcatenateCommon(theMeshesArray,
2590 theUniteIdenticalGroups,
2591 theMergeNodesAndElements,
2597 //================================================================================
2599 * SMESH_Gen_i::ConcatenateWithGroups
2601 * Concatenate the given meshes into one mesh
2602 * Create the groups of all elements from initial meshes
2604 //================================================================================
2606 SMESH::SMESH_Mesh_ptr
2607 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2608 CORBA::Boolean theUniteIdenticalGroups,
2609 CORBA::Boolean theMergeNodesAndElements,
2610 CORBA::Double theMergeTolerance,
2611 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2612 throw ( SALOME::SALOME_Exception )
2614 return ConcatenateCommon(theMeshesArray,
2615 theUniteIdenticalGroups,
2616 theMergeNodesAndElements,
2622 //================================================================================
2624 * SMESH_Gen_i::ConcatenateCommon
2626 * Concatenate the given meshes into one mesh
2628 //================================================================================
2630 SMESH::SMESH_Mesh_ptr
2631 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2632 CORBA::Boolean theUniteIdenticalGroups,
2633 CORBA::Boolean theMergeNodesAndElements,
2634 CORBA::Double theMergeTolerance,
2635 CORBA::Boolean theCommonGroups,
2636 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2637 throw ( SALOME::SALOME_Exception )
2639 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2640 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2642 // create mesh if theMeshToAppendTo not provided
2643 SMESH::SMESH_Mesh_var newMesh;
2644 if ( CORBA::is_nil( theMeshToAppendTo ))
2645 newMesh = CreateEmptyMesh();
2647 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2648 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2649 if ( !newImpl ) return newMesh._retn();
2652 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2653 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2655 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2656 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2657 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2658 TGroupsMap groupsMap;
2659 TListOfNewGroups listOfNewGroups;
2661 if ( !CORBA::is_nil( theMeshToAppendTo ))
2663 // fill groupsMap with existing groups
2664 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2665 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2667 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2668 if ( !group->_is_nil() )
2670 CORBA::String_var name = group->GetName();
2671 SMESH::ElementType type = group->GetType();
2672 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2677 ::SMESH_MeshEditor newEditor( &locMesh );
2678 ::SMESH_MeshEditor::ElemFeatures elemType;
2680 // loop on sub-meshes
2681 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2683 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2684 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2685 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2686 if ( !initImpl ) continue;
2687 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2691 // assure that IDs increment by one during iteration
2692 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2693 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2694 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2695 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2697 initMeshDS->Modified();
2698 initMeshDS->CompactMesh();
2701 // remember nb of elements before filling in
2702 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2706 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2707 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2708 while ( elemIt->more() )
2710 SMESH_NodeXYZ node = elemIt->next();
2711 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2716 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2717 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2719 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2720 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2721 while ( elemIt->more() )
2723 const SMDS_MeshElement* elem = elemIt->next();
2724 elemType.myNodes.resize( elem->NbNodes() );
2726 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2727 for ( int k = 0; itNodes->more(); k++)
2729 const SMDS_MeshNode* node = itNodes->next();
2730 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2733 // creates a corresponding element on existent nodes in new mesh
2734 newElems[ elem->GetID() ] =
2735 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2737 newEditor.ClearLastCreated(); // forget the history
2740 // create groups of just added elements
2741 SMESH::SMESH_Group_var newGroup;
2742 SMESH::ElementType groupType;
2743 if ( theCommonGroups )
2746 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2747 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2748 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2749 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2752 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2754 for( groupType = SMESH::NODE;
2755 groupType < SMESH::NB_ELEMENT_TYPES;
2756 groupType = (SMESH::ElementType)( groupType + 1 ))
2758 if ( curState[ groupType ] <= prevState[ groupType ])
2759 continue; // no elements of groupType added from the i-th mesh
2761 // make a group name
2762 std::string groupName = "Gr";
2763 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2765 CORBA::String_var name = meshSO->GetName();
2769 groupName += typeNames[ groupType ];
2771 // make and fill a group
2772 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2773 std::vector< const SMDS_MeshElement* > & elemVec =
2774 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2775 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2777 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2779 for ( size_t j = 0; j < elemVec.size(); ++j )
2781 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2782 grpDS->Add( elemVec[j] );
2786 listOfNewGroups.clear();
2787 listOfNewGroups.push_back( newGroup );
2788 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2793 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2797 SMESH::SMESH_GroupBase_ptr group;
2798 CORBA::String_var groupName;
2799 SMESH::long_array_var newIDs = new SMESH::long_array();
2801 // loop on groups of a source mesh
2802 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2803 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2805 group = listOfGroups[iG];
2806 groupType = group->GetType();
2807 groupName = group->GetName();
2808 std::string name = groupName.in();
2810 // convert a list of IDs
2811 newIDs->length( group->Size() );
2812 std::vector< const SMDS_MeshElement* > & elemVec =
2813 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2814 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2816 while ( itGrElems->more() )
2818 const SMDS_MeshElement* elem = itGrElems->next();
2819 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2821 newIDs[ nbElems++ ] = newElem->GetID();
2823 newIDs->length( nbElems );
2825 // check that a current group name and type don't have identical ones in final mesh
2826 listOfNewGroups.clear();
2827 TNameAndType nameAndType( name, groupType );
2828 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2829 if ( anIter == groupsMap.end() )
2831 // add a new group in the mesh
2832 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2833 newGroup->Add( newIDs );
2835 listOfNewGroups.push_back( newGroup );
2836 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2838 else if ( theUniteIdenticalGroups )
2840 // unite identical groups
2841 TListOfNewGroups& aNewGroups = anIter->second;
2842 aNewGroups.front()->Add( newIDs );
2846 // rename identical groups
2847 newGroup = newImpl->CreateGroup( groupType, groupName );
2848 newGroup->Add( newIDs );
2850 TListOfNewGroups& newGroups = anIter->second;
2851 std::string newGroupName;
2852 if ( newGroups.size() == 1 )
2854 newGroupName = name + "_1";
2855 newGroups.front()->SetName( newGroupName.c_str() );
2857 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2858 newGroup->SetName( newGroupName.c_str() );
2859 newGroups.push_back( newGroup );
2862 } // if an IDSource is a mesh
2865 if ( theMergeNodesAndElements ) // merge nodes
2867 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2868 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2869 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2870 /*SeparateCornersAndMedium=*/ false );
2871 newEditor.MergeNodes( groupsOfNodes );
2873 newEditor.MergeEqualElements();
2876 // Update Python script
2877 pythonDump << newMesh << " = " << this
2878 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2879 << theMeshesArray << ", "
2880 << theUniteIdenticalGroups << ", "
2881 << theMergeNodesAndElements << ", "
2882 << TVar( theMergeTolerance ) << ", "
2883 << theMeshToAppendTo << " )";
2885 pPythonDump.reset(); // enable python dump from GetGroups()
2887 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2888 if ( !newMesh->_is_nil() )
2890 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2893 // IPAL21468 Change icon of compound because it need not be computed.
2894 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2895 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2897 newMeshDS->Modified();
2899 return newMesh._retn();
2902 //================================================================================
2904 * \brief Create a mesh by copying a part of another mesh
2905 * \param meshPart - a part of mesh to copy
2906 * \param toCopyGroups - to create in the new mesh groups
2907 * the copied elements belongs to
2908 * \param toKeepIDs - to preserve IDs of the copied elements or not
2909 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2911 //================================================================================
2913 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2914 const char* meshName,
2915 CORBA::Boolean toCopyGroups,
2916 CORBA::Boolean toKeepIDs)
2917 throw ( SALOME::SALOME_Exception )
2919 Unexpect aCatch(SALOME_SalomeException);
2921 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2922 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2924 // 1. Get source mesh
2926 if ( CORBA::is_nil( meshPart ))
2927 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2929 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2930 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2932 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2934 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2936 // 2. Make a new mesh
2938 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2939 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2941 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2942 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2943 if ( !meshSO->_is_nil() )
2945 SetName( meshSO, meshName, "Mesh" );
2946 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2948 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2949 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2950 ::SMESH_MeshEditor::ElemFeatures elemType;
2952 // 3. Get elements to copy
2954 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2955 TIDSortedElemSet srcElems;
2956 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2957 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2960 srcElemIt = srcMeshDS->elementsIterator();
2961 srcNodeIt = srcMeshDS->nodesIterator();
2965 SMESH::long_array_var ids = meshPart->GetIDs();
2966 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2968 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2969 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2970 srcElems.insert( elem );
2974 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2975 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2976 srcElems.insert( elem );
2978 if ( srcElems.empty() )
2979 return newMesh._retn();
2981 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2982 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2987 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2988 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2989 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2991 const SMDS_MeshNode *nSrc, *nTgt;
2992 vector< const SMDS_MeshNode* > nodes;
2993 while ( srcElemIt->more() )
2995 const SMDS_MeshElement * elem = srcElemIt->next();
2997 nodes.resize( elem->NbNodes());
2998 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3000 for ( iN = 0; nIt->more(); ++iN )
3002 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3003 nTgt = newMeshDS->FindNode( nSrc->GetID());
3005 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3010 for ( iN = 0; nIt->more(); ++iN )
3012 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3013 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3015 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3016 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3020 if ( elem->GetType() != SMDSAbs_Node )
3022 elemType.Init( elem, /*basicOnly=*/false );
3023 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3025 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3026 if ( toCopyGroups && !toKeepIDs )
3027 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3029 } // while ( srcElemIt->more() )
3031 // 4(b). Copy free nodes
3033 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3035 while ( srcNodeIt->more() )
3037 nSrc = srcNodeIt->next();
3038 if ( nSrc->NbInverseElements() == 0 )
3041 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3043 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3050 int nbNewGroups = 0;
3053 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3054 while ( gIt->more() )
3056 SMESH_Group* group = gIt->next();
3057 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3059 // Check group type. We copy nodal groups containing nodes of copied element
3060 SMDSAbs_ElementType groupType = groupDS->GetType();
3061 if ( groupType != SMDSAbs_Node &&
3062 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3063 continue; // group type differs from types of meshPart
3065 // Find copied elements in the group
3066 vector< const SMDS_MeshElement* > groupElems;
3067 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3070 const SMDS_MeshElement* foundElem;
3071 if ( groupType == SMDSAbs_Node )
3073 while ( eIt->more() )
3074 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3075 groupElems.push_back( foundElem );
3079 while ( eIt->more() )
3080 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3081 groupElems.push_back( foundElem );
3086 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3087 if ( e2eMap.empty() ) continue;
3088 int minID = e2eMap.begin()->first->GetID();
3089 int maxID = e2eMap.rbegin()->first->GetID();
3090 TE2EMap::iterator e2e;
3091 while ( eIt->more() && groupElems.size() < e2eMap.size())
3093 const SMDS_MeshElement* e = eIt->next();
3094 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3095 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3096 groupElems.push_back( e2e->second );
3100 if ( !groupElems.empty() )
3102 SMESH::SMESH_Group_var newGroupObj =
3103 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3104 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3106 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3107 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3108 for ( unsigned i = 0; i < groupElems.size(); ++i )
3109 smdsGroup.Add( groupElems[i] );
3117 newMeshDS->Modified();
3119 *pyDump << newMesh << " = " << this
3120 << ".CopyMesh( " << meshPart << ", "
3121 << "'" << meshName << "', "
3122 << toCopyGroups << ", "
3123 << toKeepIDs << ")";
3125 pyDumpDeleter.reset(); // allow dump in GetGroups()
3127 if ( nbNewGroups > 0 ) // dump created groups
3128 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3130 return newMesh._retn();
3134 namespace // utils for CopyMeshWithGeom()
3136 typedef std::map< std::string, std::string > TStr2StrMap;
3137 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3138 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3139 typedef std::map< std::string, int > TName2IndexMap;
3141 //================================================================================
3143 * \brief Return a new sub-shape corresponding to an old one
3145 //================================================================================
3149 SMESH_Mesh_i* mySrcMesh_i;
3150 SMESH_Mesh_i* myNewMesh_i;
3151 SMESH_Gen_i* myGen_i;
3155 TStr2StrMap myOld2NewEntryMap; // map of study entries
3157 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3158 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3159 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3162 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3164 // not directly relating to shape search
3165 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3167 //================================================================================
3169 * \brief Constructor
3171 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3172 SMESH_Mesh_i* newMesh_i,
3173 SMESH_Gen_i* smeshGen_i )
3174 : mySrcMesh_i( srcMesh_i ),
3175 myNewMesh_i( newMesh_i ),
3176 myGen_i ( smeshGen_i ),
3177 myToPublish( smeshGen_i->IsEnablePublish() ),
3178 myGIPMapDone( false )
3180 // retrieve from the study shape mapping made thanks to
3181 // "Set presentation parameters and sub-shapes from arguments" option
3183 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3184 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3185 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3186 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3187 if ( newSO->_is_nil() )
3189 myToPublish = false;
3192 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3194 CORBA::String_var oldEntry = oldSO->GetID();
3195 CORBA::String_var newEntry = newSO->GetID();
3196 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3197 std::string( newEntry.in() )));
3198 std::string newMainEntry = newEntry.in();
3200 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3201 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3202 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3203 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3204 /*groupsOnly=*/false );
3205 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3207 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3208 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3209 bool refFound = false;
3210 for ( ; anIter->More(); anIter->Next() )
3212 SALOMEDS::SObject_wrap so = anIter->Value();
3213 if ( so->ReferencedObject( oldSO.inout() ))
3215 oldEntry = oldSO->GetID();
3216 newEntry = newSO->GetID();
3217 if (( refFound = ( newMainEntry != oldEntry.in() )))
3218 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3219 std::string( newEntry.in() )));
3224 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3225 if ( father->_is_equivalent( mainShapeNew ))
3227 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3228 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3229 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3230 CORBA::String_var name = newSO->GetName();
3232 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3238 //================================================================================
3240 * \brief Find a new sub-shape corresponding to an old one
3242 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3245 return GEOM::GEOM_Object::_duplicate( oldShape );
3247 GEOM::GEOM_Object_var newShape;
3249 if ( CORBA::is_nil( oldShape ))
3250 return newShape._retn();
3252 if ( !isChildOfOld( oldShape ))
3253 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3255 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3256 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3258 // try to find by entry or name
3261 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3262 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3263 if ( o2nID != myOld2NewEntryMap.end() )
3265 newShape = getShapeByEntry( o2nID->second );
3267 if ( newShape->_is_nil() )
3269 CORBA::String_var name = oldShape->GetName();
3270 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3271 if ( n2ind != myName2SubshapeIndex.end() )
3273 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3274 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3275 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3276 if ( oldIndices->length() == 0 ||
3277 newIndices->length() == 0 ||
3278 getShapeType( myNewMesh_i, newIndices[0] ) !=
3279 getShapeType( mySrcMesh_i, oldIndices[0] ))
3280 newShape = GEOM::GEOM_Object::_nil();
3285 if ( newShape->_is_nil() )
3287 // try to construct a new sub-shape using myGIPMap
3289 std::vector< int > newIndices;
3290 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3291 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3293 findNewIDs( oldIndices[i], newIndices );
3295 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3298 newShape = getInPlace( oldShape );
3300 if ( !newIndices.empty() && newShape->_is_nil() )
3302 // search for a sub-shape with same ids
3303 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3304 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3305 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3306 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3308 if ( newShape->_is_nil() )
3311 // create a new shape
3312 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3314 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3316 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3317 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3319 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3320 newIndicesList->length( newIndices.size() );
3321 for ( size_t i = 0; i < newIndices.size(); ++i )
3322 newIndicesList[ i ] = newIndices[ i ];
3323 grOp->UnionIDs( newShape, newIndicesList );
3327 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3328 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3337 if ( !newShape->_is_nil() && myToPublish )
3339 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3340 if ( !newEntry.in() || !newEntry.in()[0] )
3342 CORBA::String_var name = oldShape->GetName();
3343 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3344 newEntry = newShape->GetStudyEntry();
3345 oldEntry = oldShape->GetStudyEntry();
3346 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3347 std::string( newEntry.in() )));
3351 return newShape._retn();
3354 //================================================================================
3356 * \brief Return a study entry of a new shape by study entry of the old one
3358 std::string FindNew( const std::string & oldEntry )
3363 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3364 if ( o2nID != myOld2NewEntryMap.end() )
3365 return o2nID->second;
3367 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3368 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3371 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3372 if ( newShape->_is_nil() )
3373 return std::string();
3375 CORBA::String_var newEntry = newShape->GetStudyEntry();
3376 return newEntry.in();
3379 //================================================================================
3381 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3382 * Return zero if not found or there are more than one new ID
3384 int FindNew( int oldID )
3393 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3395 if ( myGIPMap[ oldID ].length() == 1 )
3397 newID = myGIPMap[ oldID ][ 0 ];
3399 else if ( myGIPMap[ oldID ].length() > 1 &&
3400 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3402 // select a meshed VERTEX
3403 SMESH_subMesh* newSM;
3404 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3405 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3406 ( !newSM->IsEmpty() ))
3407 newID = myGIPMap[ oldID ][ i ];
3413 //================================================================================
3415 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3416 * Return zero if the old shape is not kept as is in the new shape.
3418 int FindNewNotChanged( SMESH_subMesh* oldSM )
3421 return oldSM->GetId();
3423 int newID = FindNew( oldSM->GetId() );
3427 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3431 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3432 // one new sub-shape of the same type.
3434 if ( oldSM->DependsOn().size() !=
3435 newSM->DependsOn().size() )
3438 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3439 while ( srcSMIt->more() )
3441 oldSM = srcSMIt->next();
3442 int newSubID = FindNew( oldSM->GetId() );
3443 if ( getShapeType( myNewMesh_i, newSubID ) !=
3444 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3450 //================================================================================
3452 * \brief Return shape by study entry
3454 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3456 GEOM::GEOM_Object_var shape;
3457 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3458 if ( !so->_is_nil() )
3460 CORBA::Object_var obj = so->GetObject();
3461 shape = GEOM::GEOM_Object::_narrow( obj );
3463 return shape._retn();
3466 //================================================================================
3468 * \brief Fill myGIPMap by calling GetInPlaceMap()
3472 if ( !myGIPMapDone )
3474 myGIPMapDone = true;
3476 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3477 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3478 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3479 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3482 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3486 myGIPMap = new GEOM::ListOfListOfLong();
3491 //================================================================================
3493 * \brief Get new sub-shape by calling GetInPlace()
3495 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3497 GEOM::GEOM_Object_var newShape;
3499 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3500 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3501 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3504 newShape = op->GetInPlace( mainShapeNew, oldShape );
3509 return newShape._retn();
3512 //================================================================================
3514 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3515 * number of found IDs
3517 int findNewIDs( int oldID, std::vector< int >& newIDs )
3519 size_t prevNbIDs = newIDs.size();
3521 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3523 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3524 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3526 return newIDs.size() - prevNbIDs;
3529 //================================================================================
3531 * \brief Check if an object relates to the old shape
3533 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3535 if ( CORBA::is_nil( oldShape ))
3537 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3538 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3539 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3540 mainShapeOld1->_is_equivalent( oldShape ));
3543 //================================================================================
3545 * \brief Return shape type by shape ID
3547 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3549 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3550 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3551 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3554 //================================================================================
3556 * \brief Store a source sub-shape for which a counterpart not found and
3557 * a smesh object invalid due to that
3559 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3560 SALOMEDS::SObject_wrap smeshSO )
3562 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3563 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3565 CORBA::String_var smeshEntry = smeshSO->GetID();
3566 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3570 //================================================================================
3572 * \brief Store a source sub-shape for which a counterpart not found and
3573 * a smesh object invalid due to that
3575 void AddInvalid( std::string geomEntry,
3576 SALOMEDS::SObject_wrap smeshSO )
3578 if ( !geomEntry.empty() )
3580 CORBA::String_var smeshEntry = smeshSO->GetID();
3581 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3585 //================================================================================
3587 * \brief Store a source sub-shape for which a counterpart not found and
3588 * a smesh object invalid due to that
3590 void AddInvalid( int oldGeomID,
3591 SALOMEDS::SObject_wrap smeshSO )
3593 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3594 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3597 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3598 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3600 SMESH_Comment geomName( typeName[ shapeType ]);
3601 geomName << " #" << oldGeomID;
3603 CORBA::String_var smeshEntry = smeshSO->GetID();
3604 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3607 //================================================================================
3609 * \brief Return entries of a source sub-shape for which a counterpart not found and
3610 * of smesh objects invalid due to that
3612 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3613 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3616 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3617 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3619 nbSO += 1 + entry2entrySet->second.size();
3621 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3622 theInvalidEntries->length ( nbSO );
3623 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3625 entry2entrySet = myInvalidMap.begin();
3626 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3628 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3630 std::set< std::string > & entrySet = entry2entrySet->second;
3631 std::set< std::string >::iterator entry = entrySet.begin();
3632 for ( ; entry != entrySet.end(); ++entry )
3634 theInvalidEntries[ iEntry++ ] = entry->c_str();
3636 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3637 if ( !so->_is_nil() )
3638 theInvalidMeshSObjects[ iSO++ ] = so;
3643 }; // struct ShapeMapper
3645 //================================================================================
3647 * \brief Append an item to a CORBA sequence
3649 template < class CORBA_seq, class ITEM >
3650 void append( CORBA_seq& seq, ITEM item )
3652 if ( !CORBA::is_nil( item ))
3654 seq->length( 1 + seq->length() );
3655 seq[ seq->length() - 1 ] = item;
3658 } // namespace // utils for CopyMeshWithGeom()
3660 //================================================================================
3662 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3663 * \param [in] sourceMesh - a mesh to copy
3664 * \param [in] newGeometry - a new geometry
3665 * \param [in] toCopyGroups - to create groups in the new mesh
3666 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3667 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3668 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3669 * \param [out] newMesh - return a new mesh
3670 * \param [out] newGroups - return new groups
3671 * \param [out] newSubmeshes - return new sub-meshes
3672 * \param [out] newHypotheses - return new algorithms and hypotheses
3673 * \param [out] invalidEntries - return study entries of objects whose
3674 * counterparts are not found in the newGeometry, followed by entries
3675 * of mesh sub-objects that are invalid because they depend on a not found
3676 * preceding sub-shape
3677 * \return CORBA::Boolean - is a success
3679 //================================================================================
3681 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3682 GEOM::GEOM_Object_ptr theNewGeometry,
3683 const char* theMeshName,
3684 CORBA::Boolean theToCopyGroups,
3685 CORBA::Boolean theToReuseHypotheses,
3686 CORBA::Boolean theToCopyElements,
3687 SMESH::SMESH_Mesh_out theNewMesh,
3688 SMESH::ListOfGroups_out theNewGroups,
3689 SMESH::submesh_array_out theNewSubmeshes,
3690 SMESH::ListOfHypothesis_out theNewHypotheses,
3691 SMESH::string_array_out theInvalidEntries)
3692 throw ( SALOME::SALOME_Exception )
3694 if ( CORBA::is_nil( theSourceMesh ) ||
3695 CORBA::is_nil( theNewGeometry ))
3696 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3698 if ( !theSourceMesh->HasShapeToMesh() )
3699 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3704 TPythonDump pyDump; // prevent dump from CreateMesh()
3706 theNewMesh = CreateMesh( theNewGeometry );
3707 theNewGroups = new SMESH::ListOfGroups();
3708 theNewSubmeshes = new SMESH::submesh_array();
3709 theNewHypotheses = new SMESH::ListOfHypothesis();
3710 theInvalidEntries = new SMESH::string_array();
3712 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3714 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3715 GEOM::GEOM_Object_var geom, newGeom;
3716 SALOMEDS::SObject_wrap so;
3718 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3719 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3722 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3724 // treat hypotheses of mesh and sub-meshes
3725 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3726 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3728 bool isSubMesh = ( iSM < smList->length() );
3731 // create a new sub-mesh
3732 SMESH::SMESH_subMesh_var newSM;
3733 geom = smList[iSM]->GetSubShape();
3734 so = ObjectToSObject( smList[iSM] );
3735 CORBA::String_var name;
3736 if ( !so->_is_nil() )
3737 name = so->GetName();
3738 newGeom = shapeMapper.FindNew( geom );
3739 if ( newGeom->_is_nil() )
3741 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3742 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3747 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3749 append( theNewSubmeshes, newSM );
3751 if ( newGeom->_is_nil() )
3752 continue; // don't assign hypotheses
3756 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3758 so = ObjectToSObject( theNewMesh );
3759 SetName( so, theMeshName, "Mesh" );
3762 // assign hypotheses
3763 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3764 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3766 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3767 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3769 // get geometry hyp depends on
3770 std::vector< std::string > entryArray;
3771 std::vector< int > subIDArray;
3772 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3774 if ( !theToReuseHypotheses || dependsOnGeom )
3776 // create a new hypothesis
3777 CORBA::String_var type = hyp->GetName();
3778 CORBA::String_var lib = hyp->GetLibName();
3779 CORBA::String_var data = hyp_i->SaveTo();
3782 hyp = CreateHypothesis( type, lib );
3783 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3784 hyp_i->LoadFrom( data.in() );
3785 append( theNewHypotheses, hyp );
3789 // update geometry hyp depends on
3790 if ( dependsOnGeom )
3792 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3794 if ( !entryArray[ iGeo ].empty() )
3796 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3797 if ( newEntry.empty() )
3800 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3801 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3803 entryArray[ iGeo ] = newEntry;
3806 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3808 if ( subIDArray[ iGeo ] > 0 )
3810 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3814 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3815 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3817 subIDArray[ iGeo ] = newID;
3820 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3824 CORBA::String_var errorText;
3825 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3826 if ( errorText.in()[0] )
3829 } // loop on hypotheses
3830 } // loop on sub-meshes and mesh
3833 // copy mesh elements, keeping IDs
3834 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3835 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3837 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3838 ::SMESH_MeshEditor::ElemFeatures elemData;
3840 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3841 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3842 /*vertexLast=*/false);
3843 while ( srcSMIt->more() )
3845 SMESH_subMesh* srcSM = srcSMIt->next();
3846 if ( srcSM->IsEmpty() )
3847 continue; // not yet computed
3848 int newID = shapeMapper.FindNewNotChanged( srcSM );
3852 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3853 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3854 while ( nIt->more() )
3856 SMESH_NodeXYZ node( nIt->next() );
3857 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3859 const SMDS_PositionPtr pos = node->GetPosition();
3860 const double* uv = pos->GetParameters();
3861 switch ( pos->GetTypeOfPosition() )
3863 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3864 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3865 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3866 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3870 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3871 while( eIt->more() )
3873 const SMDS_MeshElement* e = eIt->next();
3874 elemData.Init( e, /*basicOnly=*/false );
3875 elemData.SetID( e->GetID() );
3876 elemData.myNodes.resize( e->NbNodes() );
3877 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3879 for ( iN = 0; nnIt->more(); ++iN )
3881 const SMDS_MeshNode* srcNode = nnIt->next();
3882 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3883 if ( !elemData.myNodes[ iN ])
3886 if ( iN == elemData.myNodes.size() )
3887 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3888 newMeshDS->SetMeshElementOnShape( newElem, newID );
3890 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3891 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3894 newMeshDS->Modified();
3900 TStr2StrMap old2newGroupMap;
3902 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3904 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3905 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3906 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3908 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3909 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3910 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3912 CORBA::String_var name = groups[ i ]->GetName();
3913 SMESH::ElementType elemType = groups[ i ]->GetType();
3915 SMESH::SMESH_GroupBase_var newGroup;
3917 if ( !stdlGroup->_is_nil() )
3919 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3921 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3922 const bool isElem = ( elemType != SMESH::NODE );
3923 CORBA::ULong iE = 0;
3924 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3925 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3927 if ( iE < elemIDs->length() )
3929 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3930 stdlGroup->Add( elemIDs );
3931 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3935 else if ( !geomGroup->_is_nil() )
3937 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3938 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3939 if ( newGeom->_is_nil() )
3941 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3942 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3947 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3950 else if ( !fltrGroup->_is_nil() )
3952 // replace geometry in a filter
3953 SMESH::Filter_var filter = fltrGroup->GetFilter();
3954 SMESH::Filter::Criteria_var criteria;
3955 filter->GetCriteria( criteria.out() );
3957 bool isMissingGroup = false;
3958 std::vector< std::string > badEntries;
3960 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3962 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3963 switch ( criteria[ iCr ].Type )
3965 case SMESH::FT_BelongToMeshGroup:
3967 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3968 btgg->SetGroupID( thresholdID );
3969 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3970 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3971 if ( refGroupSO->_is_nil() )
3973 CORBA::String_var refID = refGroupSO->GetID();
3974 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3975 if ( o2nID == old2newGroupMap.end() )
3977 isMissingGroup = true; // corresponding new group not yet created
3980 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3982 if ( o2nID->second.empty() ) // new referred group is invalid
3983 badEntries.push_back( refID.in() );
3986 case SMESH::FT_BelongToGeom:
3987 case SMESH::FT_BelongToPlane:
3988 case SMESH::FT_BelongToCylinder:
3989 case SMESH::FT_BelongToGenSurface:
3990 case SMESH::FT_LyingOnGeom:
3992 std::string newID = shapeMapper.FindNew( thresholdID );
3993 criteria[ iCr ].ThresholdID = newID.c_str();
3994 if ( newID.empty() )
3995 badEntries.push_back( thresholdID );
3998 case SMESH::FT_ConnectedElements:
4000 if ( thresholdID && thresholdID[0] )
4002 std::string newID = shapeMapper.FindNew( thresholdID );
4003 criteria[ iCr ].ThresholdID = newID.c_str();
4004 if ( newID.empty() )
4005 badEntries.push_back( thresholdID );
4011 } // loop on criteria
4013 if ( isMissingGroup && i < nbGroups )
4015 // to treat the group again
4016 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4020 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4021 newFilter->SetCriteria( criteria );
4023 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4024 newFilter->UnRegister();
4026 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4027 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4028 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4030 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4032 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4035 if ( !badEntries.empty() )
4038 } // treat a group on filter
4040 append( theNewGroups, newGroup );
4042 // fill old2newGroupMap
4043 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4044 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4045 if ( !srcSO->_is_nil() )
4047 CORBA::String_var srcID, newID("");
4048 srcID = srcSO->GetID();
4049 if ( !newSO->_is_nil() )
4050 newID = newSO->GetID();
4051 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4052 std::string( newID.in() )));
4055 if ( newGroup->_is_nil() )
4060 newMeshDS->CompactMesh();
4063 if ( !theMeshName || !theMeshName[0] )
4065 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4066 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4067 CORBA::String_var oldName = soOld->GetName();
4068 SetName( soNew, oldName.in(), "Mesh" );
4070 // mark invalid objects
4071 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4073 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4074 highLightInvalid( invalidSObjects[i].in(), true );
4077 << theNewMesh << ", "
4078 << theNewGroups << ", "
4079 << *theNewSubmeshes.ptr() << ", "
4080 << *theNewHypotheses.ptr() << ", "
4081 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4082 << theSourceMesh << ", "
4083 << theNewGeometry << ", "
4084 << "'" << theMeshName << "', "
4085 << theToCopyGroups << ", "
4086 << theToReuseHypotheses << ", "
4087 << theToCopyElements << " )";
4089 SMESH_CATCH( SMESH::throwCorbaException );
4094 //================================================================================
4096 * \brief Get version of MED format being used.
4098 //================================================================================
4100 char* SMESH_Gen_i::GetMEDFileVersion()
4102 MED::TInt majeur, mineur, release;
4103 majeur = mineur = release = 0;
4104 MED::GetVersionRelease(majeur, mineur, release);
4105 std::ostringstream version;
4106 version << majeur << "." << mineur << "." << release;
4107 return CORBA::string_dup( version.str().c_str() );
4110 //================================================================================
4112 * SMESH_Gen_i::GetMEDVersion
4114 * Get MED version of the file by its name
4116 //================================================================================
4118 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4120 std::string version = MED::GetMEDVersion( theFileName );
4121 return CORBA::string_dup( version.c_str() );
4124 //================================================================================
4126 * SMESH_Gen_i::CheckCompatibility
4128 * Check compatibility of file with MED format being used, read only.
4130 //================================================================================
4132 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4134 return MED::CheckCompatibility( theFileName );
4137 //================================================================================
4139 * SMESH_Gen_i::CheckWriteCompatibility
4141 * Check compatibility of file with MED format being used, for append on write.
4143 //================================================================================
4145 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4147 return MED::CheckCompatibility( theFileName, true );
4150 //================================================================================
4152 * SMESH_Gen_i::GetMeshNames
4154 * Get names of meshes defined in file with the specified name
4156 //================================================================================
4157 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4160 SMESH::string_array_var aResult = new SMESH::string_array();
4161 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4163 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4165 aResult->length( aNbMeshes );
4166 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4167 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4168 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4171 return aResult._retn();
4174 //=============================================================================
4178 * Save SMESH module's data
4180 //=============================================================================
4182 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4187 Kernel_Utils::Localizer loc;
4189 if (!myStudyContext)
4192 // Store study contents as a set of python commands
4195 SALOMEDS::Study_var aStudy = getStudyServant();
4197 // Declare a byte stream
4198 SALOMEDS::TMPFile_var aStreamFile;
4200 // Obtain a temporary dir
4201 TCollection_AsciiString tmpDir =
4202 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4204 // Create a sequence of files processed
4205 SALOMEDS_Tool::ListOfFiles aFileSeq;
4206 aFileSeq.reserve( NUM_TMP_FILES );
4208 TCollection_AsciiString aStudyName( "" );
4210 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4212 // Set names of temporary files
4213 TCollection_AsciiString filename =
4214 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4215 TCollection_AsciiString meshfile =
4216 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4217 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4218 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4219 filename = tmpDir + filename;
4220 meshfile = tmpDir + meshfile;
4223 HDFdataset* aDataset;
4224 HDFgroup* aTopGroup;
4226 HDFgroup* aSubGroup;
4227 HDFgroup* aSubSubGroup;
4228 hdf_size aSize[ 1 ];
4231 //Remove the files if they exist: BugID: 11225
4232 #ifndef WIN32 /* unix functionality */
4233 TCollection_AsciiString cmd("rm -f \"");
4235 TCollection_AsciiString cmd("del /F \"");
4245 system(cmd.ToCString());
4247 // MED writer to be used by storage process
4248 DriverMED_W_SMESHDS_Mesh myWriter;
4249 myWriter.SetFile( meshfile.ToCString() );
4252 // SetStoreName() to groups before storing hypotheses to let them refer to
4253 // groups using "store name", which is "Group <group_persistent_id>"
4255 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4256 for ( ; itBig->More(); itBig->Next() ) {
4257 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4258 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4259 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4260 if ( !CORBA::is_nil( anObject ) ) {
4261 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4262 if ( !myMesh->_is_nil() ) {
4263 myMesh->Load(); // load from study file if not yet done
4264 TPythonDump pd; // not to dump GetGroups()
4265 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4266 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4268 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4271 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4272 int anId = myStudyContext->findId( string( objStr.in() ) );
4274 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4275 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4276 aGrpBaseDS->SetStoreName( grpName );
4286 // ---> create HDF file
4287 aFile = new HDFfile( (char*) filename.ToCString() );
4288 aFile->CreateOnDisk();
4290 // --> iterator for top-level objects
4291 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4292 for ( ; itBig->More(); itBig->Next() ) {
4293 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4295 // --> hypotheses root branch (only one for the study)
4296 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4297 // create hypotheses root HDF group
4298 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4299 aTopGroup->CreateOnDisk();
4301 // iterator for all hypotheses
4302 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4303 for ( ; it->More(); it->Next() ) {
4304 SALOMEDS::SObject_wrap mySObject = it->Value();
4305 CORBA::Object_var anObject = SObjectToObject( mySObject );
4306 if ( !CORBA::is_nil( anObject ) ) {
4307 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4308 if ( !myHyp->_is_nil() ) {
4309 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4311 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4312 std::string hypname = hn.in();
4313 std::string libname = ln.in();
4315 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4316 // WIN32 and ".so" for X-system) must be deleted
4317 int libname_len = libname.length();
4319 if( libname_len > 4 )
4320 libname.resize( libname_len - 4 );
4322 // PAL17753 (Regression: missing hypothesis in restored study)
4323 // "lib" also should be removed from the beginning
4324 if( libname_len > 6 )
4325 libname = libname.substr( 3, libname_len - 3 - 3 );
4327 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4328 CORBA::String_var hypdata = myImpl->SaveTo();
4329 int id = myStudyContext->findId( string( objStr.in() ));
4331 // for each hypothesis create HDF group basing on its id
4332 char hypGrpName[30];
4333 sprintf( hypGrpName, "Hypothesis %d", id );
4334 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4335 aGroup->CreateOnDisk();
4336 // --> type name of hypothesis
4337 aSize[ 0 ] = hypname.length() + 1;
4338 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4339 aDataset->CreateOnDisk();
4340 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4341 aDataset->CloseOnDisk();
4342 // --> server plugin library name of hypothesis
4343 aSize[ 0 ] = libname.length() + 1;
4344 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4345 aDataset->CreateOnDisk();
4346 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4347 aDataset->CloseOnDisk();
4348 // --> persistent data of hypothesis
4349 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4350 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4351 aDataset->CreateOnDisk();
4352 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4353 aDataset->CloseOnDisk();
4354 // close hypothesis HDF group
4355 aGroup->CloseOnDisk();
4360 // close hypotheses root HDF group
4361 aTopGroup->CloseOnDisk();
4363 // --> algorithms root branch (only one for the study)
4364 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4365 // create algorithms root HDF group
4366 aTopGroup = new HDFgroup( "Algorithms", aFile );
4367 aTopGroup->CreateOnDisk();
4369 // iterator for all algorithms
4370 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4371 for ( ; it->More(); it->Next() ) {
4372 SALOMEDS::SObject_wrap mySObject = it->Value();
4373 CORBA::Object_var anObject = SObjectToObject( mySObject );
4374 if ( !CORBA::is_nil( anObject ) ) {
4375 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4376 if ( !myHyp->_is_nil() ) {
4377 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4379 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4380 std::string hypname = hn.in();
4381 std::string libname = ln.in();
4383 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4384 // WIN32 and ".so" for X-system) must be deleted
4385 int libname_len = libname.length();
4387 if( libname_len > 4 )
4388 libname.resize( libname_len - 4 );
4390 // PAL17753 (Regression: missing hypothesis in restored study)
4391 // "lib" also should be removed from the beginning
4392 if( libname_len > 6 )
4393 libname = libname.substr( 3, libname_len - 3 - 3 );
4395 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4396 CORBA::String_var hypdata = myImpl->SaveTo();
4397 int id = myStudyContext->findId( string( objStr.in() ) );
4399 // for each algorithm create HDF group basing on its id
4400 char hypGrpName[30];
4401 sprintf( hypGrpName, "Algorithm %d", id );
4402 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4403 aGroup->CreateOnDisk();
4404 // --> type name of algorithm
4405 aSize[0] = hypname.length() + 1;
4406 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4407 aDataset->CreateOnDisk();
4408 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4409 aDataset->CloseOnDisk();
4410 // --> server plugin library name of hypothesis
4411 aSize[0] = libname.length() + 1;
4412 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4413 aDataset->CreateOnDisk();
4414 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4415 aDataset->CloseOnDisk();
4416 // --> persistent data of algorithm
4417 aSize[0] = strlen( hypdata.in() ) + 1;
4418 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4419 aDataset->CreateOnDisk();
4420 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4421 aDataset->CloseOnDisk();
4422 // close algorithm HDF group
4423 aGroup->CloseOnDisk();
4428 // close algorithms root HDF group
4429 aTopGroup->CloseOnDisk();
4431 // --> mesh objects roots branches
4432 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4433 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4434 if ( !CORBA::is_nil( anObject ) ) {
4435 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4436 if ( !myMesh->_is_nil() ) {
4437 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4439 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4440 int id = myStudyContext->findId( string( objStr.in() ) );
4441 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4442 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4443 bool hasShape = myLocMesh.HasShapeToMesh();
4445 // for each mesh open the HDF group basing on its id
4446 char meshGrpName[ 30 ];
4447 sprintf( meshGrpName, "Mesh %d", id );
4448 aTopGroup = new HDFgroup( meshGrpName, aFile );
4449 aTopGroup->CreateOnDisk();
4451 // --> put dataset to hdf file which is a flag that mesh has data
4452 string strHasData = "0";
4453 // check if the mesh is not empty
4454 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4455 // write mesh data to med file
4456 myWriter.SetMesh( mySMESHDSMesh );
4457 myWriter.SetMeshId( id );
4460 aSize[ 0 ] = strHasData.length() + 1;
4461 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4462 aDataset->CreateOnDisk();
4463 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4464 aDataset->CloseOnDisk();
4467 // for each mesh open the HDF group basing on its auto color parameter
4468 char meshAutoColorName[ 30 ];
4469 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4471 anAutoColor[0] = myImpl->GetAutoColor();
4473 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4474 aDataset->CreateOnDisk();
4475 aDataset->WriteOnDisk( anAutoColor );
4476 aDataset->CloseOnDisk();
4478 // issue 0020693. Store _isModified flag
4479 int isModified = myLocMesh.GetIsModified();
4481 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4482 aDataset->CreateOnDisk();
4483 aDataset->WriteOnDisk( &isModified );
4484 aDataset->CloseOnDisk();
4486 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4487 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4489 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4490 aDataset->CreateOnDisk();
4491 aDataset->WriteOnDisk( &meshPersistentId );
4492 aDataset->CloseOnDisk();
4494 // Store SMESH_Mesh_i::_mainShapeTick
4495 int shapeTick = myImpl->MainShapeTick();
4497 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4498 aDataset->CreateOnDisk();
4499 aDataset->WriteOnDisk( &shapeTick );
4500 aDataset->CloseOnDisk();
4502 // write reference on a shape if exists
4503 SALOMEDS::SObject_wrap myRef;
4504 bool shapeRefFound = false;
4505 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4507 SALOMEDS::SObject_wrap myShape;
4508 bool ok = myRef->ReferencedObject( myShape.inout() );
4510 CORBA::Object_var shapeObj = myShape->GetObject();
4511 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4512 CORBA::String_var myRefOnObject = myShape->GetID();
4513 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4514 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4515 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4516 aDataset->CreateOnDisk();
4517 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4518 aDataset->CloseOnDisk();
4524 std::string info = myImpl->FileInfoToString();
4525 if ( !info.empty() )
4527 aSize[ 0 ] = info.size();
4528 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4529 aDataset->CreateOnDisk();
4530 aDataset->WriteOnDisk( (char*) info.data() );
4531 aDataset->CloseOnDisk();
4534 // write applied hypotheses if exist
4535 SALOMEDS::SObject_wrap myHypBranch;
4536 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4537 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4538 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4540 if ( found && (shapeRefFound || !hasShape) ) {
4541 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4542 aGroup->CreateOnDisk();
4544 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4546 for ( ; it->More(); it->Next() ) {
4547 SALOMEDS::SObject_wrap mySObject = it->Value();
4548 SALOMEDS::SObject_wrap myRefOnHyp;
4549 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4551 // san - it is impossible to recover applied hypotheses
4552 // using their entries within Load() method,
4553 // for there are no AttributeIORs in the study when Load() is working.
4554 // Hence, it is better to store persistent IDs of hypotheses as references to them
4556 //string myRefOnObject = myRefOnHyp->GetID();
4557 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4558 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4559 int id = myStudyContext->findId( string( objStr.in() ) );
4560 //if ( myRefOnObject.length() > 0 ) {
4561 //aSize[ 0 ] = myRefOnObject.length() + 1;
4562 char hypName[ 30 ], hypId[ 30 ];
4563 sprintf( hypName, "Hyp %d", ++hypNb );
4564 sprintf( hypId, "%d", id );
4565 aSize[ 0 ] = strlen( hypId ) + 1;
4566 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4567 aDataset->CreateOnDisk();
4568 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4569 aDataset->WriteOnDisk( hypId );
4570 aDataset->CloseOnDisk();
4574 aGroup->CloseOnDisk();
4577 // write applied algorithms if exist
4578 SALOMEDS::SObject_wrap myAlgoBranch;
4579 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4580 myAlgoBranch.inout() );
4581 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4582 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4584 if ( found && (shapeRefFound || !hasShape)) {
4585 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4586 aGroup->CreateOnDisk();
4588 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4590 for ( ; it->More(); it->Next() ) {
4591 SALOMEDS::SObject_wrap mySObject = it->Value();
4592 SALOMEDS::SObject_wrap myRefOnAlgo;
4593 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4595 // san - it is impossible to recover applied algorithms
4596 // using their entries within Load() method,
4597 // for there are no AttributeIORs in the study when Load() is working.
4598 // Hence, it is better to store persistent IDs of algorithms as references to them
4600 //string myRefOnObject = myRefOnAlgo->GetID();
4601 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4602 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4603 int id = myStudyContext->findId( string( objStr.in() ) );
4604 //if ( myRefOnObject.length() > 0 ) {
4605 //aSize[ 0 ] = myRefOnObject.length() + 1;
4606 char algoName[ 30 ], algoId[ 30 ];
4607 sprintf( algoName, "Algo %d", ++algoNb );
4608 sprintf( algoId, "%d", id );
4609 aSize[ 0 ] = strlen( algoId ) + 1;
4610 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4611 aDataset->CreateOnDisk();
4612 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4613 aDataset->WriteOnDisk( algoId );
4614 aDataset->CloseOnDisk();
4618 aGroup->CloseOnDisk();
4621 // --> submesh objects sub-branches
4623 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4624 SALOMEDS::SObject_wrap mySubmeshBranch;
4625 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4627 if ( found ) // check if there is shape reference in submeshes
4629 bool hasShapeRef = false;
4630 SALOMEDS::ChildIterator_wrap itSM =
4631 aStudy->NewChildIterator( mySubmeshBranch );
4632 for ( ; itSM->More(); itSM->Next() ) {
4633 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4634 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4635 mySubRef->ReferencedObject( myShape.inout() );
4636 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4639 { // remove one submesh
4640 if ( shapeRefFound )
4641 { // unassign hypothesis
4642 SMESH::SMESH_subMesh_var mySubMesh =
4643 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4644 if ( !mySubMesh->_is_nil() ) {
4645 int shapeID = mySubMesh->GetId();
4646 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4647 const list<const SMESHDS_Hypothesis*>& hypList =
4648 mySMESHDSMesh->GetHypothesis( S );
4649 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4650 while ( hyp != hypList.end() ) {
4651 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4652 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4656 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4658 } // loop on submeshes of a type
4659 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4660 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4663 } // end check if there is shape reference in submeshes
4665 char name_meshgroup[ 30 ];
4666 if ( i == GetSubMeshOnVertexTag() )
4667 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4668 else if ( i == GetSubMeshOnEdgeTag() )
4669 strcpy( name_meshgroup, "SubMeshes On Edge" );
4670 else if ( i == GetSubMeshOnWireTag() )
4671 strcpy( name_meshgroup, "SubMeshes On Wire" );
4672 else if ( i == GetSubMeshOnFaceTag() )
4673 strcpy( name_meshgroup, "SubMeshes On Face" );
4674 else if ( i == GetSubMeshOnShellTag() )
4675 strcpy( name_meshgroup, "SubMeshes On Shell" );
4676 else if ( i == GetSubMeshOnSolidTag() )
4677 strcpy( name_meshgroup, "SubMeshes On Solid" );
4678 else if ( i == GetSubMeshOnCompoundTag() )
4679 strcpy( name_meshgroup, "SubMeshes On Compound" );
4681 // for each type of submeshes create container HDF group
4682 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4683 aGroup->CreateOnDisk();
4685 // iterator for all submeshes of given type
4686 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4687 for ( ; itSM->More(); itSM->Next() ) {
4688 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4689 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4690 if ( !CORBA::is_nil( anSubObject ))
4692 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4693 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4694 int subid = myStudyContext->findId( string( objStr.in() ) );
4696 // for each mesh open the HDF group basing on its id
4697 char submeshGrpName[ 30 ];
4698 sprintf( submeshGrpName, "SubMesh %d", subid );
4699 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4700 aSubGroup->CreateOnDisk();
4702 // write reference on a shape, already checked if it exists
4703 SALOMEDS::SObject_wrap mySubRef, myShape;
4704 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4705 mySubRef->ReferencedObject( myShape.inout() );
4706 string myRefOnObject = myShape->GetID();
4707 if ( myRefOnObject.length() > 0 ) {
4708 aSize[ 0 ] = myRefOnObject.length() + 1;
4709 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4710 aDataset->CreateOnDisk();
4711 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4712 aDataset->CloseOnDisk();
4715 // write applied hypotheses if exist
4716 SALOMEDS::SObject_wrap mySubHypBranch;
4717 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4718 mySubHypBranch.inout() );
4720 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4721 aSubSubGroup->CreateOnDisk();
4723 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4725 for ( ; it->More(); it->Next() ) {
4726 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4727 SALOMEDS::SObject_wrap myRefOnHyp;
4728 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4730 //string myRefOnObject = myRefOnHyp->GetID();
4731 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4732 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4733 int id = myStudyContext->findId( string( objStr.in() ) );
4734 //if ( myRefOnObject.length() > 0 ) {
4735 //aSize[ 0 ] = myRefOnObject.length() + 1;
4736 char hypName[ 30 ], hypId[ 30 ];
4737 sprintf( hypName, "Hyp %d", ++hypNb );
4738 sprintf( hypId, "%d", id );
4739 aSize[ 0 ] = strlen( hypId ) + 1;
4740 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4741 aDataset->CreateOnDisk();
4742 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4743 aDataset->WriteOnDisk( hypId );
4744 aDataset->CloseOnDisk();
4748 aSubSubGroup->CloseOnDisk();
4751 // write applied algorithms if exist
4752 SALOMEDS::SObject_wrap mySubAlgoBranch;
4753 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4754 mySubAlgoBranch.inout() );
4756 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4757 aSubSubGroup->CreateOnDisk();
4759 SALOMEDS::ChildIterator_wrap it =
4760 aStudy->NewChildIterator( mySubAlgoBranch );
4762 for ( ; it->More(); it->Next() ) {
4763 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4764 SALOMEDS::SObject_wrap myRefOnAlgo;
4765 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4767 //string myRefOnObject = myRefOnAlgo->GetID();
4768 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4769 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4770 int id = myStudyContext->findId( string( objStr.in() ) );
4771 //if ( myRefOnObject.length() > 0 ) {
4772 //aSize[ 0 ] = myRefOnObject.length() + 1;
4773 char algoName[ 30 ], algoId[ 30 ];
4774 sprintf( algoName, "Algo %d", ++algoNb );
4775 sprintf( algoId, "%d", id );
4776 aSize[ 0 ] = strlen( algoId ) + 1;
4777 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4778 aDataset->CreateOnDisk();
4779 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4780 aDataset->WriteOnDisk( algoId );
4781 aDataset->CloseOnDisk();
4785 aSubSubGroup->CloseOnDisk();
4787 // close submesh HDF group
4788 aSubGroup->CloseOnDisk();
4791 // close container of submeshes by type HDF group
4792 aGroup->CloseOnDisk();
4796 // store submesh order if any
4797 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4798 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4799 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4800 char order_list[ 30 ];
4801 strcpy( order_list, "Mesh Order" );
4802 // count number of submesh ids
4804 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4805 for ( ; idIt != theOrderIds.end(); idIt++ )
4806 nbIDs += (*idIt).size();
4807 // number of values = number of IDs +
4808 // number of lists (for separators) - 1
4809 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4810 idIt = theOrderIds.begin();
4811 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4812 const TListOfInt& idList = *idIt;
4813 if (idIt != theOrderIds.begin()) // not first list
4814 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4815 // dump submesh ids from current list
4816 TListOfInt::const_iterator id_smId = idList.begin();
4817 for( ; id_smId != idList.end(); id_smId++ )
4818 smIDs[ i++ ] = *id_smId;
4821 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4823 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4824 aDataset->CreateOnDisk();
4825 aDataset->WriteOnDisk( smIDs );
4826 aDataset->CloseOnDisk();
4830 if ( !theOrderIds.empty() && isNewOrederVersion )
4832 // convert ids to entries
4833 std::list< std::list< std::string > > orderEntryLists;
4834 for ( const TListOfInt& idList : theOrderIds )
4836 orderEntryLists.emplace_back();
4837 std::list< std::string > & entryList = orderEntryLists.back();
4838 for ( const int& id : idList )
4840 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4841 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4842 SALOMEDS::SObject_var so = ObjectToSObject( go );
4843 if ( !so->_is_nil() )
4845 CORBA::String_var entry = so->GetID();
4846 entryList.emplace_back( entry.in() );
4850 // convert orderEntryLists to string
4851 std::ostringstream ostream;
4852 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4853 std::string orderEntryString = ostream.str();
4856 aSize[ 0 ] = orderEntryString.size() + 1;
4857 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4858 aDataset->CreateOnDisk();
4859 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4860 aDataset->CloseOnDisk();
4863 // groups root sub-branch
4864 SALOMEDS::SObject_wrap myGroupsBranch;
4865 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4866 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4868 char name_group[ 30 ];
4869 if ( i == GetNodeGroupsTag() )
4870 strcpy( name_group, "Groups of Nodes" );
4871 else if ( i == GetEdgeGroupsTag() )
4872 strcpy( name_group, "Groups of Edges" );
4873 else if ( i == GetFaceGroupsTag() )
4874 strcpy( name_group, "Groups of Faces" );
4875 else if ( i == GetVolumeGroupsTag() )
4876 strcpy( name_group, "Groups of Volumes" );
4877 else if ( i == Get0DElementsGroupsTag() )
4878 strcpy( name_group, "Groups of 0D Elements" );
4879 else if ( i == GetBallElementsGroupsTag() )
4880 strcpy( name_group, "Groups of Balls" );
4882 aGroup = new HDFgroup( name_group, aTopGroup );
4883 aGroup->CreateOnDisk();
4885 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4886 for ( ; it->More(); it->Next() ) {
4887 SALOMEDS::SObject_wrap mySObject = it->Value();
4888 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4889 if ( !CORBA::is_nil( aSubObject ) ) {
4890 SMESH_GroupBase_i* myGroupImpl =
4891 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4894 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4898 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4899 int anId = myStudyContext->findId( string( objStr.in() ) );
4901 // For each group, create a dataset named "Group <group_persistent_id>"
4902 // and store the group's user name into it
4903 const char* grpName = aGrpBaseDS->GetStoreName();
4904 CORBA::String_var aUserName = myGroupImpl->GetName();
4905 aSize[ 0 ] = strlen( aUserName ) + 1;
4907 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4908 aDataset->CreateOnDisk();
4909 aDataset->WriteOnDisk( aUserName );
4910 aDataset->CloseOnDisk();
4913 // For each group, create a dataset named "Group <group_persistent_id> Color"
4914 // and store the group's color into it
4915 char grpColorName[ 30 ];
4916 sprintf( grpColorName, "ColorGroup %d", anId );
4917 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4919 anRGB[ 0 ] = aColor.R;
4920 anRGB[ 1 ] = aColor.G;
4921 anRGB[ 2 ] = aColor.B;
4923 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4924 aDataset->CreateOnDisk();
4925 aDataset->WriteOnDisk( anRGB );
4926 aDataset->CloseOnDisk();
4928 // Pass SMESHDS_Group to MED writer
4929 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4931 myWriter.AddGroup( aGrpDS );
4933 // write reference on a shape if exists
4934 SMESHDS_GroupOnGeom* aGeomGrp =
4935 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4937 SALOMEDS::SObject_wrap mySubRef, myShape;
4938 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4939 mySubRef->ReferencedObject( myShape.inout() ) &&
4940 !CORBA::is_nil( myShape->GetObject() ))
4942 CORBA::String_var myRefOnObject = myShape->GetID();
4943 if ( myRefOnObject.in()[0] ) {
4944 char aRefName[ 30 ];
4945 sprintf( aRefName, "Ref on shape %d", anId);
4946 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4947 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4948 aDataset->CreateOnDisk();
4949 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4950 aDataset->CloseOnDisk();
4953 else // shape ref is invalid:
4955 // save a group on geometry as ordinary group
4956 myWriter.AddGroup( aGeomGrp );
4959 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4960 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4962 std::string str = aFilterGrp_i->FilterToString();
4963 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4964 aSize[ 0 ] = str.length() + 1;
4965 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4966 aDataset->CreateOnDisk();
4967 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4968 aDataset->CloseOnDisk();
4972 aGroup->CloseOnDisk();
4976 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4978 // Flush current mesh information into MED file
4981 // save info on nb of elements
4982 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4984 // maybe a shape was deleted in the study
4985 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4986 TopoDS_Shape nullShape;
4987 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4990 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4995 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4996 aGroup->CreateOnDisk();
4998 // each element belongs to one or none submesh,
4999 // so for each node/element, we store a submesh ID
5001 // Store submesh IDs
5002 for ( int isNode = 0; isNode < 2; ++isNode )
5004 SMDS_ElemIteratorPtr eIt =
5005 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
5006 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
5009 std::vector<int> smIDs; smIDs.reserve( nbElems );
5010 while ( eIt->more() )
5011 if ( const SMDS_MeshElement* e = eIt->next())
5012 smIDs.push_back( e->getshapeId() );
5014 aSize[ 0 ] = nbElems;
5015 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
5016 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5017 aDataset->CreateOnDisk();
5018 aDataset->WriteOnDisk( & smIDs[0] );
5019 aDataset->CloseOnDisk();
5022 aGroup->CloseOnDisk();
5024 // Store node positions on sub-shapes (SMDS_Position):
5025 // ----------------------------------------------------
5027 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5028 aGroup->CreateOnDisk();
5030 // in aGroup, create 5 datasets to contain:
5031 // "Nodes on Edges" - ID of node on edge
5032 // "Edge positions" - U parameter on node on edge
5033 // "Nodes on Faces" - ID of node on face
5034 // "Face U positions" - U parameter of node on face
5035 // "Face V positions" - V parameter of node on face
5037 // Find out nb of nodes on edges and faces
5038 // Collect corresponding sub-meshes
5039 int nbEdgeNodes = 0, nbFaceNodes = 0;
5040 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5041 // loop on SMESHDS_SubMesh'es
5042 while ( smIt->more() )
5044 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5045 if ( aSubMesh->IsComplexSubmesh() )
5046 continue; // submesh containing other submeshs
5047 int nbNodes = aSubMesh->NbNodes();
5048 if ( nbNodes == 0 ) continue;
5050 int aShapeID = aSubMesh->GetID();
5051 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5053 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5054 // write only SMDS_FacePosition and SMDS_EdgePosition
5055 switch ( aShapeType ) {
5057 nbFaceNodes += nbNodes;
5058 aFaceSM.push_back( aSubMesh );
5061 nbEdgeNodes += nbNodes;
5062 aEdgeSM.push_back( aSubMesh );
5068 // Treat positions on edges or faces
5069 for ( int onFace = 0; onFace < 2; onFace++ )
5071 // Create arrays to store in datasets
5072 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5073 if (!nbNodes) continue;
5074 int* aNodeIDs = new int [ nbNodes ];
5075 double* aUPos = new double [ nbNodes ];
5076 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5079 // loop on sub-meshes
5080 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5081 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5082 for ( ; itSM != pListSM->end(); itSM++ )
5084 SMESHDS_SubMesh* aSubMesh = (*itSM);
5086 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5087 // loop on nodes in aSubMesh
5088 while ( itNode->more() )
5091 const SMDS_MeshNode* node = itNode->next();
5092 aNodeIDs [ iNode ] = node->GetID();
5095 const SMDS_PositionPtr pos = node->GetPosition();
5096 if ( onFace ) { // on FACE
5097 SMDS_FacePositionPtr fPos = pos;
5099 aUPos[ iNode ] = fPos->GetUParameter();
5100 aVPos[ iNode ] = fPos->GetVParameter();
5107 SMDS_EdgePositionPtr ePos = pos;
5109 aUPos[ iNode ] = ePos->GetUParameter();
5115 } // loop on nodes in aSubMesh
5116 } // loop on sub-meshes
5121 aSize[ 0 ] = nbNodes;
5123 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5124 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5125 aDataset->CreateOnDisk();
5126 aDataset->WriteOnDisk( aNodeIDs );
5127 aDataset->CloseOnDisk();
5130 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5131 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5132 aDataset->CreateOnDisk();
5133 aDataset->WriteOnDisk( aUPos );
5134 aDataset->CloseOnDisk();
5137 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5138 aDataset->CreateOnDisk();
5139 aDataset->WriteOnDisk( aVPos );
5140 aDataset->CloseOnDisk();
5145 if ( aVPos ) delete [] aVPos;
5147 } // treat positions on edges or faces
5149 // close "Node Positions" group
5150 aGroup->CloseOnDisk();
5152 } // if ( there are submeshes in SMESHDS_Mesh )
5155 // close mesh HDF group
5156 aTopGroup->CloseOnDisk();
5164 aFile->CloseOnDisk();
5167 // Convert temporary files to stream
5168 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5170 // Remove temporary files and directory
5172 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5174 return aStreamFile._retn();
5177 //=============================================================================
5179 * SMESH_Gen_i::SaveASCII
5181 * Save SMESH module's data in ASCII format
5183 //=============================================================================
5185 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5187 bool isMultiFile ) {
5188 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5189 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5190 return aStreamFile._retn();
5192 //after usual saving needs to encipher binary to text string
5193 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5194 int size = aStreamFile.in().length();
5195 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5196 for ( int i = 0; i < size; i++ )
5197 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5199 buffer[size * 3] = '\0';
5201 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5203 return anAsciiStreamFile._retn();
5206 //=============================================================================
5210 * Load SMESH module's data
5212 //=============================================================================
5214 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5215 const SALOMEDS::TMPFile& theStream,
5219 UpdateStudy(); // load geom data
5220 Kernel_Utils::Localizer loc;
5222 SALOMEDS::Study_var aStudy = getStudyServant();
5224 // Get temporary files location
5225 TCollection_AsciiString tmpDir =
5226 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5228 // Convert the stream into sequence of files to process
5229 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5232 TCollection_AsciiString aStudyName( "" );
5233 if ( isMultiFile ) {
5234 CORBA::WString_var url = aStudy->URL();
5235 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5237 // Set names of temporary files
5238 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5239 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5243 HDFdataset* aDataset;
5244 HDFgroup* aTopGroup;
5246 HDFgroup* aSubGroup;
5247 HDFgroup* aSubSubGroup;
5250 // ---> open HDF file
5251 aFile = new HDFfile( (char*) filename.ToCString() );
5253 aFile->OpenOnDisk( HDF_RDONLY );
5255 catch ( HDFexception ) {
5256 INFOS( "Load(): " << filename << " not found!" );
5260 TPythonDump pd; // prevent dump during loading
5262 // For PAL13473 ("Repetitive mesh") implementation.
5263 // New dependencies between SMESH objects are established:
5264 // now hypotheses can refer to meshes, shapes and other hypotheses.
5265 // To keep data consistent, the following order of data restoration
5267 // 1. Create hypotheses
5268 // 2. Create all meshes
5269 // 3. Load hypotheses' data
5272 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5273 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5274 list< SMESH::Filter_var > filters;
5276 // get total number of top-level groups
5277 int aNbGroups = aFile->nInternalObjects();
5278 if ( aNbGroups > 0 ) {
5279 // --> in first turn we should read&create hypotheses
5280 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5281 // open hypotheses root HDF group
5282 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5283 aTopGroup->OpenOnDisk();
5285 // get number of hypotheses
5286 int aNbObjects = aTopGroup->nInternalObjects();
5287 for ( int j = 0; j < aNbObjects; j++ ) {
5288 // try to identify hypothesis
5289 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5290 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5292 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5293 // open hypothesis group
5294 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5295 aGroup->OpenOnDisk();
5297 // --> get hypothesis id
5298 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5303 // get number of datasets
5304 int aNbSubObjects = aGroup->nInternalObjects();
5305 for ( int k = 0; k < aNbSubObjects; k++ ) {
5307 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5308 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5309 // --> get hypothesis name
5310 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5311 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5312 aDataset->OpenOnDisk();
5313 size = aDataset->GetSize();
5314 char* hypname_str = new char[ size ];
5315 aDataset->ReadFromDisk( hypname_str );
5316 hypname = string( hypname_str );
5317 delete [] hypname_str;
5318 aDataset->CloseOnDisk();
5320 // --> get hypothesis plugin library name
5321 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5322 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5323 aDataset->OpenOnDisk();
5324 size = aDataset->GetSize();
5325 char* libname_str = new char[ size ];
5326 aDataset->ReadFromDisk( libname_str );
5327 if(MYDEBUG) SCRUTE( libname_str );
5328 libname = string( libname_str );
5329 delete [] libname_str;
5330 aDataset->CloseOnDisk();
5332 // --> get hypothesis data
5333 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5334 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5335 aDataset->OpenOnDisk();
5336 size = aDataset->GetSize();
5337 char* hypdata_str = new char[ size ];
5338 aDataset->ReadFromDisk( hypdata_str );
5339 hypdata = string( hypdata_str );
5340 delete [] hypdata_str;
5341 aDataset->CloseOnDisk();
5344 // close hypothesis HDF group
5345 aGroup->CloseOnDisk();
5347 // --> restore hypothesis from data
5348 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5349 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5350 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5351 SMESH::SMESH_Hypothesis_var myHyp;
5353 try { // protect persistence mechanism against exceptions
5354 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5357 INFOS( "Exception during hypothesis creation" );
5360 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5362 // myImpl->LoadFrom( hypdata.c_str() );
5363 hypDataList.push_back( make_pair( myImpl, hypdata ));
5364 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5365 int newId = myStudyContext->findId( iorString.in() );
5366 myStudyContext->mapOldToNew( id, newId );
5369 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5373 // close hypotheses root HDF group
5374 aTopGroup->CloseOnDisk();
5378 // --> then we should read&create algorithms
5379 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5380 // open algorithms root HDF group
5381 aTopGroup = new HDFgroup( "Algorithms", aFile );
5382 aTopGroup->OpenOnDisk();
5384 // get number of algorithms
5385 int aNbObjects = aTopGroup->nInternalObjects();
5386 for ( int j = 0; j < aNbObjects; j++ ) {
5387 // try to identify algorithm
5388 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5389 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5391 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5392 // open algorithm group
5393 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5394 aGroup->OpenOnDisk();
5396 // --> get algorithm id
5397 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5402 // get number of datasets
5403 int aNbSubObjects = aGroup->nInternalObjects();
5404 for ( int k = 0; k < aNbSubObjects; k++ ) {
5406 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5407 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5408 // --> get algorithm name
5409 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5410 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5411 aDataset->OpenOnDisk();
5412 size = aDataset->GetSize();
5413 char* hypname_str = new char[ size ];
5414 aDataset->ReadFromDisk( hypname_str );
5415 hypname = string( hypname_str );
5416 delete [] hypname_str;
5417 aDataset->CloseOnDisk();
5419 // --> get algorithm plugin library name
5420 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5421 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5422 aDataset->OpenOnDisk();
5423 size = aDataset->GetSize();
5424 char* libname_str = new char[ size ];
5425 aDataset->ReadFromDisk( libname_str );
5426 if(MYDEBUG) SCRUTE( libname_str );
5427 libname = string( libname_str );
5428 delete [] libname_str;
5429 aDataset->CloseOnDisk();
5431 // --> get algorithm data
5432 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5433 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5434 aDataset->OpenOnDisk();
5435 size = aDataset->GetSize();
5436 char* hypdata_str = new char[ size ];
5437 aDataset->ReadFromDisk( hypdata_str );
5438 if(MYDEBUG) SCRUTE( hypdata_str );
5439 hypdata = string( hypdata_str );
5440 delete [] hypdata_str;
5441 aDataset->CloseOnDisk();
5444 // close algorithm HDF group
5445 aGroup->CloseOnDisk();
5447 // --> restore algorithm from data
5448 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5449 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5450 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5451 SMESH::SMESH_Hypothesis_var myHyp;
5453 try { // protect persistence mechanism against exceptions
5454 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5456 catch( SALOME::SALOME_Exception& ex )
5458 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5461 INFOS( "Exception during hypothesis creation" );
5464 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5466 //myImpl->LoadFrom( hypdata.c_str() );
5467 hypDataList.push_back( make_pair( myImpl, hypdata ));
5468 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5469 int newId = myStudyContext->findId( iorString.in() );
5470 myStudyContext->mapOldToNew( id, newId );
5473 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5477 // close algorithms root HDF group
5478 aTopGroup->CloseOnDisk();
5482 // --> the rest groups should be meshes
5483 for ( int i = 0; i < aNbGroups; i++ ) {
5484 // identify next group
5485 char meshName[ HDF_NAME_MAX_LEN+1 ];
5486 aFile->InternalObjectIndentify( i, meshName );
5488 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5490 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5494 // open mesh HDF group
5495 aTopGroup = new HDFgroup( meshName, aFile );
5496 aTopGroup->OpenOnDisk();
5498 // get number of child HDF objects
5499 int aNbObjects = aTopGroup->nInternalObjects();
5500 if ( aNbObjects > 0 ) {
5502 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5503 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5504 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5505 if ( !myNewMeshImpl )
5507 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5509 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5510 int newId = myStudyContext->findId( iorString.in() );
5511 myStudyContext->mapOldToNew( id, newId );
5514 // try to read and set auto color flag
5515 char aMeshAutoColorName[ 30 ];
5516 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5517 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5519 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5520 aDataset->OpenOnDisk();
5521 size = aDataset->GetSize();
5522 int* anAutoColor = new int[ size ];
5523 aDataset->ReadFromDisk( anAutoColor );
5524 aDataset->CloseOnDisk();
5525 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5526 delete [] anAutoColor;
5529 // try to read and set reference to shape
5530 GEOM::GEOM_Object_var aShapeObject;
5531 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5532 // load mesh "Ref on shape" - it's an entry to SObject
5533 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5534 aDataset->OpenOnDisk();
5535 size = aDataset->GetSize();
5536 char* refFromFile = new char[ size ];
5537 aDataset->ReadFromDisk( refFromFile );
5538 aDataset->CloseOnDisk();
5539 if ( strlen( refFromFile ) > 0 ) {
5540 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5541 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5542 if ( !CORBA::is_nil( shapeObject ) ) {
5543 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5544 if ( !aShapeObject->_is_nil() )
5545 myNewMeshImpl->SetShape( aShapeObject );
5548 delete [] refFromFile;
5551 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5552 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5554 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5555 aDataset->OpenOnDisk();
5556 size = aDataset->GetSize();
5557 int* meshPersistentId = new int[ size ];
5558 aDataset->ReadFromDisk( meshPersistentId );
5559 aDataset->CloseOnDisk();
5560 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5561 delete [] meshPersistentId;
5564 // Restore SMESH_Mesh_i::_mainShapeTick
5565 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5567 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5568 aDataset->OpenOnDisk();
5569 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5570 aDataset->ReadFromDisk( shapeTick );
5571 aDataset->CloseOnDisk();
5574 // Restore file info
5575 if ( aTopGroup->ExistInternalObject( "file info" ))
5577 aDataset = new HDFdataset( "file info", aTopGroup );
5578 aDataset->OpenOnDisk();
5579 size = aDataset->GetSize();
5580 std::string info( size, ' ');
5581 aDataset->ReadFromDisk( (char*) info.data() );
5582 aDataset->CloseOnDisk();
5583 myNewMeshImpl->FileInfoFromString( info );
5589 // As all object that can be referred by hypothesis are created,
5590 // we can restore hypothesis data
5592 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5593 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5595 SMESH_Hypothesis_i* hyp = hyp_data->first;
5596 string & data = hyp_data->second;
5597 hyp->LoadFrom( data.c_str() );
5600 // Restore the rest mesh data
5602 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5603 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5605 aTopGroup = meshi_group->second;
5606 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5608 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5609 bool hasData = false;
5612 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5613 int newId = myStudyContext->findId( iorString.in() );
5614 int meshOldId = myStudyContext->getOldId( newId );
5616 // try to find mesh data dataset
5617 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5618 // load mesh "has data" flag
5619 aDataset = new HDFdataset( "Has data", aTopGroup );
5620 aDataset->OpenOnDisk();
5621 size = aDataset->GetSize();
5622 char* strHasData = new char[ size ];
5623 aDataset->ReadFromDisk( strHasData );
5624 aDataset->CloseOnDisk();
5625 if ( strcmp( strHasData, "1") == 0 ) {
5628 delete [] strHasData;
5631 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5632 // nodes and elements are not yet put into sub-meshes)
5633 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5634 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5635 aGroup->OpenOnDisk();
5636 // get number of applied algorithms
5637 int aNbSubObjects = aGroup->nInternalObjects();
5638 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5639 for ( int j = 0; j < aNbSubObjects; j++ ) {
5640 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5641 aGroup->InternalObjectIndentify( j, name_dataset );
5642 // check if it is an algorithm
5643 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5644 aDataset = new HDFdataset( name_dataset, aGroup );
5645 aDataset->OpenOnDisk();
5646 size = aDataset->GetSize();
5647 char* refFromFile = new char[ size ];
5648 aDataset->ReadFromDisk( refFromFile );
5649 aDataset->CloseOnDisk();
5650 // san - it is impossible to recover applied algorithms using their entries within Load() method
5651 int id = atoi( refFromFile );
5652 delete [] refFromFile;
5653 string anIOR = myStudyContext->getIORbyOldId( id );
5654 if ( !anIOR.empty() ) {
5655 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5656 if ( !CORBA::is_nil( hypObject ) ) {
5657 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5658 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5659 || !myNewMeshImpl->HasShapeToMesh()) )
5660 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5665 aGroup->CloseOnDisk();
5668 // try to get applied hypotheses
5669 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5670 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5671 aGroup->OpenOnDisk();
5672 // get number of applied hypotheses
5673 int aNbSubObjects = aGroup->nInternalObjects();
5674 for ( int j = 0; j < aNbSubObjects; j++ ) {
5675 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5676 aGroup->InternalObjectIndentify( j, name_dataset );
5677 // check if it is a hypothesis
5678 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5679 aDataset = new HDFdataset( name_dataset, aGroup );
5680 aDataset->OpenOnDisk();
5681 size = aDataset->GetSize();
5682 char* refFromFile = new char[ size ];
5683 aDataset->ReadFromDisk( refFromFile );
5684 aDataset->CloseOnDisk();
5685 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5686 int id = atoi( refFromFile );
5687 delete [] refFromFile;
5688 string anIOR = myStudyContext->getIORbyOldId( id );
5689 if ( !anIOR.empty() ) {
5690 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5691 if ( !CORBA::is_nil( hypObject ) ) {
5692 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5693 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5694 || !myNewMeshImpl->HasShapeToMesh()) )
5695 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5700 aGroup->CloseOnDisk();
5703 // --> try to find SUB-MESHES containers for each type of submesh
5704 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5705 const char* name_meshgroup = 0;
5706 if ( j == GetSubMeshOnVertexTag() )
5707 name_meshgroup = "SubMeshes On Vertex";
5708 else if ( j == GetSubMeshOnEdgeTag() )
5709 name_meshgroup = "SubMeshes On Edge";
5710 else if ( j == GetSubMeshOnWireTag() )
5711 name_meshgroup = "SubMeshes On Wire";
5712 else if ( j == GetSubMeshOnFaceTag() )
5713 name_meshgroup = "SubMeshes On Face";
5714 else if ( j == GetSubMeshOnShellTag() )
5715 name_meshgroup = "SubMeshes On Shell";
5716 else if ( j == GetSubMeshOnSolidTag() )
5717 name_meshgroup = "SubMeshes On Solid";
5718 else if ( j == GetSubMeshOnCompoundTag() )
5719 name_meshgroup = "SubMeshes On Compound";
5721 // try to get submeshes container HDF group
5722 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5723 // open submeshes containers HDF group
5724 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5725 aGroup->OpenOnDisk();
5727 // get number of submeshes
5728 int aNbSubMeshes = aGroup->nInternalObjects();
5729 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5731 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5732 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5733 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5734 // --> get submesh id
5735 int subid = atoi( name_submeshgroup + 7 );
5738 // open submesh HDF group
5739 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5740 aSubGroup->OpenOnDisk();
5742 // try to read and set reference to subshape
5743 GEOM::GEOM_Object_var aSubShapeObject;
5744 SMESH::SMESH_subMesh_var aSubMesh;
5746 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5747 // load submesh "Ref on shape" - it's an entry to SObject
5748 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5749 aDataset->OpenOnDisk();
5750 size = aDataset->GetSize();
5751 char* refFromFile = new char[ size ];
5752 aDataset->ReadFromDisk( refFromFile );
5753 aDataset->CloseOnDisk();
5754 if ( strlen( refFromFile ) > 0 ) {
5755 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5756 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5757 if ( !CORBA::is_nil( subShapeObject ) ) {
5758 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5759 if ( !aSubShapeObject->_is_nil() )
5760 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5761 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5762 if ( aSubMesh->_is_nil() )
5764 string iorSubString = GetORB()->object_to_string( aSubMesh );
5765 int newSubId = myStudyContext->findId( iorSubString );
5766 myStudyContext->mapOldToNew( subid, newSubId );
5769 delete [] refFromFile;
5772 if ( aSubMesh->_is_nil() )
5775 // try to get applied algorithms
5776 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5777 // open "applied algorithms" HDF group
5778 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5779 aSubSubGroup->OpenOnDisk();
5780 // get number of applied algorithms
5781 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5782 for ( int l = 0; l < aNbSubObjects; l++ ) {
5783 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5784 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5785 // check if it is an algorithm
5786 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5787 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5788 aDataset->OpenOnDisk();
5789 size = aDataset->GetSize();
5790 char* refFromFile = new char[ size ];
5791 aDataset->ReadFromDisk( refFromFile );
5792 aDataset->CloseOnDisk();
5794 int id = atoi( refFromFile );
5795 string anIOR = myStudyContext->getIORbyOldId( id );
5796 if ( !anIOR.empty() ) {
5797 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5798 if ( !CORBA::is_nil( hypObject ) ) {
5799 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5800 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5801 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5804 delete [] refFromFile;
5807 // close "applied algorithms" HDF group
5808 aSubSubGroup->CloseOnDisk();
5811 // try to get applied hypotheses
5812 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5813 // open "applied hypotheses" HDF group
5814 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5815 aSubSubGroup->OpenOnDisk();
5816 // get number of applied hypotheses
5817 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5818 for ( int l = 0; l < aNbSubObjects; l++ ) {
5819 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5820 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5821 // check if it is a hypothesis
5822 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5823 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5824 aDataset->OpenOnDisk();
5825 size = aDataset->GetSize();
5826 char* refFromFile = new char[ size ];
5827 aDataset->ReadFromDisk( refFromFile );
5828 aDataset->CloseOnDisk();
5830 int id = atoi( refFromFile );
5831 string anIOR = myStudyContext->getIORbyOldId( id );
5832 if ( !anIOR.empty() ) {
5833 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5834 if ( !CORBA::is_nil( hypObject ) ) {
5835 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5836 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5837 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5840 delete [] refFromFile;
5843 // close "APPLIED HYPOTHESES" hdf group
5844 aSubSubGroup->CloseOnDisk();
5847 // close SUB-MESH hdf group
5848 aSubGroup->CloseOnDisk();
5851 // close SUB-MESHES containers hdf group
5852 aGroup->CloseOnDisk();
5856 // try to get GROUPS
5857 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5858 char name_group[ 30 ];
5859 if ( ii == GetNodeGroupsTag() )
5860 strcpy( name_group, "Groups of Nodes" );
5861 else if ( ii == GetEdgeGroupsTag() )
5862 strcpy( name_group, "Groups of Edges" );
5863 else if ( ii == GetFaceGroupsTag() )
5864 strcpy( name_group, "Groups of Faces" );
5865 else if ( ii == GetVolumeGroupsTag() )
5866 strcpy( name_group, "Groups of Volumes" );
5867 else if ( ii == Get0DElementsGroupsTag() )
5868 strcpy( name_group, "Groups of 0D Elements" );
5869 else if ( ii == GetBallElementsGroupsTag() )
5870 strcpy( name_group, "Groups of Balls" );
5872 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5873 aGroup = new HDFgroup( name_group, aTopGroup );
5874 aGroup->OpenOnDisk();
5875 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5876 // within aGroup->ExistInternalObject( name )
5877 std::vector< std::string > subNames;
5878 TColStd_MapOfAsciiString mapOfNames;
5879 aGroup->GetAllObjects( subNames );
5880 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5881 mapOfNames.Add( subNames[ iN ].c_str() );
5883 for ( size_t j = 0; j < subNames.size(); j++ ) {
5884 const std::string& name_dataset = subNames[ j ];
5885 // check if it is a group
5886 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5889 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5892 int groupID = -1; // group local ID (also persistent)
5894 groupID = atoi( endptr + 1 );
5895 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5896 aDataset->OpenOnDisk();
5898 // Retrieve actual group name
5899 size = aDataset->GetSize();
5900 char* nameFromFile = new char[ size ];
5901 aDataset->ReadFromDisk( nameFromFile );
5902 aDataset->CloseOnDisk();
5904 // Try to find a shape reference
5905 TopoDS_Shape aShape;
5906 char aRefName[ 30 ];
5907 sprintf( aRefName, "Ref on shape %d", subid);
5908 if ( mapOfNames.Contains( aRefName ))
5910 // load mesh "Ref on shape" - it's an entry to SObject
5911 aDataset = new HDFdataset( aRefName, aGroup );
5912 aDataset->OpenOnDisk();
5913 size = aDataset->GetSize();
5914 char* refFromFile = new char[ size ];
5915 aDataset->ReadFromDisk( refFromFile );
5916 aDataset->CloseOnDisk();
5917 if ( strlen( refFromFile ) > 0 ) {
5918 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5919 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5920 if ( !CORBA::is_nil( shapeObject ) ) {
5921 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5922 if ( !aShapeObject->_is_nil() )
5923 aShape = GeomObjectToShape( aShapeObject );
5926 delete [] refFromFile;
5928 // Try to read a filter of SMESH_GroupOnFilter
5929 SMESH::Filter_var filter;
5930 SMESH_PredicatePtr predicate;
5931 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5932 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5934 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5935 aDataset->OpenOnDisk();
5936 size = aDataset->GetSize();
5937 char* persistStr = new char[ size ];
5938 aDataset->ReadFromDisk( persistStr );
5939 aDataset->CloseOnDisk();
5940 if ( strlen( persistStr ) > 0 ) {
5941 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5942 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5943 filters.push_back( filter );
5945 delete [] persistStr;
5948 // Create group servant
5949 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5950 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5951 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5952 delete [] nameFromFile;
5953 // Obtain a SMESHDS_Group object
5954 if ( aNewGroup->_is_nil() )
5957 string iorSubString = GetORB()->object_to_string( aNewGroup );
5958 int newSubId = myStudyContext->findId( iorSubString );
5959 myStudyContext->mapOldToNew( subid, newSubId );
5961 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5965 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5966 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5968 aFilterGroup->SetFilter( filter );
5969 filter->UnRegister();
5971 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5972 if ( !aGroupBaseDS )
5975 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5978 // Read color of the group
5979 char aGroupColorName[ 30 ];
5980 sprintf( aGroupColorName, "ColorGroup %d", subid);
5981 if ( mapOfNames.Contains( aGroupColorName ))
5983 aDataset = new HDFdataset( aGroupColorName, aGroup );
5984 aDataset->OpenOnDisk();
5985 size = aDataset->GetSize();
5986 double* anRGB = new double[ size ];
5987 aDataset->ReadFromDisk( anRGB );
5988 aDataset->CloseOnDisk();
5989 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5990 aGroupBaseDS->SetColor( aColor );
5995 aGroup->CloseOnDisk();
5999 // instead of reading mesh data, we read only brief information of all
6000 // objects: mesh, groups, sub-meshes (issue 0021208)
6003 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
6004 meshfile.ToCString(), filename.ToCString(),
6008 // read Sub-Mesh ORDER if any
6009 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
6010 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
6011 aDataset->OpenOnDisk();
6012 size = aDataset->GetSize();
6013 int* smIDs = new int[ size ];
6014 aDataset->ReadFromDisk( smIDs );
6015 aDataset->CloseOnDisk();
6016 TListOfListOfInt anOrderIds;
6017 anOrderIds.push_back( TListOfInt() );
6018 for ( int i = 0; i < size; i++ )
6019 if ( smIDs[ i ] < 0 ) // is separator
6020 anOrderIds.push_back( TListOfInt() );
6022 anOrderIds.back().push_back(smIDs[ i ]);
6024 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6027 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6029 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6030 aDataset->OpenOnDisk();
6031 size = aDataset->GetSize();
6032 std::string dataString; dataString.resize( size );
6033 aDataset->ReadFromDisk((char*) dataString.data() );
6034 aDataset->CloseOnDisk();
6036 std::istringstream istream( dataString.data() );
6037 boost::archive::text_iarchive archive( istream );
6038 std::list< std::list< std::string > > orderEntryLists;
6040 archive >> orderEntryLists;
6044 TListOfListOfInt anOrderIds;
6045 for ( const std::list< std::string >& entryList : orderEntryLists )
6047 anOrderIds.emplace_back();
6048 for ( const std::string & entry : entryList )
6050 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6051 TopoDS_Shape shape = GeomObjectToShape( go );
6052 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6053 anOrderIds.back().emplace_back( sm->GetId() );
6056 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6060 // update hyps needing full mesh data restored (issue 20918)
6061 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6063 SMESH_Hypothesis_i* hyp = hyp_data->first;
6064 hyp->UpdateAsMeshesRestored();
6067 // notify algos on completed restoration to set sub-mesh event listeners
6068 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6070 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6071 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6073 TopoDS_Shape myLocShape;
6074 if(myLocMesh.HasShapeToMesh())
6075 myLocShape = myLocMesh.GetShapeToMesh();
6077 myLocShape = SMESH_Mesh::PseudoShape();
6079 myLocMesh.GetSubMesh(myLocShape)->
6080 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6083 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6084 list< SMESH::Filter_var >::iterator f = filters.begin();
6085 for ( ; f != filters.end(); ++f )
6086 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6087 fi->FindBaseObjects();
6092 aTopGroup->CloseOnDisk();
6095 aFile->CloseOnDisk();
6098 // Remove temporary files created from the stream
6101 SMESH_File meshFile( meshfile.ToCString() );
6102 if ( !meshFile ) // no meshfile exists
6104 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6108 Engines::Container_var container = GetContainerRef();
6109 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6111 container_i->registerTemporaryFile( filename.ToCString() );
6112 container_i->registerTemporaryFile( meshfile.ToCString() );
6113 container_i->registerTemporaryFile( tmpDir.ToCString() );
6118 // creation of tree nodes for all data objects in the study
6119 // to support tree representation customization and drag-n-drop:
6120 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6121 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6122 useCaseBuilder->SetRootCurrent();
6123 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6124 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6125 for (it->InitEx(true); it->More(); it->Next()) {
6126 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6133 //=============================================================================
6135 * SMESH_Gen_i::LoadASCII
6137 * Load SMESH module's data in ASCII format
6139 //=============================================================================
6141 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6142 const SALOMEDS::TMPFile& theStream,
6144 bool isMultiFile ) {
6145 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6146 return Load( theComponent, theStream, theURL, isMultiFile );
6148 //before call main ::Load method it's need for decipher text format to
6149 //binary ( "|xx" => x' )
6150 int size = theStream.length();
6151 if ( int((size / 3 )*3) != size ) //error size of buffer
6154 int real_size = int(size / 3);
6156 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6159 unsigned int c = -1;
6160 for ( int i = 0; i < real_size; i++ )
6162 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6163 sscanf( tmp, "%x", &c );
6164 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6167 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6169 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6172 //=============================================================================
6174 * SMESH_Gen_i::Close
6176 * Clears study-connected data when it is closed
6178 //=============================================================================
6180 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6182 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6184 // Clear study contexts data
6185 myStudyContext->Clear();
6187 // remove the tmp files meshes are loaded from
6188 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6190 // Clean trace of API methods calls
6196 //=============================================================================
6198 * SMESH_Gen_i::ComponentDataType
6200 * Get component data type
6202 //=============================================================================
6204 char* SMESH_Gen_i::ComponentDataType()
6206 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6207 return CORBA::string_dup( "SMESH" );
6211 //=============================================================================
6213 * SMESH_Gen_i::IORToLocalPersistentID
6215 * Transform data from transient form to persistent
6217 //=============================================================================
6219 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6220 const char* IORString,
6221 CORBA::Boolean /*isMultiFile*/,
6222 CORBA::Boolean /*isASCII*/ )
6224 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6226 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6227 int anId = myStudyContext->findId( IORString );
6229 if(MYDEBUG) MESSAGE( "VSR " << anId )
6231 sprintf( strId, "%d", anId );
6232 return CORBA::string_dup( strId );
6235 return CORBA::string_dup( "" );
6238 //=============================================================================
6240 * SMESH_Gen_i::LocalPersistentIDToIOR
6242 * Transform data from persistent form to transient
6244 //=============================================================================
6246 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6247 const char* aLocalPersistentID,
6248 CORBA::Boolean /*isMultiFile*/,
6249 CORBA::Boolean /*isASCII*/ )
6251 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6253 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6254 int anId = atoi( aLocalPersistentID );
6255 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6257 return CORBA::string_dup( "" );
6260 //=======================================================================
6261 //function : RegisterObject
6263 //=======================================================================
6265 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6267 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6268 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6269 return myStudyContext->addObject( string( iorString.in() ) );
6274 //================================================================================
6276 * \brief Return id of registered object
6277 * \param theObject - the Object
6278 * \retval int - Object id
6280 //================================================================================
6282 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6284 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6285 string iorString = GetORB()->object_to_string( theObject );
6286 return myStudyContext->findId( iorString );
6291 //=============================================================================
6293 * SMESH_Gen_i::SetName
6295 * Set a new object name
6297 //=============================================================================
6299 void SMESH_Gen_i::SetName(const char* theIOR,
6300 const char* theName)
6302 if ( theIOR && strcmp( theIOR, "" ) ) {
6303 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6304 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6305 if ( !aSO->_is_nil() ) {
6306 SetName( aSO, theName );
6311 // Version information
6312 char* SMESH_Gen_i::getVersion()
6314 #if SMESH_DEVELOPMENT
6315 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6317 return CORBA::string_dup(SMESH_VERSION_STR);
6321 //=================================================================================
6322 // function : Move()
6323 // purpose : Moves objects to the specified position.
6324 // Is used in the drag-n-drop functionality.
6325 //=================================================================================
6327 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6328 SALOMEDS::SObject_ptr where,
6331 if ( CORBA::is_nil( where ) ) return;
6333 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6334 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6335 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6336 std::string dataType = father->ComponentDataType();
6337 if ( dataType != "SMESH" ) return; // not a SMESH component
6339 SALOMEDS::SObject_var objAfter;
6340 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6341 // insert at given row -> find insertion position
6342 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6344 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6345 if ( i == row && useCaseIt->More() ) {
6346 objAfter = useCaseIt->Value();
6350 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6351 SALOMEDS::SObject_var sobj = what[i];
6352 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6353 // insert the object to the use case tree
6354 if ( !CORBA::is_nil( objAfter ) )
6355 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6357 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6360 //================================================================================
6362 * \brief Returns true if algorithm can be used to mesh a given geometry
6363 * \param [in] theAlgoType - the algorithm type
6364 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6365 * \param [in] theGeomObject - the geometry to mesh
6366 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6367 * else, returns \c True if at least one shape is meshable
6368 * \return CORBA::Boolean - can or can't
6370 //================================================================================
6372 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6373 const char* theLibName,
6374 GEOM::GEOM_Object_ptr theGeomObject,
6375 CORBA::Boolean toCheckAll)
6379 std::string aPlatformLibName;
6380 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6381 GenericHypothesisCreator_i* aCreator =
6382 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6385 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6386 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6387 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6394 SMESH_CATCH( SMESH::doNothing );
6397 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6402 //================================================================================
6404 * \brief Collect indices of elements, which are located inside the sphere
6406 //================================================================================
6408 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6409 SMESH::ElementType theElemType,
6415 SMESH::long_array_var aResult = new SMESH::long_array();
6416 if ( meshPart->_is_nil() )
6417 return aResult._retn();
6419 // 1. Create geometrical object
6420 gp_Pnt aP( theX, theY, theZ );
6421 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6423 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6425 if ( lst.size() > 0 ) {
6426 aResult->length( lst.size() );
6427 for ( size_t i = 0; i < lst.size(); i++ ) {
6428 aResult[i] = lst[i];
6431 return aResult._retn();
6434 //================================================================================
6436 * \brief Collect indices of elements, which are located inside the box
6438 //================================================================================
6440 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6441 SMESH::ElementType theElemType,
6442 CORBA::Double theX1,
6443 CORBA::Double theY1,
6444 CORBA::Double theZ1,
6445 CORBA::Double theX2,
6446 CORBA::Double theY2,
6447 CORBA::Double theZ2)
6449 SMESH::long_array_var aResult = new SMESH::long_array();
6450 if( meshPart->_is_nil() )
6451 return aResult._retn();
6453 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6454 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6456 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6458 if( lst.size() > 0 ) {
6459 aResult->length( lst.size() );
6460 for ( size_t i = 0; i < lst.size(); i++ ) {
6461 aResult[i] = lst[i];
6464 return aResult._retn();
6467 //================================================================================
6469 * \brief Collect indices of elements, which are located inside the cylinder
6471 //================================================================================
6473 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6474 SMESH::ElementType theElemType,
6478 CORBA::Double theDX,
6479 CORBA::Double theDY,
6480 CORBA::Double theDZ,
6482 CORBA::Double theR )
6484 SMESH::long_array_var aResult = new SMESH::long_array();
6485 if( meshPart->_is_nil() )
6486 return aResult._retn();
6488 gp_Pnt aP( theX, theY, theZ );
6489 gp_Vec aV( theDX, theDY, theDZ );
6490 gp_Ax2 anAxes (aP, aV);
6492 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6494 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
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 geom object
6509 //================================================================================
6511 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6512 SMESH::ElementType theElemType,
6513 GEOM::GEOM_Object_ptr theGeom,
6514 CORBA::Double theTolerance )
6516 SMESH::long_array_var aResult = new SMESH::long_array();
6517 if( meshPart->_is_nil() || theGeom->_is_nil() )
6518 return aResult._retn();
6520 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6522 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6524 if( lst.size() > 0 ) {
6525 aResult->length( lst.size() );
6526 for ( size_t i = 0; i < lst.size(); i++ ) {
6527 aResult[i] = lst[i];
6530 return aResult._retn();
6533 //================================================================================
6535 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6537 //================================================================================
6539 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6540 SMESH::ElementType theElemType,
6541 const TopoDS_Shape& theShape,
6542 double* theTolerance) {
6544 std::vector<long> res;
6545 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6547 if ( mesh->_is_nil() )
6550 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6554 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6559 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6560 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6561 anElementsOnShape->SetAllNodes( true );
6562 anElementsOnShape->SetMesh( meshDS );
6563 anElementsOnShape->SetShape( theShape, aType );
6566 anElementsOnShape->SetTolerance(*theTolerance);
6568 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6569 if ( !msource->_is_nil() ) { // Mesh case
6570 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6572 while ( elemIt->more() ) {
6573 const SMDS_MeshElement* anElem = elemIt->next();
6574 long anId = anElem->GetID();
6575 if ( anElementsOnShape->IsSatisfy( anId ) )
6576 res.push_back( anId );
6580 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6581 if ( !gsource->_is_nil() ) {
6582 if(theElemType == SMESH::NODE) {
6583 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6584 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6585 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6586 long anId = node->GetID();
6587 if ( anElementsOnShape->IsSatisfy( anId ) )
6588 res.push_back( anId );
6591 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6592 SMESH::long_array_var elems = gsource->GetListOfID();
6593 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6594 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6595 long anId = elem->GetID();
6596 if ( anElementsOnShape->IsSatisfy( anId ) )
6597 res.push_back( anId );
6602 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6603 if ( !smsource->_is_nil() ) {
6604 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6605 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6606 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6608 long anId = elem->GetID();
6609 if ( anElementsOnShape->IsSatisfy( anId ) )
6610 res.push_back( anId );
6617 //=============================================================================
6619 * SMESHEngine_factory
6621 * C factory, accessible with dlsym, after dlopen
6623 //=============================================================================
6627 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6628 PortableServer::POA_ptr poa,
6629 PortableServer::ObjectId* contId,
6630 const char* instanceName,
6631 const char* interfaceName )
6633 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6634 if(MYDEBUG) SCRUTE(interfaceName);
6635 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6636 return aSMESHGen->getId() ;