1 // Copyright (C) 2007-2021 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>
57 #include <libgen.h> // for basename function
61 #define LibHandle HMODULE
62 #define LoadLib( name ) LoadLibrary( name )
63 #define GetProc GetProcAddress
64 #define UnLoadLib( handle ) FreeLibrary( handle );
66 #define LibHandle void*
68 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
69 #else // DYNLOAD_LOCAL
70 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
71 #endif // DYNLOAD_LOCAL
73 #define UnLoadLib( handle ) dlclose( handle );
76 #include "SMESH_Gen_i.hxx"
77 #include "SMESH_version.h"
79 #include "DriverMED_W_SMESHDS_Mesh.h"
80 #include "DriverMED_R_SMESHDS_Mesh.h"
82 #include "DriverCGNS_Read.hxx"
84 #include "MED_Factory.hxx"
85 #include "SMDS_EdgePosition.hxx"
86 #include "SMDS_FacePosition.hxx"
87 #include "SMDS_SetIterator.hxx"
88 #include "SMDS_SpacePosition.hxx"
89 #include "SMDS_VertexPosition.hxx"
90 #include "SMESHDS_Document.hxx"
91 #include "SMESHDS_Group.hxx"
92 #include "SMESHDS_GroupOnGeom.hxx"
93 #include "SMESH_Algo_i.hxx"
94 #include "SMESH_File.hxx"
95 #include "SMESH_Group.hxx"
96 #include "SMESH_Group_i.hxx"
97 #include "SMESH_Hypothesis.hxx"
98 #include "SMESH_Hypothesis_i.hxx"
99 #include "SMESH_Mesh.hxx"
100 #include "SMESH_MeshEditor.hxx"
101 #include "SMESH_Mesh_i.hxx"
102 #include "SMESH_PreMeshInfo.hxx"
103 #include "SMESH_PythonDump.hxx"
104 #include "SMESH_ControlsDef.hxx"
105 #include <SMESH_BoostTxtArchive.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/serialization/list.hpp>
149 #include <boost/serialization/string.hpp>
152 using SMESH::TPythonDump;
155 #define NUM_TMP_FILES 2
158 static int MYDEBUG = 0;
160 static int MYDEBUG = 0;
163 // Static variables definition
164 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
165 CORBA::ORB_var SMESH_Gen_i::myOrb;
166 PortableServer::POA_var SMESH_Gen_i::myPoa;
167 SALOME_NamingService_Abstract* SMESH_Gen_i::myNS = nullptr;
168 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = nullptr;
169 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = nullptr;
172 const int nbElemPerDiagonal = 10;
174 //=============================================================================
176 * GetServant [ static ]
178 * Get servant of the CORBA object
180 //=============================================================================
182 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
184 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
187 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
190 catch (PortableServer::POA::ObjectNotActive &ex)
192 INFOS("GetServant: ObjectNotActive");
195 catch (PortableServer::POA::WrongAdapter &ex)
197 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
200 catch (PortableServer::POA::WrongPolicy &ex)
202 INFOS("GetServant: WrongPolicy");
207 INFOS( "GetServant - Unknown exception was caught!!!" );
212 //=============================================================================
214 * SObjectToObject [ static ]
216 * Get CORBA object corresponding to the SALOMEDS::SObject
218 //=============================================================================
220 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
222 SALOMEDS::GenericAttribute_wrap anAttr;
223 CORBA::Object_var anObj;
224 if ( !theSObject->_is_nil() ) {
226 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
227 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
228 CORBA::String_var aValue = anIOR->Value();
229 if( strcmp( aValue, "" ) != 0 )
230 anObj = GetORB()->string_to_object( aValue );
234 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
240 // Set Naming Service object
241 void SMESH_Gen_i::SetNS(SALOME_NamingService_Abstract *ns)
248 //=============================================================================
252 * Get SALOME_NamingService object
254 //=============================================================================
256 SALOME_NamingService_Abstract* SMESH_Gen_i::GetNS()
259 myNS = SINGLETON_<SALOME_NamingService>::Instance();
260 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
261 myNS->init_orb( GetORB() );
266 //=============================================================================
270 * Get SALOME_LifeCycleCORBA object
272 //=============================================================================
274 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
276 if ( myLCC == NULL ) {
277 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
282 //=============================================================================
284 * GetGeomEngine [ static ]
286 * Get GEOM::GEOM_Gen reference
288 //=============================================================================
290 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
292 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
293 if ( !CORBA::is_nil( go ))
298 //=============================================================================
300 * SMESH_Gen_i::SMESH_Gen_i
302 * Default constructor: not for use
304 //=============================================================================
306 SMESH_Gen_i::SMESH_Gen_i()
310 //=============================================================================
312 * SMESH_Gen_i::SMESH_Gen_i
314 * Standard constructor, used with Container
316 //=============================================================================
318 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
319 PortableServer::POA_ptr poa,
320 PortableServer::ObjectId* contId,
321 const char* instanceName,
322 const char* interfaceName,
324 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
327 myOrb = CORBA::ORB::_duplicate(orb);
328 myPoa = PortableServer::POA::_duplicate(poa);
331 _id = myPoa->activate_object( _thisObj );
333 myStudyContext = new StudyContext;
335 myIsEmbeddedMode = false;
336 myIsEnablePublish = true;
337 myShapeReader = NULL; // shape reader
339 myIsHistoricalPythonDump = true;
340 myToForgetMeshDataOnHypModif = false;
342 // set it in standalone mode only
343 //OSD::SetSignal( true );
345 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
346 // find out mode (embedded or standalone) here else
347 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
348 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
351 if ( SALOME_NamingService_Abstract* ns = GetNS() )
353 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
354 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
355 if ( !session->_is_nil() )
357 CORBA::String_var str_host = session->getHostname();
358 CORBA::Long s_pid = session->getPID();
359 string my_host = Kernel_Utils::GetHostname();
361 long my_pid = (long)_getpid();
363 long my_pid = (long) getpid();
365 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
371 //=============================================================================
373 * SMESH_Gen_i::~SMESH_Gen_i
377 //=============================================================================
379 SMESH_Gen_i::~SMESH_Gen_i()
381 // delete hypothesis creators
382 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
383 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
385 // same creator can be mapped under different names
386 GenericHypothesisCreator_i* creator = (*itHyp).second;
390 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
391 if ( creator == (*itHyp2).second )
392 (*itHyp2).second = 0;
394 myHypCreatorMap.clear();
396 // Clear study contexts data
397 delete myStudyContext;
399 // delete shape reader
401 delete myShapeReader;
404 //=============================================================================
406 * SMESH_Gen_i::getHypothesisCreator
408 * Get hypothesis creator
410 //=============================================================================
412 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
413 const char* theLibName,
414 std::string& thePlatformLibName)
416 std::string aPlatformLibName;
417 /* It's Need to translate lib name for WIN32 or X platform */
418 if ( theLibName && theLibName[0] != '\0' )
420 int libNameLen = strlen(theLibName);
421 //check for old format "libXXXXXXX.so"
422 if (libNameLen > 7 &&
423 !strncmp( theLibName, "lib", 3 ) &&
424 !strcmp( theLibName+libNameLen-3, ".so" ))
428 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
429 #elif defined(__APPLE__)
430 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
432 aPlatformLibName = theLibName;
437 //try to use new format
439 aPlatformLibName = theLibName;
440 aPlatformLibName += ".dll";
441 #elif defined(__APPLE__)
442 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
444 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
448 thePlatformLibName = aPlatformLibName;
450 Unexpect aCatch(SALOME_SalomeException);
451 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
453 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
454 GenericHypothesisCreator_i* aCreator;
457 // check, if creator for this hypothesis type already exists
458 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
460 // load plugin library
461 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
464 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
465 SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
467 const char* path = aPlatformLibName.c_str();
470 const char* path = aPlatformLibName.c_str();
472 LibHandle libHandle = LoadLib( path );
476 // report any error, if occurred
478 const char* anError = dlerror();
479 throw(SALOME_Exception( anError ));
481 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
482 << aPlatformLibName));
486 // get method, returning hypothesis creator
487 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
488 GetHypothesisCreator procHandle =
489 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
492 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
493 << aPlatformLibName ));
494 UnLoadLib(libHandle);
497 // get hypothesis creator
498 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
499 aCreator = procHandle(theHypName);
502 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
503 << aPlatformLibName));
505 // map hypothesis creator to a hypothesis name
506 myHypCreatorMap[string(theHypName)] = aCreator;
511 return myHypCreatorMap[string(theHypName)];
514 catch (SALOME_Exception& S_ex)
516 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
521 //=============================================================================
523 * SMESH_Gen_i::createHypothesis
525 * Create hypothesis of given type
527 //=============================================================================
529 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
530 const char* theLibName)
532 SMESH_Hypothesis_i* myHypothesis_i = 0;
533 SMESH::SMESH_Hypothesis_var hypothesis_i;
534 std::string aPlatformLibName;
535 GenericHypothesisCreator_i* aCreator =
536 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
538 // create a new hypothesis object, store its ref. in studyContext
539 myHypothesis_i = aCreator->Create(myPoa, &myGen);
542 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
543 CORBA::String_var hypName = myHypothesis_i->GetName();
544 myHypCreatorMap[ hypName.in() ] = aCreator;
546 // activate the CORBA servant of hypothesis
547 hypothesis_i = myHypothesis_i->_this();
548 int nextId = RegisterObject( hypothesis_i );
549 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
550 else { (void)nextId; } // avoid "unused variable" warning in release mode
552 return hypothesis_i._retn();
555 //=============================================================================
557 * SMESH_Gen_i::createMesh
559 * Create empty mesh on shape
561 //=============================================================================
563 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
565 Unexpect aCatch(SALOME_SalomeException);
566 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
568 // Get or create the GEOM_Client instance
570 // create a new mesh object servant, store it in a map in study context
571 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
572 // create a new mesh object
573 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
574 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
576 // activate the CORBA servant of Mesh
577 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
578 int nextId = RegisterObject( mesh );
579 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
580 else { (void)nextId; } // avoid "unused variable" warning in release mode
583 catch (SALOME_Exception& S_ex) {
584 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
586 return SMESH::SMESH_Mesh::_nil();
589 //=============================================================================
591 * SMESH_Gen_i::GetShapeReader
595 //=============================================================================
597 GEOM_Client* SMESH_Gen_i::GetShapeReader()
599 // create shape reader if necessary
600 if ( !myShapeReader )
601 myShapeReader = new GEOM_Client(GetContainerRef());
602 ASSERT( myShapeReader );
603 return myShapeReader;
606 //=============================================================================
608 * SMESH_Gen_i::SetGeomEngine
610 * Set GEOM::GEOM_Gen reference
612 //=============================================================================
614 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
616 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
619 //=============================================================================
621 * SMESH_Gen_i::SetEmbeddedMode
625 //=============================================================================
627 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
629 myIsEmbeddedMode = theMode;
631 if ( !myIsEmbeddedMode ) {
632 //PAL10867: disable signals catching with "noexcepthandler" option
633 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
634 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
639 char* envDisableFPE = getenv("DISABLE_FPE");
640 if (envDisableFPE && atoi(envDisableFPE))
645 OSD::SetSignal( raiseFPE );
647 // else OSD::SetSignal() is called in GUI
651 //=============================================================================
653 * SMESH_Gen_i::IsEmbeddedMode
657 //=============================================================================
659 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
661 return myIsEmbeddedMode;
664 //=============================================================================
666 * SMESH_Gen_i::SetEnablePublish
668 * Set enable publishing in the study
670 //=============================================================================
672 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
674 myIsEnablePublish = theIsEnablePublish;
677 //=============================================================================
679 * SMESH_Gen_i::IsEnablePublish
681 * Check enable publishing
683 //=============================================================================
685 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
687 return myIsEnablePublish;
690 //=============================================================================
692 * SMESH_Gen_i::UpdateStudy
694 * Update study (needed at switching GEOM->SMESH)
696 //=============================================================================
698 void SMESH_Gen_i::UpdateStudy()
700 if ( !myStudyContext )
701 myStudyContext = new StudyContext;
703 SALOMEDS::Study_var aStudy = getStudyServant();
704 if ( !CORBA::is_nil( aStudy ) )
706 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
708 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
709 if( !GEOM_var->_is_nil() )
710 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
712 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
713 if( !GEOM_var->_is_nil() )
714 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
716 // NPAL16168, issue 0020210
717 // Let meshes update their data depending on GEOM groups that could change
718 CORBA::String_var compDataType = ComponentDataType();
719 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
720 if ( !me->_is_nil() ) {
721 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
722 for ( ; anIter->More(); anIter->Next() ) {
723 SALOMEDS::SObject_wrap so = anIter->Value();
724 CORBA::Object_var ior = SObjectToObject( so );
725 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
726 mesh->CheckGeomModif();
732 //================================================================================
734 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
736 //================================================================================
738 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
740 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
741 SALOMEDS::GenericAttribute_wrap attr;
742 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
744 SALOMEDS::AttributePixMap_wrap pm = attr;
745 CORBA::String_var ico = pm->GetPixMap();
746 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
751 //=================================================================================
752 // function : hasObjectInfo()
753 // purpose : shows if module provides information for its objects
754 //=================================================================================
756 bool SMESH_Gen_i::hasObjectInfo()
761 //=================================================================================
762 // function : getObjectInfo()
763 // purpose : returns an information for a given object by its entry
764 //=================================================================================
766 char* SMESH_Gen_i::getObjectInfo( const char* entry )
768 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
769 // for the rest, "module 'SMESH', ID=0:1:2:*"
773 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
774 CORBA::Object_var obj = SObjectToObject( so );
775 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
776 if ( isGeomModifIcon( mesh ))
778 txt << "The geometry was changed and the mesh needs to be recomputed";
783 CORBA::String_var compType = ComponentDataType();
784 txt << "module '" << compType << "', ID=" << entry;
786 return CORBA::string_dup( txt );
789 //=============================================================================
791 * SMESH_Gen_i::GetStudyContext
795 //=============================================================================
797 StudyContext* SMESH_Gen_i::GetStudyContext()
799 return myStudyContext;
802 //=============================================================================
804 * SMESH_Gen_i::CreateHypothesis
806 * Create hypothesis/algorithm of given type and publish it in the study
808 //=============================================================================
810 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
811 const char* theLibName )
813 Unexpect aCatch(SALOME_SalomeException);
814 // Create hypothesis/algorithm
815 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
817 // Publish hypothesis/algorithm in the study
818 if ( CanPublishInStudy( hyp ) ) {
819 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
820 if ( !aSO->_is_nil() ) {
821 // Update Python script
822 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
823 << theHypName << "', '" << theLibName << "')";
830 //================================================================================
832 * \brief Return a hypothesis initialized by given average length.
833 * \param theHypType - hypothesis type name
834 * \param theLibName - plugin library name
835 * \param theAverageLength - average length
836 * \param theQuadDominated - is quad-dominated flag
837 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
839 //================================================================================
841 SMESH::SMESH_Hypothesis_ptr
842 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
843 const char* theLibName,
844 CORBA::Double theAverageLength,
845 CORBA::Boolean theQuadDominated)
847 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
848 theAverageLength, theQuadDominated };
850 SMESH::SMESH_Hypothesis_var hyp =
851 GetHypothesisParameterValues( theHypType, theLibName,
852 SMESH::SMESH_Mesh::_nil(),
853 GEOM::GEOM_Object::_nil(),
855 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
857 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
858 << theHypType << "', '"
859 << theLibName << "', "
860 << theAverageLength << ", "
861 << theQuadDominated << " )";
866 //================================================================================
868 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
869 * existing on the given geometry or to size of the geometry.
870 * \param theHypType - hypothesis type name
871 * \param theLibName - plugin library name
872 * \param theMesh - The mesh of interest
873 * \param theGeom - The shape to get parameter values from
874 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
875 * in a study and used to compute the mesh, or a temporary one created just to pass
878 //================================================================================
880 SMESH::SMESH_Hypothesis_ptr
881 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
882 const char* theLibName,
883 SMESH::SMESH_Mesh_ptr theMesh,
884 GEOM::GEOM_Object_ptr theGeom,
885 const SMESH::HypInitParams& theParams)
887 Unexpect aCatch(SALOME_SalomeException);
889 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
890 if ( byMesh && CORBA::is_nil( theMesh ) )
891 return SMESH::SMESH_Hypothesis::_nil();
892 if ( byMesh && CORBA::is_nil( theGeom ) )
893 return SMESH::SMESH_Hypothesis::_nil();
895 // -----------------------------------------------
896 // find hypothesis used to mesh theGeom
897 // -----------------------------------------------
899 // get mesh and shape
900 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
901 TopoDS_Shape shape = GeomObjectToShape( theGeom );
902 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
903 return SMESH::SMESH_Hypothesis::_nil();
904 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
906 // create a temporary hypothesis to know its dimension
907 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
908 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
910 return SMESH::SMESH_Hypothesis::_nil();
911 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
914 // look for a hypothesis of theHypType used to mesh the shape
915 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
918 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
919 int nbLocalHyps = aHypList->length();
920 for ( int i = 0; i < nbLocalHyps; i++ ) {
921 CORBA::String_var hypName = aHypList[i]->GetName();
922 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
923 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
925 // check super shapes
926 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
927 while ( nbLocalHyps == 0 && itShape.More() ) {
928 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
929 if ( ! CORBA::is_nil( geomObj )) {
930 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
931 nbLocalHyps = aHypList->length();
932 for ( int i = 0; i < nbLocalHyps; i++ )
933 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
934 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
940 // let the temporary hypothesis find out somehow parameter values by mesh
941 if ( hyp->SetParametersByMesh( mesh, shape ))
942 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
946 ::SMESH_Hypothesis::TDefaults dflts;
947 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
948 dflts._nbSegments = myGen.GetDefaultNbSegments();
949 dflts._elemLength = theParams.averageLength;
950 dflts._quadDominated = theParams.quadDominated;
951 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
954 dflts._diagonal = mesh->GetShapeDiagonalSize();
956 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
957 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
958 dflts._shape = &shape;
961 // let the hypothesis initialize it's values
962 if ( hyp->SetParametersByDefaults( dflts, mesh ))
963 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
966 return SMESH::SMESH_Hypothesis::_nil();
969 //=============================================================================
971 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
972 * \param [in] theHyp - the hypothesis of interest
973 * \param [out] theMesh - the sole mesh using \a theHyp
974 * \param [out] theShape - the sole geometry \a theHyp is assigned to
975 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
977 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
978 * considered as SAME sub-mesh => result is \c true.
979 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
980 * a shape to which an hyp being edited is assigned.
982 //=============================================================================
984 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
985 SMESH::SMESH_Mesh_out theMesh,
986 GEOM::GEOM_Object_out theShape)
988 if ( CORBA::is_nil( theHyp ))
991 // get Mesh component SO
992 CORBA::String_var compDataType = ComponentDataType();
993 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
994 if ( CORBA::is_nil( comp ))
997 // look for child SO of meshes
998 SMESH::SMESH_Mesh_var foundMesh;
999 TopoDS_Shape foundShape;
1001 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1002 for ( ; meshIter->More() && isSole; meshIter->Next() )
1004 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1005 CORBA::Object_var obj = SObjectToObject( curSO );
1006 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1010 // look for a sole shape where theHyp is assigned
1011 bool isHypFound = false;
1012 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1013 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1014 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1016 const THypList& hyps = s2hypsIt.Value();
1017 THypList::const_iterator h = hyps.begin();
1018 for ( ; h != hyps.end(); ++h )
1019 if ( (*h)->GetID() == theHyp->GetId() )
1021 if ( h != hyps.end()) // theHyp found
1024 if ( ! foundShape.IsNull() &&
1025 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1027 foundShape.Nullify();
1031 foundShape = s2hypsIt.Key();
1033 } // loop on assigned hyps
1035 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1037 if ( !foundMesh->_is_nil() ) // not a sole mesh
1039 if ( !foundMesh->HasShapeToMesh() ||
1040 !mesh_i ->HasShapeToMesh() )
1042 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1046 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1047 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1048 isSole = s1->IsSame( s2 );
1051 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1057 ! foundMesh->_is_nil() &&
1058 ! foundShape.IsNull() )
1060 theMesh = foundMesh._retn();
1061 theShape = ShapeToGeomObject( foundShape );
1062 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1067 //=============================================================================
1069 * Set number of segments per diagonal of boundary box of geometry by which
1070 * default segment length of appropriate 1D hypotheses is defined
1072 //=============================================================================
1074 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1076 if ( theNbSegments > 0 )
1077 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1079 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1082 //=============================================================================
1084 * \brief Set default number of segments per edge
1086 //=============================================================================
1088 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1090 if ( theNbSegments > 0 )
1091 myGen.SetDefaultNbSegments( int(theNbSegments) );
1093 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1096 //=============================================================================
1098 * Set an option value
1100 //=============================================================================
1102 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1104 if ( name && value && strlen( value ) > 0 )
1107 if ( strcmp(name, "historical_python_dump") == 0 )
1109 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1110 msgToGUI = "preferences/SMESH/historical_python_dump/";
1111 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1113 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1115 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1116 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1117 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1119 else if ( strcmp(name, "default_grp_color") == 0 )
1123 // color must be presented as a string of following form:
1124 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1125 str = str.substr(1);
1126 for ( size_t i = 0; i < str.length()/2; i++ )
1127 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1128 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1130 else if ( value ) { // rgb color ("255,170,0", for example)
1131 string tempValue( value );
1132 char* colorValue = strtok( &tempValue[0], "," );
1133 while ( colorValue != NULL ) {
1134 int c_value = atoi( colorValue );
1135 if ( c_value >= 0 && c_value <= 255 )
1136 color.push_back( c_value );
1137 colorValue = strtok( NULL, "," );
1140 if ( color.size() == 3 ) { // color must have three valid component
1141 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1142 myDefaultGroupColor = value;
1143 msgToGUI = "preferences/SMESH/default_grp_color/";
1148 // update preferences in case if SetOption() is invoked from python console
1149 if ( !msgToGUI.empty() )
1151 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1152 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1153 if ( !CORBA::is_nil( session ) )
1154 session->emitMessageOneWay(msgToGUI.c_str());
1159 //=============================================================================
1161 * Return an option value
1163 //=============================================================================
1165 char* SMESH_Gen_i::GetOption(const char* name)
1169 if ( strcmp(name, "historical_python_dump") == 0 )
1171 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1173 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1175 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1177 if ( strcmp(name, "default_grp_color") == 0 )
1179 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1182 return CORBA::string_dup( "" );
1185 //=============================================================================
1187 * SMESH_Gen_i::CreateMesh
1189 * Create empty mesh on a shape and publish it in the study
1191 //=============================================================================
1193 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1195 Unexpect aCatch(SALOME_SalomeException);
1196 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1198 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1200 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1201 ASSERT( meshServant );
1202 meshServant->SetShape( theShapeObject );
1204 // publish mesh in the study
1205 if ( CanPublishInStudy( mesh ) ) {
1206 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1207 aStudyBuilder->NewCommand(); // There is a transaction
1208 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1209 aStudyBuilder->CommitCommand();
1210 if ( !aSO->_is_nil() ) {
1211 // Update Python script
1212 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1216 return mesh._retn();
1219 //=============================================================================
1221 * SMESH_Gen_i::CreateEmptyMesh
1225 //=============================================================================
1227 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1229 Unexpect aCatch(SALOME_SalomeException);
1230 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1232 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1234 // publish mesh in the study
1235 if ( CanPublishInStudy( mesh ) ) {
1236 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1237 aStudyBuilder->NewCommand(); // There is a transaction
1238 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1239 aStudyBuilder->CommitCommand();
1240 if ( !aSO->_is_nil() ) {
1241 // Update Python script
1242 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1246 return mesh._retn();
1251 //================================================================================
1253 * \brief Throw an exception in case if the file can't be read
1255 //================================================================================
1257 void checkFileReadable( const char* theFileName )
1259 SMESH_File f ( theFileName );
1262 if ( !f.error().empty() )
1263 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1265 THROW_SALOME_CORBA_EXCEPTION
1266 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1267 SALOME::BAD_PARAM );
1272 //=============================================================================
1274 * SMESH_Gen_i::CreateMeshFromUNV
1276 * Create mesh and import data from UNV file
1278 //=============================================================================
1280 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1282 Unexpect aCatch(SALOME_SalomeException);
1284 checkFileReadable( theFileName );
1286 SMESH::SMESH_Mesh_var aMesh = createMesh();
1288 // publish mesh in the study
1289 if ( CanPublishInStudy( aMesh ) ) {
1290 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1291 aStudyBuilder->NewCommand(); // There is a transaction
1292 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1293 aStudyBuilder->CommitCommand();
1294 if ( !aSO->_is_nil() ) {
1295 // Update Python script
1296 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1300 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1302 aServant->ImportUNVFile( theFileName );
1304 // Dump creation of groups
1305 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1307 aServant->GetImpl().GetMeshDS()->Modified();
1308 return aMesh._retn();
1311 //=============================================================================
1313 * SMESH_Gen_i::CreateMeshFromMED
1315 * Create mesh and import data from MED file
1317 //=============================================================================
1319 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1320 SMESH::DriverMED_ReadStatus& theStatus,
1321 const char* theCommandNameForPython,
1322 const char* theFileNameForPython)
1325 char bname[ _MAX_FNAME ];
1326 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1327 string aFileName = bname;
1329 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1331 // Retrieve mesh names from the file
1332 DriverMED_R_SMESHDS_Mesh myReader;
1333 myReader.SetFile( theFileName );
1334 myReader.SetMeshId( -1 );
1335 Driver_Mesh::Status aStatus;
1336 list<string> aNames = myReader.GetMeshNames(aStatus);
1337 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1338 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1340 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1343 TPythonDump aPythonDump(this);
1344 aPythonDump << "([";
1346 if (theStatus == SMESH::DRS_OK) {
1347 SALOMEDS::StudyBuilder_var aStudyBuilder;
1348 aStudyBuilder = getStudyServant()->NewBuilder();
1349 aStudyBuilder->NewCommand(); // There is a transaction
1351 aResult->length( aNames.size() );
1354 // Iterate through all meshes and create mesh objects
1355 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1358 if (i > 0) aPythonDump << ", ";
1361 SMESH::SMESH_Mesh_var mesh = createMesh();
1363 // publish mesh in the study
1364 SALOMEDS::SObject_wrap aSO;
1365 if ( CanPublishInStudy( mesh ) )
1366 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1367 // - as names of meshes are stored in MED file, we use them for data publishing
1368 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1369 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1372 if ( !aSO->_is_nil() ) {
1375 aPythonDump << "mesh_" << i;
1378 // Read mesh data (groups are published automatically by ImportMEDFile())
1379 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1380 ASSERT( meshServant );
1381 SMESH::DriverMED_ReadStatus status1 =
1382 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1383 if (status1 > theStatus)
1384 theStatus = status1;
1386 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1387 meshServant->GetImpl().GetMeshDS()->Modified();
1389 if ( !aStudyBuilder->_is_nil() )
1390 aStudyBuilder->CommitCommand();
1393 // Update Python script
1394 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1396 // Dump creation of groups
1397 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1398 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1400 return aResult._retn();
1403 //================================================================================
1405 * \brief Create meshes by reading a MED file
1407 //================================================================================
1409 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1410 SMESH::DriverMED_ReadStatus& theStatus)
1412 Unexpect aCatch(SALOME_SalomeException);
1413 checkFileReadable( theFileName );
1415 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1416 "CreateMeshesFromMED", theFileName);
1420 //=============================================================================
1422 * SMESH_Gen_i::CreateMeshFromSAUV
1424 * Create mesh and import data from SAUV file
1426 //=============================================================================
1428 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1429 SMESH::DriverMED_ReadStatus& theStatus)
1431 Unexpect aCatch(SALOME_SalomeException);
1432 checkFileReadable( theFileName );
1434 std::string sauvfilename(theFileName);
1435 std::string medfilename(theFileName);
1436 medfilename += ".med";
1439 cmd = "%PYTHONBIN% ";
1444 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1446 system(cmd.c_str());
1447 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1449 "CreateMeshesFromSAUV",
1450 sauvfilename.c_str());
1452 cmd = "%PYTHONBIN% ";
1457 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1459 system(cmd.c_str());
1463 //=============================================================================
1465 * SMESH_Gen_i::CreateMeshFromSTL
1467 * Create mesh and import data from STL file
1469 //=============================================================================
1471 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1473 Unexpect aCatch(SALOME_SalomeException);
1474 checkFileReadable( theFileName );
1476 SMESH::SMESH_Mesh_var aMesh = createMesh();
1479 char bname[ _MAX_FNAME ];
1480 _splitpath( theFileName, NULL, NULL, bname, NULL );
1481 string aFileName = bname;
1483 string aFileName = basename( const_cast<char *>(theFileName) );
1485 // publish mesh in the study
1486 if ( CanPublishInStudy( aMesh ) ) {
1487 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1488 aStudyBuilder->NewCommand(); // There is a transaction
1489 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1490 aStudyBuilder->CommitCommand();
1491 if ( !aSO->_is_nil() ) {
1492 // Update Python script
1493 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1497 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1499 aServant->ImportSTLFile( theFileName );
1500 aServant->GetImpl().GetMeshDS()->Modified();
1501 return aMesh._retn();
1504 //================================================================================
1506 * \brief Create meshes and import data from the CGSN file
1508 //================================================================================
1510 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1511 SMESH::DriverMED_ReadStatus& theStatus)
1513 Unexpect aCatch(SALOME_SalomeException);
1514 checkFileReadable( theFileName );
1516 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1519 // Retrieve nb meshes from the file
1520 DriverCGNS_Read myReader;
1521 myReader.SetFile( theFileName );
1522 Driver_Mesh::Status aStatus;
1523 int nbMeshes = myReader.GetNbMeshes(aStatus);
1524 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1526 aResult->length( nbMeshes );
1528 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1531 TPythonDump aPythonDump(this);
1532 aPythonDump << "([";
1534 if (theStatus == SMESH::DRS_OK)
1536 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1537 aStudyBuilder->NewCommand(); // There is a transaction
1541 // Iterate through all meshes and create mesh objects
1542 for ( ; i < nbMeshes; ++i )
1545 if (i > 0) aPythonDump << ", ";
1548 SMESH::SMESH_Mesh_var mesh = createMesh();
1549 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1551 // Read mesh data (groups are published automatically by ImportMEDFile())
1552 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1553 ASSERT( meshServant );
1555 SMESH::DriverMED_ReadStatus status1 =
1556 meshServant->ImportCGNSFile( theFileName, i, meshName );
1557 if (status1 > theStatus)
1558 theStatus = status1;
1560 meshServant->GetImpl().GetMeshDS()->Modified();
1561 // publish mesh in the study
1562 SALOMEDS::SObject_wrap aSO;
1563 if ( CanPublishInStudy( mesh ) )
1564 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1567 if ( !aSO->_is_nil() ) {
1571 aPythonDump << "mesh_" << i;
1574 aStudyBuilder->CommitCommand();
1577 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1579 // Dump creation of groups
1580 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1581 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1583 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1586 return aResult._retn();
1589 //================================================================================
1591 * \brief Create a mesh and import data from a GMF file
1593 //================================================================================
1595 SMESH::SMESH_Mesh_ptr
1596 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1597 CORBA::Boolean theMakeRequiredGroups,
1598 SMESH::ComputeError_out theError)
1600 Unexpect aCatch(SALOME_SalomeException);
1601 checkFileReadable( theFileName );
1603 SMESH::SMESH_Mesh_var aMesh = createMesh();
1605 char bname[ _MAX_FNAME ];
1606 _splitpath( theFileName, NULL, NULL, bname, NULL );
1607 string aFileName = bname;
1609 string aFileName = basename( const_cast<char *>(theFileName) );
1611 // publish mesh in the study
1612 if ( CanPublishInStudy( aMesh ) ) {
1613 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1614 aStudyBuilder->NewCommand(); // There is a transaction
1615 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1616 aStudyBuilder->CommitCommand();
1617 if ( !aSO->_is_nil() ) {
1618 // Update Python script
1619 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1620 << theFileName << "', "
1621 << theMakeRequiredGroups << " )";
1624 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1626 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1627 aServant->GetImpl().GetMeshDS()->Modified();
1628 return aMesh._retn();
1632 //=============================================================================
1634 * SMESH_Gen_i::IsReadyToCompute
1636 * Return true if mesh contains enough data to be computed
1638 //=============================================================================
1640 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1641 GEOM::GEOM_Object_ptr theShapeObject )
1643 Unexpect aCatch(SALOME_SalomeException);
1644 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1646 if ( CORBA::is_nil( theShapeObject ) )
1647 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1648 SALOME::BAD_PARAM );
1649 if ( CORBA::is_nil( theMesh ) )
1650 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1651 SALOME::BAD_PARAM );
1654 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1655 ASSERT( meshServant );
1656 if ( meshServant ) {
1657 // get local TopoDS_Shape
1658 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1659 // call implementation
1660 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1661 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1664 catch ( SALOME_Exception& S_ex ) {
1665 INFOS( "catch exception "<< S_ex.what() );
1670 //================================================================================
1672 * \brief Find SObject for an algo
1674 //================================================================================
1676 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1679 SALOMEDS::Study_var aStudy = getStudyServant();
1680 if ( !aStudy->_is_nil() ) {
1681 // find algo in the study
1682 CORBA::String_var compDataType = ComponentDataType();
1683 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1684 if ( !father->_is_nil() ) {
1685 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1686 for ( ; itBig->More(); itBig->Next() ) {
1687 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1688 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1689 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1690 for ( ; algoIt->More(); algoIt->Next() ) {
1691 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1692 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1693 if ( !CORBA::is_nil( algoIOR )) {
1694 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1695 if ( impl && impl->GetImpl() == algo )
1696 return algoSO._retn();
1698 } // loop on algo SO's
1701 } // SMESH component iterator
1705 return SALOMEDS::SObject::_nil();
1708 //================================================================================
1710 * \brief Return errors of mesh computation
1712 //================================================================================
1714 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1715 GEOM::GEOM_Object_ptr theSubObject )
1717 Unexpect aCatch(SALOME_SalomeException);
1718 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1720 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1721 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1723 if ( CORBA::is_nil( theMesh ) )
1724 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1726 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1728 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1731 if(theMesh->HasShapeToMesh())
1732 shape = GeomObjectToShape( theSubObject );
1734 shape = SMESH_Mesh::PseudoShape();
1736 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1738 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1741 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1742 const bool includeSelf = true, complexShapeFirst = true;
1743 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1745 while ( smIt->more() )
1748 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1750 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1751 if ( error && !error->IsOK() )
1753 if ( !( error->myAlgo ) &&
1754 !( error->myAlgo = sm->GetAlgo() ))
1756 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1757 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1758 errStruct.comment = error->myComment.c_str();
1759 errStruct.subShapeID = sm->GetId();
1760 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1761 if ( !algoSO->_is_nil() ) {
1762 CORBA::String_var algoName = algoSO->GetName();
1763 errStruct.algoName = algoName;
1766 errStruct.algoName = error->myAlgo->GetName();
1768 errStruct.hasBadMesh = error->HasBadElems();
1771 error_array->length( nbErr );
1774 catch ( SALOME_Exception& S_ex ) {
1775 INFOS( "catch exception "<< S_ex.what() );
1778 return error_array._retn();
1781 //================================================================================
1783 * \brief Return mesh elements preventing computation of a subshape
1785 //================================================================================
1787 SMESH::MeshPreviewStruct*
1788 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1789 CORBA::Short theSubShapeID )
1791 Unexpect aCatch(SALOME_SalomeException);
1792 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1794 if ( CORBA::is_nil( theMesh ) )
1795 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1797 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1800 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1802 // mesh implementation
1803 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1804 // submesh by subshape id
1805 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1808 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1809 if ( error && error->HasBadElems() )
1811 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1812 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1814 // get nodes of elements and count elements
1815 TNode2LocalIDMap mapNode2LocalID;
1816 list< TNodeLocalID > connectivity;
1817 int i, nbElements = 0, nbConnNodes = 0;
1819 const list<const SMDS_MeshElement*>& badElems =
1820 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1821 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1822 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1823 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1825 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1826 while ( nIt->more() )
1827 connectivity.push_back
1828 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1830 // fill node coords and assign local ids to the nodes
1831 int nbNodes = mapNode2LocalID.size();
1832 result->nodesXYZ.length( nbNodes );
1833 TNodeLocalID node2ID = mapNode2LocalID.begin();
1834 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1835 node2ID->second = i;
1836 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1837 result->nodesXYZ[i].x = node->X();
1838 result->nodesXYZ[i].y = node->Y();
1839 result->nodesXYZ[i].z = node->Z();
1841 // fill connectivity
1842 result->elementConnectivities.length( nbConnNodes );
1843 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1844 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1845 result->elementConnectivities[i] = (*connIt)->second;
1847 // fill element types
1848 result->elementTypes.length( nbElements );
1849 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1851 const SMDS_MeshElement* elem = *elemIt;
1852 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1853 result->elementTypes[i].isPoly = elem->IsPoly();
1854 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1860 catch ( SALOME_Exception& S_ex ) {
1861 INFOS( "catch exception "<< S_ex.what() );
1864 return result._retn();
1867 //================================================================================
1869 * \brief Create a group of elements preventing computation of a sub-shape
1871 //================================================================================
1873 SMESH::ListOfGroups*
1874 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1875 CORBA::Short theSubShapeID,
1876 const char* theGroupName )
1878 Unexpect aCatch(SALOME_SalomeException);
1880 SMESH::ListOfGroups_var groups;
1882 if ( CORBA::is_nil( theMesh ) )
1883 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1886 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1888 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1889 TPythonDump(this) << groups << " = " << this
1890 << ".MakeGroupsOfBadInputElements( "
1891 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1894 catch ( SALOME_Exception& S_ex ) {
1895 INFOS( "catch exception "<< S_ex.what() );
1897 return groups._retn();
1900 //================================================================================
1902 * \brief Returns errors of hypotheses definition
1903 * \param theMesh - the mesh
1904 * \param theSubObject - the main or sub- shape
1905 * \retval SMESH::algo_error_array* - sequence of errors
1907 //================================================================================
1909 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1910 GEOM::GEOM_Object_ptr theSubObject )
1912 Unexpect aCatch(SALOME_SalomeException);
1913 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1915 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1916 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1918 if ( CORBA::is_nil( theMesh ) )
1919 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1921 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1923 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1924 ASSERT( meshServant );
1925 if ( meshServant ) {
1926 TopoDS_Shape myLocShape;
1927 if(theMesh->HasShapeToMesh())
1928 myLocShape = GeomObjectToShape( theSubObject );
1930 myLocShape = SMESH_Mesh::PseudoShape();
1932 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1933 list< ::SMESH_Gen::TAlgoStateError > error_list;
1934 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1935 // call ::SMESH_Gen::GetAlgoState()
1936 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1937 error_array->length( error_list.size() );
1939 for ( error = error_list.begin(); error != error_list.end(); ++error )
1941 // fill AlgoStateError structure
1942 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1943 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1944 errStruct.algoDim = error->_algoDim;
1945 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1946 errStruct.algoName = "";
1947 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1948 if ( !algoSO->_is_nil() ) {
1949 CORBA::String_var algoName = algoSO->GetName();
1950 errStruct.algoName = algoName.in();
1955 catch ( SALOME_Exception& S_ex ) {
1956 INFOS( "catch exception "<< S_ex.what() );
1958 return error_array._retn();
1961 //=============================================================================
1963 * SMESH_Gen_i::GetSubShapesId
1965 * Get sub-shapes unique ID's list
1967 //=============================================================================
1970 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1971 const SMESH::object_array& theListOfSubShapeObject )
1973 Unexpect aCatch(SALOME_SalomeException);
1974 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1976 SMESH::long_array_var shapesId = new SMESH::long_array;
1979 if ( CORBA::is_nil( theMainShapeObject ) )
1980 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1984 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1985 TopTools_IndexedMapOfShape myIndexToShape;
1986 TopExp::MapShapes(myMainShape,myIndexToShape);
1988 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1990 GEOM::GEOM_Object_var aShapeObject
1991 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1992 if ( CORBA::is_nil( aShapeObject ) )
1993 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1994 SALOME::BAD_PARAM );
1996 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1997 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1999 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2000 setId.insert(myIndexToShape.FindIndex(F));
2001 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2003 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2005 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2006 setId.insert(myIndexToShape.FindIndex(E));
2007 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2009 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2011 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2012 setId.insert(myIndexToShape.FindIndex(V));
2013 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2016 shapesId->length(setId.size());
2017 set<int>::iterator iind;
2019 for (iind = setId.begin(); iind != setId.end(); iind++)
2021 if(MYDEBUG) SCRUTE((*iind));
2022 shapesId[i] = (*iind);
2023 if(MYDEBUG) SCRUTE(shapesId[i]);
2027 catch (SALOME_Exception& S_ex)
2029 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2032 return shapesId._retn();
2035 //=============================================================================
2037 * SMESH_Gen_i::Compute
2039 * Compute mesh on a shape
2041 //=============================================================================
2043 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2044 GEOM::GEOM_Object_ptr theShapeObject )
2047 Unexpect aCatch(SALOME_SalomeException);
2048 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2050 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2051 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2052 SALOME::BAD_PARAM );
2054 if ( CORBA::is_nil( theMesh ) )
2055 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2056 SALOME::BAD_PARAM );
2058 // Update Python script
2059 TPythonDump(this) << "isDone = " << this << ".Compute( "
2060 << theMesh << ", " << theShapeObject << ")";
2064 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2065 ASSERT( meshServant );
2066 if ( meshServant ) {
2067 if ( isGeomModifIcon( theMesh ))
2068 meshServant->Clear();
2070 meshServant->Load();
2071 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2072 meshServant->CheckGeomModif();
2073 // get local TopoDS_Shape
2074 TopoDS_Shape myLocShape;
2075 if(theMesh->HasShapeToMesh())
2076 myLocShape = GeomObjectToShape( theShapeObject );
2078 myLocShape = SMESH_Mesh::PseudoShape();
2079 // call implementation compute
2080 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2081 myGen.PrepareCompute( myLocMesh, myLocShape );
2082 int how = ::SMESH_Gen::COMPACT_MESH;
2083 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2084 how |= ::SMESH_Gen::SHAPE_ONLY;
2085 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2086 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2087 myLocMesh.GetMeshDS()->Modified();
2088 UpdateIcons( theMesh );
2090 HighLightInvalid( theMesh, /*isInvalid=*/false );
2094 catch ( std::bad_alloc& ) {
2095 INFOS( "Compute(): lack of memory" );
2097 catch ( SALOME_Exception& S_ex ) {
2098 INFOS( "Compute(): catch exception "<< S_ex.what() );
2101 INFOS( "Compute(): unknown exception " );
2106 //=============================================================================
2108 * SMESH_Gen_i::CancelCompute
2110 * Cancel Compute mesh on a shape
2112 //=============================================================================
2114 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2115 GEOM::GEOM_Object_ptr theShapeObject )
2117 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2119 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2120 TopoDS_Shape myLocShape;
2121 if(theMesh->HasShapeToMesh())
2122 myLocShape = GeomObjectToShape( theShapeObject );
2124 myLocShape = SMESH_Mesh::PseudoShape();
2125 myGen.CancelCompute( myLocMesh, myLocShape);
2129 //=============================================================================
2131 * SMESH_Gen_i::Precompute
2133 * Compute mesh as preview till indicated dimension on shape
2135 //=============================================================================
2137 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2138 GEOM::GEOM_Object_ptr theShapeObject,
2139 SMESH::Dimension theDimension,
2140 SMESH::long_array& theShapesId)
2142 Unexpect aCatch(SALOME_SalomeException);
2143 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2145 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2146 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2147 SALOME::BAD_PARAM );
2149 if ( CORBA::is_nil( theMesh ) )
2150 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2151 SALOME::BAD_PARAM );
2153 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2156 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2157 meshServant->Load();
2158 ASSERT( meshServant );
2159 if ( meshServant ) {
2160 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2161 meshServant->CheckGeomModif();
2162 // get local TopoDS_Shape
2163 TopoDS_Shape myLocShape;
2164 if(theMesh->HasShapeToMesh())
2165 myLocShape = GeomObjectToShape( theShapeObject );
2167 return result._retn();
2169 // call implementation compute
2170 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2172 ::MeshDimension aDim = (MeshDimension)theDimension;
2173 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2175 int nbShapeId = shapeIds.size();
2176 theShapesId.length( nbShapeId );
2177 // iterates on shapes and collect mesh entities into mesh preview
2178 TSetOfInt::const_iterator idIt = shapeIds.begin();
2179 TSetOfInt::const_iterator idEnd = shapeIds.end();
2180 std::map< int, int > mapOfShIdNb;
2181 std::set< SMESH_TLink > setOfEdge;
2182 std::list< SMDSAbs_ElementType > listOfElemType;
2183 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2184 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2185 TNode2LocalIDMap mapNode2LocalID;
2186 list< TNodeLocalID > connectivity;
2187 int i, nbConnNodes = 0;
2188 std::set< const SMESH_subMesh* > setOfVSubMesh;
2189 // iterates on shapes
2190 for ( ; idIt != idEnd; idIt++ )
2192 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2194 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2195 if ( !sm || !sm->IsMeshComputed() )
2198 const TopoDS_Shape& aSh = sm->GetSubShape();
2199 const int shDim = myGen.GetShapeDim( aSh );
2200 if ( shDim < 1 || shDim > theDimension )
2203 mapOfShIdNb[ *idIt ] = 0;
2204 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2206 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2207 if ( !smDS ) continue;
2209 if ( theDimension == SMESH::DIM_2D )
2211 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2212 while ( faceIt->more() )
2214 const SMDS_MeshElement* face = faceIt->next();
2215 int aNbNode = face->NbNodes();
2217 aNbNode /= 2; // do not take into account additional middle nodes
2219 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2220 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2222 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2223 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2225 listOfElemType.push_back( SMDSAbs_Edge );
2226 connectivity.push_back
2227 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2228 connectivity.push_back
2229 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2235 else if ( theDimension == SMESH::DIM_1D )
2237 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2238 while ( nodeIt->more() )
2240 listOfElemType.push_back( SMDSAbs_Node );
2241 connectivity.push_back
2242 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2244 // add corner nodes by first vertex from edge
2245 SMESH_subMeshIteratorPtr edgeSmIt =
2246 sm->getDependsOnIterator(/*includeSelf*/false,
2247 /*complexShapeFirst*/false);
2248 while ( edgeSmIt->more() )
2250 SMESH_subMesh* vertexSM = edgeSmIt->next();
2251 // check that vertex is not already treated
2252 if ( !setOfVSubMesh.insert( vertexSM ).second )
2254 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2257 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2258 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2259 while ( nodeIt->more() )
2261 listOfElemType.push_back( SMDSAbs_Node );
2262 connectivity.push_back
2263 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2269 // fill node coords and assign local ids to the nodes
2270 int nbNodes = mapNode2LocalID.size();
2271 result->nodesXYZ.length( nbNodes );
2272 TNodeLocalID node2ID = mapNode2LocalID.begin();
2273 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2274 node2ID->second = i;
2275 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2276 result->nodesXYZ[i].x = node->X();
2277 result->nodesXYZ[i].y = node->Y();
2278 result->nodesXYZ[i].z = node->Z();
2280 // fill connectivity
2281 result->elementConnectivities.length( nbConnNodes );
2282 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2283 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2284 result->elementConnectivities[i] = (*connIt)->second;
2287 // fill element types
2288 result->elementTypes.length( listOfElemType.size() );
2289 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2290 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2291 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2293 SMDSAbs_ElementType elemType = *typeIt;
2294 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2295 result->elementTypes[i].isPoly = false;
2296 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2299 // correct number of shapes
2300 theShapesId.length( mapOfShIdNb.size() );
2304 catch ( std::bad_alloc& ) {
2305 INFOS( "Precompute(): lack of memory" );
2307 catch ( SALOME_Exception& S_ex ) {
2308 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2311 INFOS( "Precompute(): unknown exception " );
2313 return result._retn();
2317 //=============================================================================
2319 * SMESH_Gen_i::Evaluate
2321 * Evaluate mesh on a shape
2323 //=============================================================================
2325 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2326 GEOM::GEOM_Object_ptr theShapeObject)
2328 Unexpect aCatch(SALOME_SalomeException);
2329 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2331 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2332 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2334 if ( CORBA::is_nil( theMesh ) )
2335 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2337 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2338 nbels->length(SMESH::Entity_Last);
2339 int i = SMESH::Entity_Node;
2340 for (; i < SMESH::Entity_Last; i++)
2343 // Update Python script
2344 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2345 << theMesh << ", " << theShapeObject << ")";
2349 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2350 ASSERT( meshServant );
2351 if ( meshServant ) {
2352 meshServant->Load();
2353 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2354 meshServant->CheckGeomModif();
2355 // get local TopoDS_Shape
2356 TopoDS_Shape myLocShape;
2357 if(theMesh->HasShapeToMesh())
2358 myLocShape = GeomObjectToShape( theShapeObject );
2360 myLocShape = SMESH_Mesh::PseudoShape();
2361 // call implementation compute
2362 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2363 MapShapeNbElems aResMap;
2364 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2365 MapShapeNbElemsItr anIt = aResMap.begin();
2366 for(; anIt!=aResMap.end(); anIt++) {
2367 const vector<smIdType>& aVec = (*anIt).second;
2368 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2369 smIdType nbElem = aVec[i];
2370 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2372 SMESH_subMesh* sm = anIt->first;
2373 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2374 const SMESH_Algo* algo = sm->GetAlgo();
2375 if ( (algo && !error.get()) || error->IsOK() )
2376 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2380 nbels[i] += aVec[i];
2384 return nbels._retn();
2387 catch ( std::bad_alloc& ) {
2388 INFOS( "Evaluate(): lack of memory" );
2390 catch ( SALOME_Exception& S_ex ) {
2391 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2394 INFOS( "Evaluate(): unknown exception " );
2397 return nbels._retn();
2400 //================================================================================
2402 * \brief Return geometrical object the given element is built on
2403 * \param theMesh - the mesh the element is in
2404 * \param theElementID - the element ID
2405 * \param theGeomName - the name of the result geom object if it is not yet published
2406 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2408 //================================================================================
2410 GEOM::GEOM_Object_ptr
2411 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2412 SMESH::smIdType theElementID,
2413 const char* theGeomName)
2415 Unexpect aCatch(SALOME_SalomeException);
2417 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2418 if ( !geom->_is_nil() ) {
2419 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2420 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2422 // try to find the corresponding SObject
2423 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2424 if ( SObj->_is_nil() ) // submesh can be not found even if published
2426 // try to find published submesh
2427 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2428 if ( !geom->IsMainShape() && list->length() == 1 ) {
2429 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2430 SALOMEDS::ChildIterator_wrap it;
2431 if ( !mainSO->_is_nil() ) {
2432 it = getStudyServant()->NewChildIterator( mainSO );
2434 if ( !it->_is_nil() ) {
2435 for ( it->InitEx(true); it->More(); it->Next() ) {
2436 SALOMEDS::SObject_wrap so = it->Value();
2437 CORBA::Object_var obj = SObjectToObject( so );
2438 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2439 if ( !subGeom->_is_nil() ) {
2440 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2441 if ( subList->length() == 1 && list[0] == subList[0] ) {
2451 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2452 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2454 // return only published geometry
2455 if ( !SObj->_is_nil() ) {
2456 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2457 CORBA::Object_var obj = SObjectToObject( SObj );
2458 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2462 return GEOM::GEOM_Object::_nil();
2465 //================================================================================
2467 * \brief Return geometrical object the given element is built on.
2468 * \param theMesh - the mesh the element is in
2469 * \param theElementID - the element ID
2470 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2472 //================================================================================
2474 GEOM::GEOM_Object_ptr
2475 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2476 SMESH::smIdType theElementID)
2478 Unexpect aCatch(SALOME_SalomeException);
2479 if ( CORBA::is_nil( theMesh ) )
2480 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2482 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2483 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2485 // get a core mesh DS
2486 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2487 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2489 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2490 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2491 // find the element in mesh
2492 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2493 // find a shape id by the element
2494 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2495 // get a geom object by the shape id
2496 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2497 if ( geom->_is_nil() ) {
2498 // try to find a published sub-shape
2499 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2500 SALOMEDS::ChildIterator_wrap it;
2501 if ( !mainSO->_is_nil() ) {
2502 it = getStudyServant()->NewChildIterator( mainSO );
2504 if ( !it->_is_nil() ) {
2505 for ( it->InitEx(true); it->More(); it->Next() ) {
2506 SALOMEDS::SObject_wrap so = it->Value();
2507 CORBA::Object_var obj = SObjectToObject( so );
2508 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2509 if ( !subGeom->_is_nil() ) {
2510 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2511 if ( subList->length() == 1 && shapeID == subList[0] ) {
2519 if ( geom->_is_nil() ) {
2521 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2522 if ( !op->_is_nil() )
2523 geom = op->GetSubShape( mainShape, shapeID );
2528 if ( !geom->_is_nil() ) {
2529 GeomObjectToShape( geom ); // let geom client remember the found shape
2530 return geom._retn();
2535 return GEOM::GEOM_Object::_nil();
2538 //================================================================================
2540 * SMESH_Gen_i::Concatenate
2542 * Concatenate the given meshes into one mesh
2544 //================================================================================
2546 SMESH::SMESH_Mesh_ptr
2547 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2548 CORBA::Boolean theUniteIdenticalGroups,
2549 CORBA::Boolean theMergeNodesAndElements,
2550 CORBA::Double theMergeTolerance,
2551 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2553 return ConcatenateCommon(theMeshesArray,
2554 theUniteIdenticalGroups,
2555 theMergeNodesAndElements,
2561 //================================================================================
2563 * SMESH_Gen_i::ConcatenateWithGroups
2565 * Concatenate the given meshes into one mesh
2566 * Create the groups of all elements from initial meshes
2568 //================================================================================
2570 SMESH::SMESH_Mesh_ptr
2571 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2572 CORBA::Boolean theUniteIdenticalGroups,
2573 CORBA::Boolean theMergeNodesAndElements,
2574 CORBA::Double theMergeTolerance,
2575 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2577 return ConcatenateCommon(theMeshesArray,
2578 theUniteIdenticalGroups,
2579 theMergeNodesAndElements,
2585 //================================================================================
2587 * SMESH_Gen_i::ConcatenateCommon
2589 * Concatenate the given meshes into one mesh
2591 //================================================================================
2593 SMESH::SMESH_Mesh_ptr
2594 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2595 CORBA::Boolean theUniteIdenticalGroups,
2596 CORBA::Boolean theMergeNodesAndElements,
2597 CORBA::Double theMergeTolerance,
2598 CORBA::Boolean theCommonGroups,
2599 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2601 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2602 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2604 // create mesh if theMeshToAppendTo not provided
2605 SMESH::SMESH_Mesh_var newMesh;
2606 if ( CORBA::is_nil( theMeshToAppendTo ))
2607 newMesh = CreateEmptyMesh();
2609 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2610 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2611 if ( !newImpl ) return newMesh._retn();
2614 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2615 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2617 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2618 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2619 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2620 TGroupsMap groupsMap;
2621 TListOfNewGroups listOfNewGroups;
2623 if ( !CORBA::is_nil( theMeshToAppendTo ))
2625 // fill groupsMap with existing groups
2626 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2627 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2629 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2630 if ( !group->_is_nil() )
2632 CORBA::String_var name = group->GetName();
2633 SMESH::ElementType type = group->GetType();
2634 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2639 ::SMESH_MeshEditor newEditor( &locMesh );
2640 ::SMESH_MeshEditor::ElemFeatures elemType;
2642 // loop on sub-meshes
2643 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2645 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2646 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2647 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2648 if ( !initImpl ) continue;
2649 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2653 // assure that IDs increment by one during iteration
2654 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2655 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2656 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2657 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2659 initMeshDS->Modified();
2660 initMeshDS->CompactMesh();
2663 // remember nb of elements before filling in
2664 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2668 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2669 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2670 while ( elemIt->more() )
2672 SMESH_NodeXYZ node = elemIt->next();
2673 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2678 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2679 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2681 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2682 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2683 while ( elemIt->more() )
2685 const SMDS_MeshElement* elem = elemIt->next();
2686 elemType.myNodes.resize( elem->NbNodes() );
2688 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2689 for ( int k = 0; itNodes->more(); k++)
2691 const SMDS_MeshNode* node = itNodes->next();
2692 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2695 // creates a corresponding element on existent nodes in new mesh
2696 newElems[ elem->GetID() ] =
2697 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2699 newEditor.ClearLastCreated(); // forget the history
2702 // create groups of just added elements
2703 SMESH::SMESH_Group_var newGroup;
2704 SMESH::ElementType groupType;
2705 if ( theCommonGroups )
2708 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2710 // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2711 static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2712 "Update names of ElementType's!!!" );
2714 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2716 for( groupType = SMESH::NODE;
2717 groupType < SMESH::NB_ELEMENT_TYPES;
2718 groupType = (SMESH::ElementType)( groupType + 1 ))
2720 if ( curState[ groupType ] <= prevState[ groupType ])
2721 continue; // no elements of groupType added from the i-th mesh
2723 // make a group name
2724 std::string groupName = "Gr";
2725 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2727 CORBA::String_var name = meshSO->GetName();
2731 groupName += typeNames[ groupType ];
2733 // make and fill a group
2734 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2735 std::vector< const SMDS_MeshElement* > & elemVec =
2736 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2737 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2739 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2741 for ( size_t j = 0; j < elemVec.size(); ++j )
2743 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2744 grpDS->Add( elemVec[j] );
2748 listOfNewGroups.clear();
2749 listOfNewGroups.push_back( newGroup );
2750 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2755 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2759 SMESH::SMESH_GroupBase_ptr group;
2760 CORBA::String_var groupName;
2761 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2763 // loop on groups of a source mesh
2764 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2765 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2767 group = listOfGroups[iG];
2768 groupType = group->GetType();
2769 groupName = group->GetName();
2770 std::string name = groupName.in();
2772 // convert a list of IDs
2773 newIDs->length( group->Size() );
2774 std::vector< const SMDS_MeshElement* > & elemVec =
2775 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2776 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2778 while ( itGrElems->more() )
2780 const SMDS_MeshElement* elem = itGrElems->next();
2781 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2783 newIDs[ nbElems++ ] = newElem->GetID();
2785 newIDs->length( nbElems );
2787 // check that a current group name and type don't have identical ones in final mesh
2788 listOfNewGroups.clear();
2789 TNameAndType nameAndType( name, groupType );
2790 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2791 if ( anIter == groupsMap.end() )
2793 // add a new group in the mesh
2794 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2795 newGroup->Add( newIDs );
2797 listOfNewGroups.push_back( newGroup );
2798 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2800 else if ( theUniteIdenticalGroups )
2802 // unite identical groups
2803 TListOfNewGroups& aNewGroups = anIter->second;
2804 aNewGroups.front()->Add( newIDs );
2808 // rename identical groups
2809 newGroup = newImpl->CreateGroup( groupType, groupName );
2810 newGroup->Add( newIDs );
2812 TListOfNewGroups& newGroups = anIter->second;
2813 std::string newGroupName;
2814 if ( newGroups.size() == 1 )
2816 newGroupName = name + "_1";
2817 newGroups.front()->SetName( newGroupName.c_str() );
2819 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2820 newGroup->SetName( newGroupName.c_str() );
2821 newGroups.push_back( newGroup );
2824 } // if an IDSource is a mesh
2827 if ( theMergeNodesAndElements ) // merge nodes
2829 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2830 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2831 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2832 /*SeparateCornersAndMedium=*/ false );
2833 newEditor.MergeNodes( groupsOfNodes );
2835 newEditor.MergeEqualElements();
2838 // Update Python script
2839 pythonDump << newMesh << " = " << this
2840 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2841 << theMeshesArray << ", "
2842 << theUniteIdenticalGroups << ", "
2843 << theMergeNodesAndElements << ", "
2844 << TVar( theMergeTolerance ) << ", "
2845 << theMeshToAppendTo << " )";
2847 pPythonDump.reset(); // enable python dump from GetGroups()
2849 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2850 if ( !newMesh->_is_nil() )
2852 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2855 // IPAL21468 Change icon of compound because it need not be computed.
2856 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2857 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2859 newMeshDS->Modified();
2861 return newMesh._retn();
2864 //================================================================================
2866 * \brief Create a mesh by copying a part of another mesh
2867 * \param meshPart - a part of mesh to copy
2868 * \param toCopyGroups - to create in the new mesh groups
2869 * the copied elements belongs to
2870 * \param toKeepIDs - to preserve IDs of the copied elements or not
2871 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2873 //================================================================================
2875 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2876 const char* meshName,
2877 CORBA::Boolean toCopyGroups,
2878 CORBA::Boolean toKeepIDs)
2880 Unexpect aCatch(SALOME_SalomeException);
2882 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2883 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2885 // 1. Get source mesh
2887 if ( CORBA::is_nil( meshPart ))
2888 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2890 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2891 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2893 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2895 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2897 // 2. Make a new mesh
2899 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2900 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2902 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2903 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2904 if ( !meshSO->_is_nil() )
2906 SetName( meshSO, meshName, "Mesh" );
2907 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2909 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2910 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2911 ::SMESH_MeshEditor::ElemFeatures elemType;
2913 // 3. Get elements to copy
2915 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2916 TIDSortedElemSet srcElems;
2917 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2918 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2921 srcElemIt = srcMeshDS->elementsIterator();
2922 srcNodeIt = srcMeshDS->nodesIterator();
2926 SMESH::smIdType_array_var ids = meshPart->GetIDs();
2927 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2929 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2930 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2931 srcElems.insert( elem );
2935 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2936 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2937 srcElems.insert( elem );
2939 if ( srcElems.empty() )
2940 return newMesh._retn();
2942 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2943 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2948 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2949 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2950 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2952 const SMDS_MeshNode *nSrc, *nTgt;
2953 vector< const SMDS_MeshNode* > nodes;
2954 while ( srcElemIt->more() )
2956 const SMDS_MeshElement * elem = srcElemIt->next();
2958 nodes.resize( elem->NbNodes());
2959 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2961 for ( iN = 0; nIt->more(); ++iN )
2963 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2964 nTgt = newMeshDS->FindNode( nSrc->GetID());
2966 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2971 for ( iN = 0; nIt->more(); ++iN )
2973 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2974 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2976 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2977 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2981 if ( elem->GetType() != SMDSAbs_Node )
2983 elemType.Init( elem, /*basicOnly=*/false );
2984 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2986 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2987 if ( toCopyGroups && !toKeepIDs )
2988 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2990 } // while ( srcElemIt->more() )
2992 // 4(b). Copy free nodes
2994 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2996 while ( srcNodeIt->more() )
2998 nSrc = srcNodeIt->next();
2999 if ( nSrc->NbInverseElements() == 0 )
3002 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3004 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3011 int nbNewGroups = 0;
3014 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3015 while ( gIt->more() )
3017 SMESH_Group* group = gIt->next();
3018 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3020 // Check group type. We copy nodal groups containing nodes of copied element
3021 SMDSAbs_ElementType groupType = groupDS->GetType();
3022 if ( groupType != SMDSAbs_Node &&
3023 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3024 continue; // group type differs from types of meshPart
3026 // Find copied elements in the group
3027 vector< const SMDS_MeshElement* > groupElems;
3028 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3031 const SMDS_MeshElement* foundElem;
3032 if ( groupType == SMDSAbs_Node )
3034 while ( eIt->more() )
3035 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3036 groupElems.push_back( foundElem );
3040 while ( eIt->more() )
3041 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3042 groupElems.push_back( foundElem );
3047 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3048 if ( e2eMap.empty() ) continue;
3049 smIdType minID = e2eMap.begin()->first->GetID();
3050 smIdType maxID = e2eMap.rbegin()->first->GetID();
3051 TE2EMap::iterator e2e;
3052 while ( eIt->more() && groupElems.size() < e2eMap.size())
3054 const SMDS_MeshElement* e = eIt->next();
3055 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3056 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3057 groupElems.push_back( e2e->second );
3061 if ( !groupElems.empty() )
3063 SMESH::SMESH_Group_var newGroupObj =
3064 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3065 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3067 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3068 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3069 for ( unsigned i = 0; i < groupElems.size(); ++i )
3070 smdsGroup.Add( groupElems[i] );
3078 newMeshDS->Modified();
3080 *pyDump << newMesh << " = " << this
3081 << ".CopyMesh( " << meshPart << ", "
3082 << "'" << meshName << "', "
3083 << toCopyGroups << ", "
3084 << toKeepIDs << ")";
3086 pyDumpDeleter.reset(); // allow dump in GetGroups()
3088 if ( nbNewGroups > 0 ) // dump created groups
3089 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3091 return newMesh._retn();
3095 namespace // utils for CopyMeshWithGeom()
3097 typedef std::map< std::string, std::string > TStr2StrMap;
3098 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3099 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3100 typedef std::map< std::string, int > TName2IndexMap;
3102 //================================================================================
3104 * \brief Return a new sub-shape corresponding to an old one
3106 //================================================================================
3110 SMESH_Mesh_i* mySrcMesh_i;
3111 SMESH_Mesh_i* myNewMesh_i;
3112 SMESH_Gen_i* myGen_i;
3116 TStr2StrMap myOld2NewEntryMap; // map of study entries
3118 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3119 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3120 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3123 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3125 // not directly relating to shape search
3126 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3128 //================================================================================
3130 * \brief Constructor
3132 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3133 SMESH_Mesh_i* newMesh_i,
3134 SMESH_Gen_i* smeshGen_i )
3135 : mySrcMesh_i( srcMesh_i ),
3136 myNewMesh_i( newMesh_i ),
3137 myGen_i ( smeshGen_i ),
3138 myToPublish( smeshGen_i->IsEnablePublish() ),
3139 myGIPMapDone( false )
3141 // retrieve from the study shape mapping made thanks to
3142 // "Set presentation parameters and sub-shapes from arguments" option
3144 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3145 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3146 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3147 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3148 if ( newSO->_is_nil() )
3150 myToPublish = false;
3153 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3155 CORBA::String_var oldEntry = oldSO->GetID();
3156 CORBA::String_var newEntry = newSO->GetID();
3157 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3158 std::string( newEntry.in() )));
3159 std::string newMainEntry = newEntry.in();
3161 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3162 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3163 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3164 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3165 /*groupsOnly=*/false );
3166 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3168 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3169 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3170 bool refFound = false;
3171 for ( ; anIter->More(); anIter->Next() )
3173 SALOMEDS::SObject_wrap so = anIter->Value();
3174 if ( so->ReferencedObject( oldSO.inout() ))
3176 oldEntry = oldSO->GetID();
3177 newEntry = newSO->GetID();
3178 if (( refFound = ( newMainEntry != oldEntry.in() )))
3179 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3180 std::string( newEntry.in() )));
3185 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3186 if ( father->_is_equivalent( mainShapeNew ))
3188 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3189 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3190 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3191 CORBA::String_var name = newSO->GetName();
3193 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3199 //================================================================================
3201 * \brief Find a new sub-shape corresponding to an old one
3203 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3206 return GEOM::GEOM_Object::_duplicate( oldShape );
3208 GEOM::GEOM_Object_var newShape;
3210 if ( CORBA::is_nil( oldShape ))
3211 return newShape._retn();
3213 if ( !isChildOfOld( oldShape ))
3214 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3216 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3217 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3219 // try to find by entry or name
3222 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3223 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3224 if ( o2nID != myOld2NewEntryMap.end() )
3226 newShape = getShapeByEntry( o2nID->second );
3228 if ( newShape->_is_nil() )
3230 CORBA::String_var name = oldShape->GetName();
3231 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3232 if ( n2ind != myName2SubshapeIndex.end() )
3234 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3235 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3236 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3237 if ( oldIndices->length() == 0 ||
3238 newIndices->length() == 0 ||
3239 getShapeType( myNewMesh_i, newIndices[0] ) !=
3240 getShapeType( mySrcMesh_i, oldIndices[0] ))
3241 newShape = GEOM::GEOM_Object::_nil();
3246 if ( newShape->_is_nil() )
3248 // try to construct a new sub-shape using myGIPMap
3250 std::vector< int > newIndices;
3251 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3252 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3254 findNewIDs( oldIndices[i], newIndices );
3256 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3259 newShape = getInPlace( oldShape );
3261 if ( !newIndices.empty() && newShape->_is_nil() )
3263 // search for a sub-shape with same ids
3264 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3265 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3266 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3267 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3269 if ( newShape->_is_nil() )
3272 // create a new shape
3273 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3275 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3277 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3278 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3280 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3281 newIndicesList->length( newIndices.size() );
3282 for ( size_t i = 0; i < newIndices.size(); ++i )
3283 newIndicesList[ i ] = newIndices[ i ];
3284 grOp->UnionIDs( newShape, newIndicesList );
3288 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3289 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3298 if ( !newShape->_is_nil() && myToPublish )
3300 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3301 if ( !newEntry.in() || !newEntry.in()[0] )
3303 CORBA::String_var name = oldShape->GetName();
3304 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3305 newEntry = newShape->GetStudyEntry();
3306 oldEntry = oldShape->GetStudyEntry();
3307 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3308 std::string( newEntry.in() )));
3312 return newShape._retn();
3315 //================================================================================
3317 * \brief Return a study entry of a new shape by study entry of the old one
3319 std::string FindNew( const std::string & oldEntry )
3324 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3325 if ( o2nID != myOld2NewEntryMap.end() )
3326 return o2nID->second;
3328 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3329 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3332 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3333 if ( newShape->_is_nil() )
3334 return std::string();
3336 CORBA::String_var newEntry = newShape->GetStudyEntry();
3337 return newEntry.in();
3340 //================================================================================
3342 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3343 * Return zero if not found or there are more than one new ID
3345 int FindNew( int oldID )
3354 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3356 if ( myGIPMap[ oldID ].length() == 1 )
3358 newID = myGIPMap[ oldID ][ 0 ];
3360 else if ( myGIPMap[ oldID ].length() > 1 &&
3361 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3363 // select a meshed VERTEX
3364 SMESH_subMesh* newSM;
3365 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3366 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3367 ( !newSM->IsEmpty() ))
3368 newID = myGIPMap[ oldID ][ i ];
3374 //================================================================================
3376 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3377 * Return zero if the old shape is not kept as is in the new shape.
3379 int FindNewNotChanged( SMESH_subMesh* oldSM )
3382 return oldSM->GetId();
3384 int newID = FindNew( oldSM->GetId() );
3388 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3392 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3393 // one new sub-shape of the same type.
3395 if ( oldSM->DependsOn().size() !=
3396 newSM->DependsOn().size() )
3399 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3400 while ( srcSMIt->more() )
3402 oldSM = srcSMIt->next();
3403 int newSubID = FindNew( oldSM->GetId() );
3404 if ( getShapeType( myNewMesh_i, newSubID ) !=
3405 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3411 //================================================================================
3413 * \brief Return shape by study entry
3415 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3417 GEOM::GEOM_Object_var shape;
3418 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3419 if ( !so->_is_nil() )
3421 CORBA::Object_var obj = so->GetObject();
3422 shape = GEOM::GEOM_Object::_narrow( obj );
3424 return shape._retn();
3427 //================================================================================
3429 * \brief Fill myGIPMap by calling GetInPlaceMap()
3433 if ( !myGIPMapDone )
3435 myGIPMapDone = true;
3437 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3438 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3439 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3440 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3443 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3447 myGIPMap = new GEOM::ListOfListOfLong();
3452 //================================================================================
3454 * \brief Get new sub-shape by calling GetInPlace()
3456 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3458 GEOM::GEOM_Object_var newShape;
3460 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3461 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3462 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3465 newShape = op->GetInPlace( mainShapeNew, oldShape );
3470 return newShape._retn();
3473 //================================================================================
3475 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3476 * number of found IDs
3478 int findNewIDs( int oldID, std::vector< int >& newIDs )
3480 size_t prevNbIDs = newIDs.size();
3482 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3484 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3485 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3487 return newIDs.size() - prevNbIDs;
3490 //================================================================================
3492 * \brief Check if an object relates to the old shape
3494 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3496 if ( CORBA::is_nil( oldShape ))
3498 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3499 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3500 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3501 mainShapeOld1->_is_equivalent( oldShape ));
3504 //================================================================================
3506 * \brief Return shape type by shape ID
3508 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3510 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3511 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3512 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3515 //================================================================================
3517 * \brief Store a source sub-shape for which a counterpart not found and
3518 * a smesh object invalid due to that
3520 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3521 SALOMEDS::SObject_wrap smeshSO )
3523 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3524 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3526 CORBA::String_var smeshEntry = smeshSO->GetID();
3527 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3531 //================================================================================
3533 * \brief Store a source sub-shape for which a counterpart not found and
3534 * a smesh object invalid due to that
3536 void AddInvalid( std::string geomEntry,
3537 SALOMEDS::SObject_wrap smeshSO )
3539 if ( !geomEntry.empty() )
3541 CORBA::String_var smeshEntry = smeshSO->GetID();
3542 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3546 //================================================================================
3548 * \brief Store a source sub-shape for which a counterpart not found and
3549 * a smesh object invalid due to that
3551 void AddInvalid( int oldGeomID,
3552 SALOMEDS::SObject_wrap smeshSO )
3554 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3555 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3558 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3559 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3561 SMESH_Comment geomName( typeName[ shapeType ]);
3562 geomName << " #" << oldGeomID;
3564 CORBA::String_var smeshEntry = smeshSO->GetID();
3565 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3568 //================================================================================
3570 * \brief Return entries of a source sub-shape for which a counterpart not found and
3571 * of smesh objects invalid due to that
3573 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3574 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3577 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3578 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3580 nbSO += 1 + entry2entrySet->second.size();
3582 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3583 theInvalidEntries->length ( nbSO );
3584 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3586 entry2entrySet = myInvalidMap.begin();
3587 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3589 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3591 std::set< std::string > & entrySet = entry2entrySet->second;
3592 std::set< std::string >::iterator entry = entrySet.begin();
3593 for ( ; entry != entrySet.end(); ++entry )
3595 theInvalidEntries[ iEntry++ ] = entry->c_str();
3597 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3598 if ( !so->_is_nil() )
3599 theInvalidMeshSObjects[ iSO++ ] = so;
3604 }; // struct ShapeMapper
3606 //================================================================================
3608 * \brief Append an item to a CORBA sequence
3610 template < class CORBA_seq, class ITEM >
3611 void append( CORBA_seq& seq, ITEM item )
3613 if ( !CORBA::is_nil( item ))
3615 seq->length( 1 + seq->length() );
3616 seq[ seq->length() - 1 ] = item;
3619 } // namespace // utils for CopyMeshWithGeom()
3621 //================================================================================
3623 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3624 * \param [in] sourceMesh - a mesh to copy
3625 * \param [in] newGeometry - a new geometry
3626 * \param [in] toCopyGroups - to create groups in the new mesh
3627 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3628 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3629 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3630 * \param [out] newMesh - return a new mesh
3631 * \param [out] newGroups - return new groups
3632 * \param [out] newSubmeshes - return new sub-meshes
3633 * \param [out] newHypotheses - return new algorithms and hypotheses
3634 * \param [out] invalidEntries - return study entries of objects whose
3635 * counterparts are not found in the newGeometry, followed by entries
3636 * of mesh sub-objects that are invalid because they depend on a not found
3637 * preceding sub-shape
3638 * \return CORBA::Boolean - is a success
3640 //================================================================================
3642 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3643 GEOM::GEOM_Object_ptr theNewGeometry,
3644 const char* theMeshName,
3645 CORBA::Boolean theToCopyGroups,
3646 CORBA::Boolean theToReuseHypotheses,
3647 CORBA::Boolean theToCopyElements,
3648 SMESH::SMESH_Mesh_out theNewMesh,
3649 SMESH::ListOfGroups_out theNewGroups,
3650 SMESH::submesh_array_out theNewSubmeshes,
3651 SMESH::ListOfHypothesis_out theNewHypotheses,
3652 SMESH::string_array_out theInvalidEntries)
3654 if ( CORBA::is_nil( theSourceMesh ) ||
3655 CORBA::is_nil( theNewGeometry ))
3656 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3658 if ( !theSourceMesh->HasShapeToMesh() )
3659 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3664 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3666 theNewMesh = CreateMesh( theNewGeometry );
3667 theNewGroups = new SMESH::ListOfGroups();
3668 theNewSubmeshes = new SMESH::submesh_array();
3669 theNewHypotheses = new SMESH::ListOfHypothesis();
3670 theInvalidEntries = new SMESH::string_array();
3672 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3674 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3675 GEOM::GEOM_Object_var geom, newGeom;
3676 SALOMEDS::SObject_wrap so;
3678 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3679 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3682 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3684 // treat hypotheses of mesh and sub-meshes
3685 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3686 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3688 bool isSubMesh = ( iSM < smList->length() );
3691 // create a new sub-mesh
3692 SMESH::SMESH_subMesh_var newSM;
3693 geom = smList[iSM]->GetSubShape();
3694 so = ObjectToSObject( smList[iSM] );
3695 CORBA::String_var name;
3696 if ( !so->_is_nil() )
3697 name = so->GetName();
3698 newGeom = shapeMapper.FindNew( geom );
3699 if ( newGeom->_is_nil() )
3701 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3702 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3707 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3709 append( theNewSubmeshes, newSM );
3711 if ( newGeom->_is_nil() )
3712 continue; // don't assign hypotheses
3716 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3718 so = ObjectToSObject( theNewMesh );
3719 SetName( so, theMeshName, "Mesh" );
3722 // assign hypotheses
3723 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3724 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3726 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3727 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3729 // get geometry hyp depends on
3730 std::vector< std::string > entryArray;
3731 std::vector< int > subIDArray;
3732 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3734 if ( !theToReuseHypotheses || dependsOnGeom )
3736 // create a new hypothesis
3737 CORBA::String_var type = hyp->GetName();
3738 CORBA::String_var lib = hyp->GetLibName();
3739 CORBA::String_var data = hyp_i->SaveTo();
3742 hyp = CreateHypothesis( type, lib );
3743 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3744 hyp_i->LoadFrom( data.in() );
3745 append( theNewHypotheses, hyp );
3749 // update geometry hyp depends on
3750 if ( dependsOnGeom )
3752 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3754 if ( !entryArray[ iGeo ].empty() )
3756 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3757 if ( newEntry.empty() )
3760 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3761 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3763 entryArray[ iGeo ] = newEntry;
3766 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3768 if ( subIDArray[ iGeo ] > 0 )
3770 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3774 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3775 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3777 subIDArray[ iGeo ] = newID;
3780 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3784 CORBA::String_var errorText;
3785 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3786 if ( errorText.in()[0] )
3789 } // loop on hypotheses
3790 } // loop on sub-meshes and mesh
3793 // copy mesh elements, keeping IDs
3794 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3795 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3797 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3798 ::SMESH_MeshEditor::ElemFeatures elemData;
3800 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3801 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3802 /*vertexLast=*/false);
3803 while ( srcSMIt->more() )
3805 SMESH_subMesh* srcSM = srcSMIt->next();
3806 if ( srcSM->IsEmpty() )
3807 continue; // not yet computed
3808 int newID = shapeMapper.FindNewNotChanged( srcSM );
3812 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3813 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3814 while ( nIt->more() )
3816 SMESH_NodeXYZ node( nIt->next() );
3817 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3819 const SMDS_PositionPtr pos = node->GetPosition();
3820 const double* uv = pos->GetParameters();
3821 switch ( pos->GetTypeOfPosition() )
3823 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3824 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3825 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3826 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3830 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3831 while( eIt->more() )
3833 const SMDS_MeshElement* e = eIt->next();
3834 elemData.Init( e, /*basicOnly=*/false );
3835 elemData.SetID( e->GetID() );
3836 elemData.myNodes.resize( e->NbNodes() );
3837 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3839 for ( iN = 0; nnIt->more(); ++iN )
3841 const SMDS_MeshNode* srcNode = nnIt->next();
3842 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3843 if ( !elemData.myNodes[ iN ])
3846 if ( iN == elemData.myNodes.size() )
3847 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3848 newMeshDS->SetMeshElementOnShape( newElem, newID );
3850 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3851 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3854 newMeshDS->Modified();
3860 TStr2StrMap old2newGroupMap;
3862 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3864 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3865 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3866 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3868 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3869 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3870 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3872 CORBA::String_var name = groups[ i ]->GetName();
3873 SMESH::ElementType elemType = groups[ i ]->GetType();
3875 SMESH::SMESH_GroupBase_var newGroup;
3877 if ( !stdlGroup->_is_nil() )
3879 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3881 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3882 const bool isElem = ( elemType != SMESH::NODE );
3883 CORBA::ULong iE = 0;
3884 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3885 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3887 if ( iE < elemIDs->length() )
3889 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3890 stdlGroup->Add( elemIDs );
3891 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3895 else if ( !geomGroup->_is_nil() )
3897 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3898 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3899 if ( newGeom->_is_nil() )
3901 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3902 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3907 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3910 else if ( !fltrGroup->_is_nil() )
3912 // replace geometry in a filter
3913 SMESH::Filter_var filter = fltrGroup->GetFilter();
3914 SMESH::Filter::Criteria_var criteria;
3915 filter->GetCriteria( criteria.out() );
3917 bool isMissingGroup = false;
3918 std::vector< std::string > badEntries;
3920 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3922 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3923 switch ( criteria[ iCr ].Type )
3925 case SMESH::FT_BelongToMeshGroup:
3927 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3928 btgg->SetGroupID( thresholdID );
3929 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3930 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3931 if ( refGroupSO->_is_nil() )
3933 CORBA::String_var refID = refGroupSO->GetID();
3934 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3935 if ( o2nID == old2newGroupMap.end() )
3937 isMissingGroup = true; // corresponding new group not yet created
3940 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3942 if ( o2nID->second.empty() ) // new referred group is invalid
3943 badEntries.push_back( refID.in() );
3946 case SMESH::FT_BelongToGeom:
3947 case SMESH::FT_BelongToPlane:
3948 case SMESH::FT_BelongToCylinder:
3949 case SMESH::FT_BelongToGenSurface:
3950 case SMESH::FT_LyingOnGeom:
3952 std::string newID = shapeMapper.FindNew( thresholdID );
3953 criteria[ iCr ].ThresholdID = newID.c_str();
3954 if ( newID.empty() )
3955 badEntries.push_back( thresholdID );
3958 case SMESH::FT_ConnectedElements:
3960 if ( thresholdID && thresholdID[0] )
3962 std::string newID = shapeMapper.FindNew( thresholdID );
3963 criteria[ iCr ].ThresholdID = newID.c_str();
3964 if ( newID.empty() )
3965 badEntries.push_back( thresholdID );
3971 } // loop on criteria
3973 if ( isMissingGroup && i < nbGroups )
3975 // to treat the group again
3976 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3980 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3981 newFilter->SetCriteria( criteria );
3983 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3984 newFilter->UnRegister();
3986 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3987 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3988 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3990 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3992 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3995 if ( !badEntries.empty() )
3998 } // treat a group on filter
4000 append( theNewGroups, newGroup );
4002 // fill old2newGroupMap
4003 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4004 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4005 if ( !srcSO->_is_nil() )
4007 CORBA::String_var srcID, newID("");
4008 srcID = srcSO->GetID();
4009 if ( !newSO->_is_nil() )
4010 newID = newSO->GetID();
4011 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4012 std::string( newID.in() )));
4015 if ( newGroup->_is_nil() )
4020 newMeshDS->CompactMesh();
4023 if ( !theMeshName || !theMeshName[0] )
4025 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4026 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4027 CORBA::String_var oldName = soOld->GetName();
4028 SetName( soNew, oldName.in(), "Mesh" );
4030 // mark invalid objects
4031 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4033 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4034 highLightInvalid( invalidSObjects[i].in(), true );
4037 << theNewMesh << ", "
4038 << theNewGroups << ", "
4039 << *theNewSubmeshes.ptr() << ", "
4040 << *theNewHypotheses.ptr() << ", "
4041 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4042 << theSourceMesh << ", "
4043 << theNewGeometry << ", "
4044 << "'" << theMeshName << "', "
4045 << theToCopyGroups << ", "
4046 << theToReuseHypotheses << ", "
4047 << theToCopyElements << " )";
4049 SMESH_CATCH( SMESH::throwCorbaException );
4054 //================================================================================
4056 * \brief Get version of MED format being used.
4058 //================================================================================
4060 char* SMESH_Gen_i::GetMEDFileVersion()
4062 MED::TInt majeur, mineur, release;
4063 majeur = mineur = release = 0;
4064 MED::GetVersionRelease(majeur, mineur, release);
4065 std::ostringstream version;
4066 version << majeur << "." << mineur << "." << release;
4067 return CORBA::string_dup( version.str().c_str() );
4070 //================================================================================
4072 * SMESH_Gen_i::GetMEDVersion
4074 * Get MED version of the file by its name
4076 //================================================================================
4078 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4080 std::string version = MED::GetMEDVersion( theFileName );
4081 return CORBA::string_dup( version.c_str() );
4084 //================================================================================
4086 * SMESH_Gen_i::CheckCompatibility
4088 * Check compatibility of file with MED format being used, read only.
4090 //================================================================================
4092 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4094 return MED::CheckCompatibility( theFileName );
4097 //================================================================================
4099 * SMESH_Gen_i::CheckWriteCompatibility
4101 * Check compatibility of file with MED format being used, for append on write.
4103 //================================================================================
4105 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4107 return MED::CheckCompatibility( theFileName, true );
4110 //================================================================================
4112 * SMESH_Gen_i::GetMeshNames
4114 * Get names of meshes defined in file with the specified name
4116 //================================================================================
4117 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4120 SMESH::string_array_var aResult = new SMESH::string_array();
4121 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4123 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4125 aResult->length( aNbMeshes );
4126 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4127 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4128 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4131 return aResult._retn();
4134 //=============================================================================
4138 * Save SMESH module's data
4140 //=============================================================================
4142 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4147 Kernel_Utils::Localizer loc;
4149 if (!myStudyContext)
4152 // Store study contents as a set of python commands
4155 SALOMEDS::Study_var aStudy = getStudyServant();
4157 // Declare a byte stream
4158 SALOMEDS::TMPFile_var aStreamFile;
4160 // Obtain a temporary dir
4161 TCollection_AsciiString tmpDir =
4162 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4164 // Create a sequence of files processed
4165 SALOMEDS_Tool::ListOfFiles aFileSeq;
4166 aFileSeq.reserve( NUM_TMP_FILES );
4168 TCollection_AsciiString aStudyName( "" );
4170 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4172 // Set names of temporary files
4173 TCollection_AsciiString filename =
4174 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4175 TCollection_AsciiString meshfile =
4176 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4177 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4178 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4179 filename = tmpDir + filename;
4180 meshfile = tmpDir + meshfile;
4183 HDFdataset* aDataset;
4184 HDFgroup* aTopGroup;
4186 HDFgroup* aSubGroup;
4187 HDFgroup* aSubSubGroup;
4188 hdf_size aSize[ 1 ];
4191 //Remove the files if they exist: BugID: 11225
4192 #ifndef WIN32 /* unix functionality */
4193 TCollection_AsciiString cmd("rm -f \"");
4195 TCollection_AsciiString cmd("del /F \"");
4205 system(cmd.ToCString());
4207 // MED writer to be used by storage process
4208 DriverMED_W_SMESHDS_Mesh writer;
4209 writer.SetFile( meshfile.ToCString() );
4210 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4213 // SetStoreName() to groups before storing hypotheses to let them refer to
4214 // groups using "store name", which is "Group <group_persistent_id>"
4216 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4217 for ( ; itBig->More(); itBig->Next() ) {
4218 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4219 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4220 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4221 if ( !CORBA::is_nil( anObject ) ) {
4222 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4223 if ( !myMesh->_is_nil() ) {
4224 myMesh->Load(); // load from study file if not yet done
4225 TPythonDump pd(this); // not to dump GetGroups()
4226 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4227 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4229 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4232 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4233 int anId = myStudyContext->findId( string( objStr.in() ) );
4235 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4236 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4237 aGrpBaseDS->SetStoreName( grpName );
4247 // ---> create HDF file
4248 aFile = new HDFfile( (char*) filename.ToCString() );
4249 aFile->CreateOnDisk();
4251 // --> iterator for top-level objects
4252 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4253 for ( ; itBig->More(); itBig->Next() ) {
4254 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4256 // --> hypotheses root branch (only one for the study)
4257 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4258 // create hypotheses root HDF group
4259 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4260 aTopGroup->CreateOnDisk();
4262 // iterator for all hypotheses
4263 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4264 for ( ; it->More(); it->Next() ) {
4265 SALOMEDS::SObject_wrap mySObject = it->Value();
4266 CORBA::Object_var anObject = SObjectToObject( mySObject );
4267 if ( !CORBA::is_nil( anObject ) ) {
4268 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4269 if ( !myHyp->_is_nil() ) {
4270 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4272 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4273 std::string hypname = hn.in();
4274 std::string libname = ln.in();
4276 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4277 // WIN32 and ".so" for X-system) must be deleted
4278 int libname_len = libname.length();
4280 if( libname_len > 4 )
4281 libname.resize( libname_len - 4 );
4283 // PAL17753 (Regression: missing hypothesis in restored study)
4284 // "lib" also should be removed from the beginning
4285 if( libname_len > 6 )
4286 libname = libname.substr( 3, libname_len - 3 - 3 );
4288 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4289 CORBA::String_var hypdata = myImpl->SaveTo();
4290 int id = myStudyContext->findId( string( objStr.in() ));
4292 // for each hypothesis create HDF group basing on its id
4293 char hypGrpName[30];
4294 sprintf( hypGrpName, "Hypothesis %d", id );
4295 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4296 aGroup->CreateOnDisk();
4297 // --> type name of hypothesis
4298 aSize[ 0 ] = hypname.length() + 1;
4299 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4300 aDataset->CreateOnDisk();
4301 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4302 aDataset->CloseOnDisk();
4303 // --> server plugin library name of hypothesis
4304 aSize[ 0 ] = libname.length() + 1;
4305 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4306 aDataset->CreateOnDisk();
4307 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4308 aDataset->CloseOnDisk();
4309 // --> persistent data of hypothesis
4310 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4311 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4312 aDataset->CreateOnDisk();
4313 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4314 aDataset->CloseOnDisk();
4315 // close hypothesis HDF group
4316 aGroup->CloseOnDisk();
4321 // close hypotheses root HDF group
4322 aTopGroup->CloseOnDisk();
4324 // --> algorithms root branch (only one for the study)
4325 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4326 // create algorithms root HDF group
4327 aTopGroup = new HDFgroup( "Algorithms", aFile );
4328 aTopGroup->CreateOnDisk();
4330 // iterator for all algorithms
4331 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4332 for ( ; it->More(); it->Next() ) {
4333 SALOMEDS::SObject_wrap mySObject = it->Value();
4334 CORBA::Object_var anObject = SObjectToObject( mySObject );
4335 if ( !CORBA::is_nil( anObject ) ) {
4336 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4337 if ( !myHyp->_is_nil() ) {
4338 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4340 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4341 std::string hypname = hn.in();
4342 std::string libname = ln.in();
4344 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4345 // WIN32 and ".so" for X-system) must be deleted
4346 int libname_len = libname.length();
4348 if( libname_len > 4 )
4349 libname.resize( libname_len - 4 );
4351 // PAL17753 (Regression: missing hypothesis in restored study)
4352 // "lib" also should be removed from the beginning
4353 if( libname_len > 6 )
4354 libname = libname.substr( 3, libname_len - 3 - 3 );
4356 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4357 CORBA::String_var hypdata = myImpl->SaveTo();
4358 int id = myStudyContext->findId( string( objStr.in() ) );
4360 // for each algorithm create HDF group basing on its id
4361 char hypGrpName[30];
4362 sprintf( hypGrpName, "Algorithm %d", id );
4363 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4364 aGroup->CreateOnDisk();
4365 // --> type name of algorithm
4366 aSize[0] = hypname.length() + 1;
4367 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4368 aDataset->CreateOnDisk();
4369 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4370 aDataset->CloseOnDisk();
4371 // --> server plugin library name of hypothesis
4372 aSize[0] = libname.length() + 1;
4373 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4374 aDataset->CreateOnDisk();
4375 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4376 aDataset->CloseOnDisk();
4377 // --> persistent data of algorithm
4378 aSize[0] = strlen( hypdata.in() ) + 1;
4379 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4380 aDataset->CreateOnDisk();
4381 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4382 aDataset->CloseOnDisk();
4383 // close algorithm HDF group
4384 aGroup->CloseOnDisk();
4389 // close algorithms root HDF group
4390 aTopGroup->CloseOnDisk();
4392 // --> mesh objects roots branches
4393 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4394 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4395 if ( !CORBA::is_nil( anObject ) ) {
4396 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4397 if ( !myMesh->_is_nil() ) {
4398 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4400 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4401 int id = myStudyContext->findId( string( objStr.in() ) );
4402 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4403 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4404 bool hasShape = myLocMesh.HasShapeToMesh();
4406 // for each mesh open the HDF group basing on its id
4407 char meshGrpName[ 30 ];
4408 sprintf( meshGrpName, "Mesh %d", id );
4409 aTopGroup = new HDFgroup( meshGrpName, aFile );
4410 aTopGroup->CreateOnDisk();
4412 // --> put dataset to hdf file which is a flag that mesh has data
4413 string strHasData = "0";
4414 // check if the mesh is not empty
4415 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4416 // write mesh data to med file
4417 writer.SetMesh( mySMESHDSMesh );
4418 writer.SetMeshId( id );
4421 aSize[ 0 ] = strHasData.length() + 1;
4422 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4423 aDataset->CreateOnDisk();
4424 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4425 aDataset->CloseOnDisk();
4428 // for each mesh open the HDF group basing on its auto color parameter
4429 char meshAutoColorName[ 30 ];
4430 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4432 anAutoColor[0] = myImpl->GetAutoColor();
4434 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4435 aDataset->CreateOnDisk();
4436 aDataset->WriteOnDisk( anAutoColor );
4437 aDataset->CloseOnDisk();
4439 // issue 0020693. Store _isModified flag
4440 int isModified = myLocMesh.GetIsModified();
4442 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4443 aDataset->CreateOnDisk();
4444 aDataset->WriteOnDisk( &isModified );
4445 aDataset->CloseOnDisk();
4447 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4448 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4450 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4451 aDataset->CreateOnDisk();
4452 aDataset->WriteOnDisk( &meshPersistentId );
4453 aDataset->CloseOnDisk();
4455 // Store SMESH_Mesh_i::_mainShapeTick
4456 int shapeTick = myImpl->MainShapeTick();
4458 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4459 aDataset->CreateOnDisk();
4460 aDataset->WriteOnDisk( &shapeTick );
4461 aDataset->CloseOnDisk();
4463 // write reference on a shape if exists
4464 SALOMEDS::SObject_wrap myRef;
4465 bool shapeRefFound = false;
4466 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4468 SALOMEDS::SObject_wrap myShape;
4469 bool ok = myRef->ReferencedObject( myShape.inout() );
4471 CORBA::Object_var shapeObj = myShape->GetObject();
4472 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4473 CORBA::String_var myRefOnObject = myShape->GetID();
4474 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4475 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4476 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4477 aDataset->CreateOnDisk();
4478 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4479 aDataset->CloseOnDisk();
4485 std::string info = myImpl->FileInfoToString();
4486 if ( !info.empty() )
4488 aSize[ 0 ] = info.size();
4489 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4490 aDataset->CreateOnDisk();
4491 aDataset->WriteOnDisk( (char*) info.data() );
4492 aDataset->CloseOnDisk();
4495 // write applied hypotheses if exist
4496 SALOMEDS::SObject_wrap myHypBranch;
4497 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4498 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4499 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4501 if ( found && (shapeRefFound || !hasShape) ) {
4502 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4503 aGroup->CreateOnDisk();
4505 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4507 for ( ; it->More(); it->Next() ) {
4508 SALOMEDS::SObject_wrap mySObject = it->Value();
4509 SALOMEDS::SObject_wrap myRefOnHyp;
4510 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4512 // san - it is impossible to recover applied hypotheses
4513 // using their entries within Load() method,
4514 // for there are no AttributeIORs in the study when Load() is working.
4515 // Hence, it is better to store persistent IDs of hypotheses as references to them
4517 //string myRefOnObject = myRefOnHyp->GetID();
4518 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4519 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4520 int id = myStudyContext->findId( string( objStr.in() ) );
4521 //if ( myRefOnObject.length() > 0 ) {
4522 //aSize[ 0 ] = myRefOnObject.length() + 1;
4523 char hypName[ 30 ], hypId[ 30 ];
4524 sprintf( hypName, "Hyp %d", ++hypNb );
4525 sprintf( hypId, "%d", id );
4526 aSize[ 0 ] = strlen( hypId ) + 1;
4527 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4528 aDataset->CreateOnDisk();
4529 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4530 aDataset->WriteOnDisk( hypId );
4531 aDataset->CloseOnDisk();
4535 aGroup->CloseOnDisk();
4538 // write applied algorithms if exist
4539 SALOMEDS::SObject_wrap myAlgoBranch;
4540 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4541 myAlgoBranch.inout() );
4542 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4543 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4545 if ( found && (shapeRefFound || !hasShape)) {
4546 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4547 aGroup->CreateOnDisk();
4549 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4551 for ( ; it->More(); it->Next() ) {
4552 SALOMEDS::SObject_wrap mySObject = it->Value();
4553 SALOMEDS::SObject_wrap myRefOnAlgo;
4554 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4556 // san - it is impossible to recover applied algorithms
4557 // using their entries within Load() method,
4558 // for there are no AttributeIORs in the study when Load() is working.
4559 // Hence, it is better to store persistent IDs of algorithms as references to them
4561 //string myRefOnObject = myRefOnAlgo->GetID();
4562 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4563 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4564 int id = myStudyContext->findId( string( objStr.in() ) );
4565 //if ( myRefOnObject.length() > 0 ) {
4566 //aSize[ 0 ] = myRefOnObject.length() + 1;
4567 char algoName[ 30 ], algoId[ 30 ];
4568 sprintf( algoName, "Algo %d", ++algoNb );
4569 sprintf( algoId, "%d", id );
4570 aSize[ 0 ] = strlen( algoId ) + 1;
4571 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4572 aDataset->CreateOnDisk();
4573 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4574 aDataset->WriteOnDisk( algoId );
4575 aDataset->CloseOnDisk();
4579 aGroup->CloseOnDisk();
4582 // --> submesh objects sub-branches
4584 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4585 SALOMEDS::SObject_wrap mySubmeshBranch;
4586 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4588 if ( found ) // check if there is shape reference in submeshes
4590 bool hasShapeRef = false;
4591 SALOMEDS::ChildIterator_wrap itSM =
4592 aStudy->NewChildIterator( mySubmeshBranch );
4593 for ( ; itSM->More(); itSM->Next() ) {
4594 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4595 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4596 mySubRef->ReferencedObject( myShape.inout() );
4597 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4600 { // remove one submesh
4601 if ( shapeRefFound )
4602 { // unassign hypothesis
4603 SMESH::SMESH_subMesh_var mySubMesh =
4604 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4605 if ( !mySubMesh->_is_nil() ) {
4606 int shapeID = mySubMesh->GetId();
4607 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4608 const list<const SMESHDS_Hypothesis*>& hypList =
4609 mySMESHDSMesh->GetHypothesis( S );
4610 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4611 while ( hyp != hypList.end() ) {
4612 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4613 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4617 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4619 } // loop on submeshes of a type
4620 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4621 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4624 } // end check if there is shape reference in submeshes
4626 char name_meshgroup[ 30 ];
4627 if ( i == GetSubMeshOnVertexTag() )
4628 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4629 else if ( i == GetSubMeshOnEdgeTag() )
4630 strcpy( name_meshgroup, "SubMeshes On Edge" );
4631 else if ( i == GetSubMeshOnWireTag() )
4632 strcpy( name_meshgroup, "SubMeshes On Wire" );
4633 else if ( i == GetSubMeshOnFaceTag() )
4634 strcpy( name_meshgroup, "SubMeshes On Face" );
4635 else if ( i == GetSubMeshOnShellTag() )
4636 strcpy( name_meshgroup, "SubMeshes On Shell" );
4637 else if ( i == GetSubMeshOnSolidTag() )
4638 strcpy( name_meshgroup, "SubMeshes On Solid" );
4639 else if ( i == GetSubMeshOnCompoundTag() )
4640 strcpy( name_meshgroup, "SubMeshes On Compound" );
4642 // for each type of submeshes create container HDF group
4643 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4644 aGroup->CreateOnDisk();
4646 // iterator for all submeshes of given type
4647 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4648 for ( ; itSM->More(); itSM->Next() ) {
4649 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4650 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4651 if ( !CORBA::is_nil( anSubObject ))
4653 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4654 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4655 int subid = myStudyContext->findId( string( objStr.in() ) );
4657 // for each mesh open the HDF group basing on its id
4658 char submeshGrpName[ 30 ];
4659 sprintf( submeshGrpName, "SubMesh %d", subid );
4660 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4661 aSubGroup->CreateOnDisk();
4663 // write reference on a shape, already checked if it exists
4664 SALOMEDS::SObject_wrap mySubRef, myShape;
4665 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4666 mySubRef->ReferencedObject( myShape.inout() );
4667 string myRefOnObject = myShape->GetID();
4668 if ( myRefOnObject.length() > 0 ) {
4669 aSize[ 0 ] = myRefOnObject.length() + 1;
4670 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4671 aDataset->CreateOnDisk();
4672 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4673 aDataset->CloseOnDisk();
4676 // write applied hypotheses if exist
4677 SALOMEDS::SObject_wrap mySubHypBranch;
4678 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4679 mySubHypBranch.inout() );
4681 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4682 aSubSubGroup->CreateOnDisk();
4684 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4686 for ( ; it->More(); it->Next() ) {
4687 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4688 SALOMEDS::SObject_wrap myRefOnHyp;
4689 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4691 //string myRefOnObject = myRefOnHyp->GetID();
4692 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4693 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4694 int id = myStudyContext->findId( string( objStr.in() ) );
4695 //if ( myRefOnObject.length() > 0 ) {
4696 //aSize[ 0 ] = myRefOnObject.length() + 1;
4697 char hypName[ 30 ], hypId[ 30 ];
4698 sprintf( hypName, "Hyp %d", ++hypNb );
4699 sprintf( hypId, "%d", id );
4700 aSize[ 0 ] = strlen( hypId ) + 1;
4701 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4702 aDataset->CreateOnDisk();
4703 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4704 aDataset->WriteOnDisk( hypId );
4705 aDataset->CloseOnDisk();
4709 aSubSubGroup->CloseOnDisk();
4712 // write applied algorithms if exist
4713 SALOMEDS::SObject_wrap mySubAlgoBranch;
4714 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4715 mySubAlgoBranch.inout() );
4717 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4718 aSubSubGroup->CreateOnDisk();
4720 SALOMEDS::ChildIterator_wrap it =
4721 aStudy->NewChildIterator( mySubAlgoBranch );
4723 for ( ; it->More(); it->Next() ) {
4724 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4725 SALOMEDS::SObject_wrap myRefOnAlgo;
4726 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4728 //string myRefOnObject = myRefOnAlgo->GetID();
4729 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4730 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4731 int id = myStudyContext->findId( string( objStr.in() ) );
4732 //if ( myRefOnObject.length() > 0 ) {
4733 //aSize[ 0 ] = myRefOnObject.length() + 1;
4734 char algoName[ 30 ], algoId[ 30 ];
4735 sprintf( algoName, "Algo %d", ++algoNb );
4736 sprintf( algoId, "%d", id );
4737 aSize[ 0 ] = strlen( algoId ) + 1;
4738 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4739 aDataset->CreateOnDisk();
4740 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4741 aDataset->WriteOnDisk( algoId );
4742 aDataset->CloseOnDisk();
4746 aSubSubGroup->CloseOnDisk();
4748 // close submesh HDF group
4749 aSubGroup->CloseOnDisk();
4752 // close container of submeshes by type HDF group
4753 aGroup->CloseOnDisk();
4757 // store submesh order if any
4758 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4759 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4760 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4761 char order_list[ 30 ];
4762 strcpy( order_list, "Mesh Order" );
4763 // count number of submesh ids
4765 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4766 for ( ; idIt != theOrderIds.end(); idIt++ )
4767 nbIDs += (*idIt).size();
4768 // number of values = number of IDs +
4769 // number of lists (for separators) - 1
4770 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4771 idIt = theOrderIds.begin();
4772 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4773 const TListOfInt& idList = *idIt;
4774 if (idIt != theOrderIds.begin()) // not first list
4775 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4776 // dump submesh ids from current list
4777 TListOfInt::const_iterator id_smId = idList.begin();
4778 for( ; id_smId != idList.end(); id_smId++ )
4779 smIDs[ i++ ] = *id_smId;
4782 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4784 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4785 aDataset->CreateOnDisk();
4786 aDataset->WriteOnDisk( smIDs );
4787 aDataset->CloseOnDisk();
4791 if ( !theOrderIds.empty() && isNewOrederVersion )
4793 // convert ids to entries
4794 std::list< std::list< std::string > > orderEntryLists;
4795 for ( const TListOfInt& idList : theOrderIds )
4797 orderEntryLists.emplace_back();
4798 std::list< std::string > & entryList = orderEntryLists.back();
4799 for ( const int& id : idList )
4801 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4802 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4803 SALOMEDS::SObject_var so = ObjectToSObject( go );
4804 if ( !so->_is_nil() )
4806 CORBA::String_var entry = so->GetID();
4807 entryList.emplace_back( entry.in() );
4811 // convert orderEntryLists to string
4812 std::ostringstream ostream;
4813 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4814 std::string orderEntryString = ostream.str();
4817 aSize[ 0 ] = orderEntryString.size() + 1;
4818 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4819 aDataset->CreateOnDisk();
4820 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4821 aDataset->CloseOnDisk();
4824 // groups root sub-branch
4825 SALOMEDS::SObject_wrap myGroupsBranch;
4826 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4827 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4829 char name_group[ 30 ];
4830 if ( i == GetNodeGroupsTag() )
4831 strcpy( name_group, "Groups of Nodes" );
4832 else if ( i == GetEdgeGroupsTag() )
4833 strcpy( name_group, "Groups of Edges" );
4834 else if ( i == GetFaceGroupsTag() )
4835 strcpy( name_group, "Groups of Faces" );
4836 else if ( i == GetVolumeGroupsTag() )
4837 strcpy( name_group, "Groups of Volumes" );
4838 else if ( i == Get0DElementsGroupsTag() )
4839 strcpy( name_group, "Groups of 0D Elements" );
4840 else if ( i == GetBallElementsGroupsTag() )
4841 strcpy( name_group, "Groups of Balls" );
4843 aGroup = new HDFgroup( name_group, aTopGroup );
4844 aGroup->CreateOnDisk();
4846 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4847 for ( ; it->More(); it->Next() ) {
4848 SALOMEDS::SObject_wrap mySObject = it->Value();
4849 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4850 if ( !CORBA::is_nil( aSubObject ) ) {
4851 SMESH_GroupBase_i* myGroupImpl =
4852 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4855 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4859 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4860 int anId = myStudyContext->findId( string( objStr.in() ) );
4862 // For each group, create a dataset named "Group <group_persistent_id>"
4863 // and store the group's user name into it
4864 const char* grpName = aGrpBaseDS->GetStoreName();
4865 CORBA::String_var aUserName = myGroupImpl->GetName();
4866 aSize[ 0 ] = strlen( aUserName ) + 1;
4868 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4869 aDataset->CreateOnDisk();
4870 aDataset->WriteOnDisk( aUserName );
4871 aDataset->CloseOnDisk();
4874 // For each group, create a dataset named "Group <group_persistent_id> Color"
4875 // and store the group's color into it
4876 char grpColorName[ 30 ];
4877 sprintf( grpColorName, "ColorGroup %d", anId );
4878 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4880 anRGB[ 0 ] = aColor.R;
4881 anRGB[ 1 ] = aColor.G;
4882 anRGB[ 2 ] = aColor.B;
4884 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4885 aDataset->CreateOnDisk();
4886 aDataset->WriteOnDisk( anRGB );
4887 aDataset->CloseOnDisk();
4889 // Pass SMESHDS_Group to MED writer
4890 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4892 writer.AddGroup( aGrpDS );
4894 // write reference on a shape if exists
4895 SMESHDS_GroupOnGeom* aGeomGrp =
4896 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4898 SALOMEDS::SObject_wrap mySubRef, myShape;
4899 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4900 mySubRef->ReferencedObject( myShape.inout() ) &&
4901 !CORBA::is_nil( myShape->GetObject() ))
4903 CORBA::String_var myRefOnObject = myShape->GetID();
4904 if ( myRefOnObject.in()[0] ) {
4905 char aRefName[ 30 ];
4906 sprintf( aRefName, "Ref on shape %d", anId);
4907 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4908 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4909 aDataset->CreateOnDisk();
4910 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4911 aDataset->CloseOnDisk();
4914 else // shape ref is invalid:
4916 // save a group on geometry as ordinary group
4917 writer.AddGroup( aGeomGrp );
4920 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4921 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4923 std::string str = aFilterGrp_i->FilterToString();
4924 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4925 aSize[ 0 ] = str.length() + 1;
4926 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4927 aDataset->CreateOnDisk();
4928 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4929 aDataset->CloseOnDisk();
4933 aGroup->CloseOnDisk();
4937 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4939 // Flush current mesh information into MED file
4942 // save info on nb of elements
4943 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4945 // maybe a shape was deleted in the study
4946 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4947 TopoDS_Shape nullShape;
4948 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4951 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4956 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4957 aGroup->CreateOnDisk();
4959 // each element belongs to one or none submesh,
4960 // so for each node/element, we store a submesh ID
4962 // Store submesh IDs
4963 for ( int isNode = 0; isNode < 2; ++isNode )
4965 SMDS_ElemIteratorPtr eIt =
4966 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4967 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4970 std::vector<int> smIDs; smIDs.reserve( nbElems );
4971 while ( eIt->more() )
4972 if ( const SMDS_MeshElement* e = eIt->next())
4973 smIDs.push_back( e->getshapeId() );
4975 aSize[ 0 ] = nbElems;
4976 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4977 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4978 aDataset->CreateOnDisk();
4979 aDataset->WriteOnDisk( & smIDs[0] );
4980 aDataset->CloseOnDisk();
4983 aGroup->CloseOnDisk();
4985 // Store node positions on sub-shapes (SMDS_Position):
4986 // ----------------------------------------------------
4988 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4989 aGroup->CreateOnDisk();
4991 // in aGroup, create 5 datasets to contain:
4992 // "Nodes on Edges" - ID of node on edge
4993 // "Edge positions" - U parameter on node on edge
4994 // "Nodes on Faces" - ID of node on face
4995 // "Face U positions" - U parameter of node on face
4996 // "Face V positions" - V parameter of node on face
4998 // Find out nb of nodes on edges and faces
4999 // Collect corresponding sub-meshes
5000 int nbEdgeNodes = 0, nbFaceNodes = 0;
5001 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5002 // loop on SMESHDS_SubMesh'es
5003 while ( smIt->more() )
5005 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5006 if ( aSubMesh->IsComplexSubmesh() )
5007 continue; // submesh containing other submeshs
5008 smIdType nbNodes = aSubMesh->NbNodes();
5009 if ( nbNodes == 0 ) continue;
5011 int aShapeID = aSubMesh->GetID();
5012 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5014 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5015 // write only SMDS_FacePosition and SMDS_EdgePosition
5016 switch ( aShapeType ) {
5018 nbFaceNodes += nbNodes;
5019 aFaceSM.push_back( aSubMesh );
5022 nbEdgeNodes += nbNodes;
5023 aEdgeSM.push_back( aSubMesh );
5029 // Treat positions on edges or faces
5030 for ( int onFace = 0; onFace < 2; onFace++ )
5032 // Create arrays to store in datasets
5033 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5034 if (!nbNodes) continue;
5035 int* aNodeIDs = new int [ nbNodes ];
5036 double* aUPos = new double [ nbNodes ];
5037 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5040 // loop on sub-meshes
5041 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5042 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5043 for ( ; itSM != pListSM->end(); itSM++ )
5045 SMESHDS_SubMesh* aSubMesh = (*itSM);
5047 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5048 // loop on nodes in aSubMesh
5049 while ( itNode->more() )
5052 const SMDS_MeshNode* node = itNode->next();
5053 aNodeIDs [ iNode ] = node->GetID();
5056 const SMDS_PositionPtr pos = node->GetPosition();
5057 if ( onFace ) { // on FACE
5058 SMDS_FacePositionPtr fPos = pos;
5060 aUPos[ iNode ] = fPos->GetUParameter();
5061 aVPos[ iNode ] = fPos->GetVParameter();
5068 SMDS_EdgePositionPtr ePos = pos;
5070 aUPos[ iNode ] = ePos->GetUParameter();
5076 } // loop on nodes in aSubMesh
5077 } // loop on sub-meshes
5082 aSize[ 0 ] = nbNodes;
5084 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5085 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5086 aDataset->CreateOnDisk();
5087 aDataset->WriteOnDisk( aNodeIDs );
5088 aDataset->CloseOnDisk();
5091 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5092 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5093 aDataset->CreateOnDisk();
5094 aDataset->WriteOnDisk( aUPos );
5095 aDataset->CloseOnDisk();
5098 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5099 aDataset->CreateOnDisk();
5100 aDataset->WriteOnDisk( aVPos );
5101 aDataset->CloseOnDisk();
5106 if ( aVPos ) delete [] aVPos;
5108 } // treat positions on edges or faces
5110 // close "Node Positions" group
5111 aGroup->CloseOnDisk();
5113 } // if ( there are submeshes in SMESHDS_Mesh )
5116 // close mesh HDF group
5117 aTopGroup->CloseOnDisk();
5125 aFile->CloseOnDisk();
5128 // Convert temporary files to stream
5129 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5131 // Remove temporary files and directory
5133 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5135 return aStreamFile._retn();
5138 //=============================================================================
5140 * SMESH_Gen_i::SaveASCII
5142 * Save SMESH module's data in ASCII format
5144 //=============================================================================
5146 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5148 bool isMultiFile ) {
5149 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5150 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5151 return aStreamFile._retn();
5153 //after usual saving needs to encipher binary to text string
5154 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5155 int size = aStreamFile.in().length();
5156 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5157 for ( int i = 0; i < size; i++ )
5158 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5160 buffer[size * 3] = '\0';
5162 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5164 return anAsciiStreamFile._retn();
5167 //=============================================================================
5171 * Load SMESH module's data
5173 //=============================================================================
5175 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5176 const SALOMEDS::TMPFile& theStream,
5180 UpdateStudy(); // load geom data
5181 Kernel_Utils::Localizer loc;
5183 SALOMEDS::Study_var aStudy = getStudyServant();
5185 // Get temporary files location
5186 TCollection_AsciiString tmpDir =
5187 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5189 // Convert the stream into sequence of files to process
5190 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5193 TCollection_AsciiString aStudyName( "" );
5194 if ( isMultiFile ) {
5195 CORBA::WString_var url = aStudy->URL();
5196 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5197 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5199 // Set names of temporary files
5200 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5201 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5205 HDFdataset* aDataset;
5206 HDFgroup* aTopGroup;
5208 HDFgroup* aSubGroup;
5209 HDFgroup* aSubSubGroup;
5212 // ---> open HDF file
5213 aFile = new HDFfile( (char*) filename.ToCString() );
5215 aFile->OpenOnDisk( HDF_RDONLY );
5217 catch ( HDFexception ) {
5218 INFOS( "Load(): " << filename << " not found!" );
5222 TPythonDump pd(this); // prevent dump during loading
5224 // For PAL13473 ("Repetitive mesh") implementation.
5225 // New dependencies between SMESH objects are established:
5226 // now hypotheses can refer to meshes, shapes and other hypotheses.
5227 // To keep data consistent, the following order of data restoration
5229 // 1. Create hypotheses
5230 // 2. Create all meshes
5231 // 3. Load hypotheses' data
5234 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5235 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5236 list< SMESH::Filter_var > filters;
5238 // get total number of top-level groups
5239 int aNbGroups = aFile->nInternalObjects();
5240 if ( aNbGroups > 0 ) {
5241 // --> in first turn we should read&create hypotheses
5242 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5243 // open hypotheses root HDF group
5244 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5245 aTopGroup->OpenOnDisk();
5247 // get number of hypotheses
5248 int aNbObjects = aTopGroup->nInternalObjects();
5249 for ( int j = 0; j < aNbObjects; j++ ) {
5250 // try to identify hypothesis
5251 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5252 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5254 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5255 // open hypothesis group
5256 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5257 aGroup->OpenOnDisk();
5259 // --> get hypothesis id
5260 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5265 // get number of datasets
5266 int aNbSubObjects = aGroup->nInternalObjects();
5267 for ( int k = 0; k < aNbSubObjects; k++ ) {
5269 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5270 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5271 // --> get hypothesis name
5272 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5273 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5274 aDataset->OpenOnDisk();
5275 size = aDataset->GetSize();
5276 char* hypname_str = new char[ size ];
5277 aDataset->ReadFromDisk( hypname_str );
5278 hypname = string( hypname_str );
5279 delete [] hypname_str;
5280 aDataset->CloseOnDisk();
5282 // --> get hypothesis plugin library name
5283 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5284 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5285 aDataset->OpenOnDisk();
5286 size = aDataset->GetSize();
5287 char* libname_str = new char[ size ];
5288 aDataset->ReadFromDisk( libname_str );
5289 if(MYDEBUG) SCRUTE( libname_str );
5290 libname = string( libname_str );
5291 delete [] libname_str;
5292 aDataset->CloseOnDisk();
5294 // --> get hypothesis data
5295 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5296 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5297 aDataset->OpenOnDisk();
5298 size = aDataset->GetSize();
5299 char* hypdata_str = new char[ size ];
5300 aDataset->ReadFromDisk( hypdata_str );
5301 hypdata = string( hypdata_str );
5302 delete [] hypdata_str;
5303 aDataset->CloseOnDisk();
5306 // close hypothesis HDF group
5307 aGroup->CloseOnDisk();
5309 // --> restore hypothesis from data
5310 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5311 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5312 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5313 SMESH::SMESH_Hypothesis_var myHyp;
5315 try { // protect persistence mechanism against exceptions
5316 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5319 INFOS( "Exception during hypothesis creation" );
5322 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5324 // myImpl->LoadFrom( hypdata.c_str() );
5325 hypDataList.push_back( make_pair( myImpl, hypdata ));
5326 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5327 int newId = myStudyContext->findId( iorString.in() );
5328 myStudyContext->mapOldToNew( id, newId );
5331 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5335 // close hypotheses root HDF group
5336 aTopGroup->CloseOnDisk();
5340 // --> then we should read&create algorithms
5341 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5342 // open algorithms root HDF group
5343 aTopGroup = new HDFgroup( "Algorithms", aFile );
5344 aTopGroup->OpenOnDisk();
5346 // get number of algorithms
5347 int aNbObjects = aTopGroup->nInternalObjects();
5348 for ( int j = 0; j < aNbObjects; j++ ) {
5349 // try to identify algorithm
5350 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5351 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5353 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5354 // open algorithm group
5355 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5356 aGroup->OpenOnDisk();
5358 // --> get algorithm id
5359 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5364 // get number of datasets
5365 int aNbSubObjects = aGroup->nInternalObjects();
5366 for ( int k = 0; k < aNbSubObjects; k++ ) {
5368 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5369 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5370 // --> get algorithm name
5371 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5372 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5373 aDataset->OpenOnDisk();
5374 size = aDataset->GetSize();
5375 char* hypname_str = new char[ size ];
5376 aDataset->ReadFromDisk( hypname_str );
5377 hypname = string( hypname_str );
5378 delete [] hypname_str;
5379 aDataset->CloseOnDisk();
5381 // --> get algorithm plugin library name
5382 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5383 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5384 aDataset->OpenOnDisk();
5385 size = aDataset->GetSize();
5386 char* libname_str = new char[ size ];
5387 aDataset->ReadFromDisk( libname_str );
5388 if(MYDEBUG) SCRUTE( libname_str );
5389 libname = string( libname_str );
5390 delete [] libname_str;
5391 aDataset->CloseOnDisk();
5393 // --> get algorithm data
5394 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5395 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5396 aDataset->OpenOnDisk();
5397 size = aDataset->GetSize();
5398 char* hypdata_str = new char[ size ];
5399 aDataset->ReadFromDisk( hypdata_str );
5400 if(MYDEBUG) SCRUTE( hypdata_str );
5401 hypdata = string( hypdata_str );
5402 delete [] hypdata_str;
5403 aDataset->CloseOnDisk();
5406 // close algorithm HDF group
5407 aGroup->CloseOnDisk();
5409 // --> restore algorithm from data
5410 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5411 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5412 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5413 SMESH::SMESH_Hypothesis_var myHyp;
5415 try { // protect persistence mechanism against exceptions
5416 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5418 catch( SALOME::SALOME_Exception& ex )
5420 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5423 INFOS( "Exception during hypothesis creation" );
5426 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5428 //myImpl->LoadFrom( hypdata.c_str() );
5429 hypDataList.push_back( make_pair( myImpl, hypdata ));
5430 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5431 int newId = myStudyContext->findId( iorString.in() );
5432 myStudyContext->mapOldToNew( id, newId );
5435 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5439 // close algorithms root HDF group
5440 aTopGroup->CloseOnDisk();
5444 // --> the rest groups should be meshes
5445 for ( int i = 0; i < aNbGroups; i++ ) {
5446 // identify next group
5447 char meshName[ HDF_NAME_MAX_LEN+1 ];
5448 aFile->InternalObjectIndentify( i, meshName );
5450 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5452 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5456 // open mesh HDF group
5457 aTopGroup = new HDFgroup( meshName, aFile );
5458 aTopGroup->OpenOnDisk();
5460 // get number of child HDF objects
5461 int aNbObjects = aTopGroup->nInternalObjects();
5462 if ( aNbObjects > 0 ) {
5464 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5465 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5466 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5467 if ( !myNewMeshImpl )
5469 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5471 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5472 int newId = myStudyContext->findId( iorString.in() );
5473 myStudyContext->mapOldToNew( id, newId );
5476 // try to read and set auto color flag
5477 char aMeshAutoColorName[ 30 ];
5478 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5479 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5481 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5482 aDataset->OpenOnDisk();
5483 size = aDataset->GetSize();
5484 int* anAutoColor = new int[ size ];
5485 aDataset->ReadFromDisk( anAutoColor );
5486 aDataset->CloseOnDisk();
5487 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5488 delete [] anAutoColor;
5491 // try to read and set reference to shape
5492 GEOM::GEOM_Object_var aShapeObject;
5493 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5494 // load mesh "Ref on shape" - it's an entry to SObject
5495 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5496 aDataset->OpenOnDisk();
5497 size = aDataset->GetSize();
5498 char* refFromFile = new char[ size ];
5499 aDataset->ReadFromDisk( refFromFile );
5500 aDataset->CloseOnDisk();
5501 if ( strlen( refFromFile ) > 0 ) {
5502 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5503 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5504 if ( !CORBA::is_nil( shapeObject ) ) {
5505 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5506 if ( !aShapeObject->_is_nil() )
5507 myNewMeshImpl->SetShape( aShapeObject );
5510 delete [] refFromFile;
5513 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5514 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5516 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5517 aDataset->OpenOnDisk();
5518 size = aDataset->GetSize();
5519 int* meshPersistentId = new int[ size ];
5520 aDataset->ReadFromDisk( meshPersistentId );
5521 aDataset->CloseOnDisk();
5522 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5523 delete [] meshPersistentId;
5526 // Restore SMESH_Mesh_i::_mainShapeTick
5527 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5529 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5530 aDataset->OpenOnDisk();
5531 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5532 aDataset->ReadFromDisk( shapeTick );
5533 aDataset->CloseOnDisk();
5536 // Restore file info
5537 if ( aTopGroup->ExistInternalObject( "file info" ))
5539 aDataset = new HDFdataset( "file info", aTopGroup );
5540 aDataset->OpenOnDisk();
5541 size = aDataset->GetSize();
5542 std::string info( size, ' ');
5543 aDataset->ReadFromDisk( (char*) info.data() );
5544 aDataset->CloseOnDisk();
5545 myNewMeshImpl->FileInfoFromString( info );
5551 // As all objects that can be referred by hypothesis are created,
5552 // we can restore hypothesis data
5554 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5555 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5557 SMESH_Hypothesis_i* hyp = hyp_data->first;
5558 string & data = hyp_data->second;
5559 hyp->LoadFrom( data.c_str() );
5562 // Restore the rest mesh data
5564 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5565 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5567 aTopGroup = meshi_group->second;
5568 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5570 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5571 bool hasData = false;
5574 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5575 int newId = myStudyContext->findId( iorString.in() );
5576 int meshOldId = myStudyContext->getOldId( newId );
5578 // try to find mesh data dataset
5579 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5580 // load mesh "has data" flag
5581 aDataset = new HDFdataset( "Has data", aTopGroup );
5582 aDataset->OpenOnDisk();
5583 size = aDataset->GetSize();
5584 char* strHasData = new char[ size ];
5585 aDataset->ReadFromDisk( strHasData );
5586 aDataset->CloseOnDisk();
5587 if ( strcmp( strHasData, "1") == 0 ) {
5590 delete [] strHasData;
5593 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5594 // nodes and elements are not yet put into sub-meshes)
5595 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5596 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5597 aGroup->OpenOnDisk();
5598 // get number of applied algorithms
5599 int aNbSubObjects = aGroup->nInternalObjects();
5600 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5601 for ( int j = 0; j < aNbSubObjects; j++ ) {
5602 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5603 aGroup->InternalObjectIndentify( j, name_dataset );
5604 // check if it is an algorithm
5605 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5606 aDataset = new HDFdataset( name_dataset, aGroup );
5607 aDataset->OpenOnDisk();
5608 size = aDataset->GetSize();
5609 char* refFromFile = new char[ size ];
5610 aDataset->ReadFromDisk( refFromFile );
5611 aDataset->CloseOnDisk();
5612 // san - it is impossible to recover applied algorithms using their entries within Load() method
5613 int id = atoi( refFromFile );
5614 delete [] refFromFile;
5615 string anIOR = myStudyContext->getIORbyOldId( id );
5616 if ( !anIOR.empty() ) {
5617 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5618 if ( !CORBA::is_nil( hypObject ) ) {
5619 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5620 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5621 || !myNewMeshImpl->HasShapeToMesh()) )
5622 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5627 aGroup->CloseOnDisk();
5630 // try to get applied hypotheses
5631 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5632 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5633 aGroup->OpenOnDisk();
5634 // get number of applied hypotheses
5635 int aNbSubObjects = aGroup->nInternalObjects();
5636 for ( int j = 0; j < aNbSubObjects; j++ ) {
5637 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5638 aGroup->InternalObjectIndentify( j, name_dataset );
5639 // check if it is a hypothesis
5640 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5641 aDataset = new HDFdataset( name_dataset, aGroup );
5642 aDataset->OpenOnDisk();
5643 size = aDataset->GetSize();
5644 char* refFromFile = new char[ size ];
5645 aDataset->ReadFromDisk( refFromFile );
5646 aDataset->CloseOnDisk();
5647 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5648 int id = atoi( refFromFile );
5649 delete [] refFromFile;
5650 string anIOR = myStudyContext->getIORbyOldId( id );
5651 if ( !anIOR.empty() ) {
5652 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5653 if ( !CORBA::is_nil( hypObject ) ) {
5654 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5655 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5656 || !myNewMeshImpl->HasShapeToMesh()) )
5657 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5662 aGroup->CloseOnDisk();
5665 // --> try to find SUB-MESHES containers for each type of submesh
5666 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5667 const char* name_meshgroup = 0;
5668 if ( j == GetSubMeshOnVertexTag() )
5669 name_meshgroup = "SubMeshes On Vertex";
5670 else if ( j == GetSubMeshOnEdgeTag() )
5671 name_meshgroup = "SubMeshes On Edge";
5672 else if ( j == GetSubMeshOnWireTag() )
5673 name_meshgroup = "SubMeshes On Wire";
5674 else if ( j == GetSubMeshOnFaceTag() )
5675 name_meshgroup = "SubMeshes On Face";
5676 else if ( j == GetSubMeshOnShellTag() )
5677 name_meshgroup = "SubMeshes On Shell";
5678 else if ( j == GetSubMeshOnSolidTag() )
5679 name_meshgroup = "SubMeshes On Solid";
5680 else if ( j == GetSubMeshOnCompoundTag() )
5681 name_meshgroup = "SubMeshes On Compound";
5683 // try to get submeshes container HDF group
5684 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5685 // open submeshes containers HDF group
5686 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5687 aGroup->OpenOnDisk();
5689 // get number of submeshes
5690 int aNbSubMeshes = aGroup->nInternalObjects();
5691 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5693 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5694 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5695 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5696 // --> get submesh id
5697 int subid = atoi( name_submeshgroup + 7 );
5700 // open submesh HDF group
5701 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5702 aSubGroup->OpenOnDisk();
5704 // try to read and set reference to subshape
5705 GEOM::GEOM_Object_var aSubShapeObject;
5706 SMESH::SMESH_subMesh_var aSubMesh;
5708 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5709 // load submesh "Ref on shape" - it's an entry to SObject
5710 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5711 aDataset->OpenOnDisk();
5712 size = aDataset->GetSize();
5713 char* refFromFile = new char[ size ];
5714 aDataset->ReadFromDisk( refFromFile );
5715 aDataset->CloseOnDisk();
5716 if ( strlen( refFromFile ) > 0 ) {
5717 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5718 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5719 if ( !CORBA::is_nil( subShapeObject ) ) {
5720 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5721 if ( !aSubShapeObject->_is_nil() )
5722 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5723 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5724 if ( aSubMesh->_is_nil() )
5726 string iorSubString = GetORB()->object_to_string( aSubMesh );
5727 int newSubId = myStudyContext->findId( iorSubString );
5728 myStudyContext->mapOldToNew( subid, newSubId );
5731 delete [] refFromFile;
5734 if ( aSubMesh->_is_nil() )
5737 // try to get applied algorithms
5738 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5739 // open "applied algorithms" HDF group
5740 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5741 aSubSubGroup->OpenOnDisk();
5742 // get number of applied algorithms
5743 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5744 for ( int l = 0; l < aNbSubObjects; l++ ) {
5745 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5746 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5747 // check if it is an algorithm
5748 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5749 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5750 aDataset->OpenOnDisk();
5751 size = aDataset->GetSize();
5752 char* refFromFile = new char[ size ];
5753 aDataset->ReadFromDisk( refFromFile );
5754 aDataset->CloseOnDisk();
5756 int id = atoi( refFromFile );
5757 string anIOR = myStudyContext->getIORbyOldId( id );
5758 if ( !anIOR.empty() ) {
5759 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5760 if ( !CORBA::is_nil( hypObject ) ) {
5761 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5762 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5763 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5766 delete [] refFromFile;
5769 // close "applied algorithms" HDF group
5770 aSubSubGroup->CloseOnDisk();
5773 // try to get applied hypotheses
5774 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5775 // open "applied hypotheses" HDF group
5776 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5777 aSubSubGroup->OpenOnDisk();
5778 // get number of applied hypotheses
5779 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5780 for ( int l = 0; l < aNbSubObjects; l++ ) {
5781 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5782 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5783 // check if it is a hypothesis
5784 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5785 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5786 aDataset->OpenOnDisk();
5787 size = aDataset->GetSize();
5788 char* refFromFile = new char[ size ];
5789 aDataset->ReadFromDisk( refFromFile );
5790 aDataset->CloseOnDisk();
5792 int id = atoi( refFromFile );
5793 string anIOR = myStudyContext->getIORbyOldId( id );
5794 if ( !anIOR.empty() ) {
5795 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5796 if ( !CORBA::is_nil( hypObject ) ) {
5797 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5798 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5799 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5802 delete [] refFromFile;
5805 // close "APPLIED HYPOTHESES" hdf group
5806 aSubSubGroup->CloseOnDisk();
5809 // close SUB-MESH hdf group
5810 aSubGroup->CloseOnDisk();
5813 // close SUB-MESHES containers hdf group
5814 aGroup->CloseOnDisk();
5818 // try to get GROUPS
5819 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5820 char name_group[ 30 ];
5821 if ( ii == GetNodeGroupsTag() )
5822 strcpy( name_group, "Groups of Nodes" );
5823 else if ( ii == GetEdgeGroupsTag() )
5824 strcpy( name_group, "Groups of Edges" );
5825 else if ( ii == GetFaceGroupsTag() )
5826 strcpy( name_group, "Groups of Faces" );
5827 else if ( ii == GetVolumeGroupsTag() )
5828 strcpy( name_group, "Groups of Volumes" );
5829 else if ( ii == Get0DElementsGroupsTag() )
5830 strcpy( name_group, "Groups of 0D Elements" );
5831 else if ( ii == GetBallElementsGroupsTag() )
5832 strcpy( name_group, "Groups of Balls" );
5834 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5835 aGroup = new HDFgroup( name_group, aTopGroup );
5836 aGroup->OpenOnDisk();
5837 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5838 // within aGroup->ExistInternalObject( name )
5839 std::vector< std::string > subNames;
5840 TColStd_MapOfAsciiString mapOfNames;
5841 aGroup->GetAllObjects( subNames );
5842 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5843 mapOfNames.Add( subNames[ iN ].c_str() );
5845 for ( size_t j = 0; j < subNames.size(); j++ ) {
5846 const std::string& name_dataset = subNames[ j ];
5847 // check if it is a group
5848 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5851 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5854 int groupID = -1; // group local ID (also persistent)
5856 groupID = atoi( endptr + 1 );
5857 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5858 aDataset->OpenOnDisk();
5860 // Retrieve actual group name
5861 size = aDataset->GetSize();
5862 char* nameFromFile = new char[ size ];
5863 aDataset->ReadFromDisk( nameFromFile );
5864 aDataset->CloseOnDisk();
5866 // Try to find a shape reference
5867 TopoDS_Shape aShape;
5868 char aRefName[ 30 ];
5869 sprintf( aRefName, "Ref on shape %d", subid);
5870 if ( mapOfNames.Contains( aRefName ))
5872 // load mesh "Ref on shape" - it's an entry to SObject
5873 aDataset = new HDFdataset( aRefName, aGroup );
5874 aDataset->OpenOnDisk();
5875 size = aDataset->GetSize();
5876 char* refFromFile = new char[ size ];
5877 aDataset->ReadFromDisk( refFromFile );
5878 aDataset->CloseOnDisk();
5879 if ( strlen( refFromFile ) > 0 ) {
5880 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5881 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5882 if ( !CORBA::is_nil( shapeObject ) ) {
5883 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5884 if ( !aShapeObject->_is_nil() )
5885 aShape = GeomObjectToShape( aShapeObject );
5888 delete [] refFromFile;
5890 // Try to read a filter of SMESH_GroupOnFilter
5891 SMESH::Filter_var filter;
5892 SMESH_PredicatePtr predicate;
5893 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5894 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5896 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5897 aDataset->OpenOnDisk();
5898 size = aDataset->GetSize();
5899 char* persistStr = new char[ size ];
5900 aDataset->ReadFromDisk( persistStr );
5901 aDataset->CloseOnDisk();
5902 if ( strlen( persistStr ) > 0 ) {
5903 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5904 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5905 filters.push_back( filter );
5907 delete [] persistStr;
5910 // Create group servant
5911 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5912 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5913 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5914 delete [] nameFromFile;
5915 // Obtain a SMESHDS_Group object
5916 if ( aNewGroup->_is_nil() )
5919 string iorSubString = GetORB()->object_to_string( aNewGroup );
5920 int newSubId = myStudyContext->findId( iorSubString );
5921 myStudyContext->mapOldToNew( subid, newSubId );
5923 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5927 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5928 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5930 aFilterGroup->SetFilter( filter );
5931 filter->UnRegister();
5933 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5934 if ( !aGroupBaseDS )
5937 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5940 // Read color of the group
5941 char aGroupColorName[ 30 ];
5942 sprintf( aGroupColorName, "ColorGroup %d", subid);
5943 if ( mapOfNames.Contains( aGroupColorName ))
5945 aDataset = new HDFdataset( aGroupColorName, aGroup );
5946 aDataset->OpenOnDisk();
5947 size = aDataset->GetSize();
5948 double* anRGB = new double[ size ];
5949 aDataset->ReadFromDisk( anRGB );
5950 aDataset->CloseOnDisk();
5951 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5952 aGroupBaseDS->SetColor( aColor );
5957 aGroup->CloseOnDisk();
5961 // instead of reading mesh data, we read only brief information of all
5962 // objects: mesh, groups, sub-meshes (issue 0021208)
5965 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5966 meshfile.ToCString(), filename.ToCString(),
5970 // read Sub-Mesh ORDER if any
5971 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5972 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5973 aDataset->OpenOnDisk();
5974 size = aDataset->GetSize();
5975 int* smIDs = new int[ size ];
5976 aDataset->ReadFromDisk( smIDs );
5977 aDataset->CloseOnDisk();
5978 TListOfListOfInt anOrderIds;
5979 anOrderIds.push_back( TListOfInt() );
5980 for ( int i = 0; i < size; i++ )
5981 if ( smIDs[ i ] < 0 ) // is separator
5982 anOrderIds.push_back( TListOfInt() );
5984 anOrderIds.back().push_back(smIDs[ i ]);
5986 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5989 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5991 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5992 aDataset->OpenOnDisk();
5993 size = aDataset->GetSize();
5994 std::string dataString; dataString.resize( size );
5995 aDataset->ReadFromDisk((char*) dataString.data() );
5996 aDataset->CloseOnDisk();
5998 std::list< std::list< std::string > > orderEntryLists;
5999 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6001 TListOfListOfInt anOrderIds;
6002 for ( const std::list< std::string >& entryList : orderEntryLists )
6004 anOrderIds.emplace_back();
6005 for ( const std::string & entry : entryList )
6007 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6008 TopoDS_Shape shape = GeomObjectToShape( go );
6009 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6010 anOrderIds.back().emplace_back( sm->GetId() );
6013 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6017 // update hyps needing full mesh data restored (issue 20918)
6018 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6020 SMESH_Hypothesis_i* hyp = hyp_data->first;
6021 hyp->UpdateAsMeshesRestored();
6024 // notify algos on completed restoration to set sub-mesh event listeners
6025 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6027 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6028 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6030 TopoDS_Shape myLocShape;
6031 if(myLocMesh.HasShapeToMesh())
6032 myLocShape = myLocMesh.GetShapeToMesh();
6034 myLocShape = SMESH_Mesh::PseudoShape();
6036 myLocMesh.GetSubMesh(myLocShape)->
6037 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6040 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6041 list< SMESH::Filter_var >::iterator f = filters.begin();
6042 for ( ; f != filters.end(); ++f )
6043 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6044 fi->FindBaseObjects();
6049 aTopGroup->CloseOnDisk();
6052 aFile->CloseOnDisk();
6055 // Remove temporary files created from the stream
6058 SMESH_File meshFile( meshfile.ToCString() );
6059 if ( !meshFile ) // no meshfile exists
6061 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6065 Engines::Container_var container = GetContainerRef();
6066 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6068 container_i->registerTemporaryFile( filename.ToCString() );
6069 container_i->registerTemporaryFile( meshfile.ToCString() );
6070 container_i->registerTemporaryFile( tmpDir.ToCString() );
6075 // creation of tree nodes for all data objects in the study
6076 // to support tree representation customization and drag-n-drop:
6077 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6078 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6079 useCaseBuilder->SetRootCurrent();
6080 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6081 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6082 for (it->InitEx(true); it->More(); it->Next()) {
6083 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6090 //=============================================================================
6092 * SMESH_Gen_i::LoadASCII
6094 * Load SMESH module's data in ASCII format
6096 //=============================================================================
6098 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6099 const SALOMEDS::TMPFile& theStream,
6101 bool isMultiFile ) {
6102 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6103 return Load( theComponent, theStream, theURL, isMultiFile );
6105 //before call main ::Load method it's need for decipher text format to
6106 //binary ( "|xx" => x' )
6107 int size = theStream.length();
6108 if ( int((size / 3 )*3) != size ) //error size of buffer
6111 int real_size = int(size / 3);
6113 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6116 unsigned int c = -1;
6117 for ( int i = 0; i < real_size; i++ )
6119 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6120 sscanf( tmp, "%x", &c );
6121 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6124 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6126 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6129 //=============================================================================
6131 * SMESH_Gen_i::Close
6133 * Clears study-connected data when it is closed
6135 //=============================================================================
6137 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6139 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6141 // Clear study contexts data
6142 myStudyContext->Clear();
6144 // remove the tmp files meshes are loaded from
6145 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6147 // Clean trace of API methods calls
6153 //=============================================================================
6155 * SMESH_Gen_i::ComponentDataType
6157 * Get component data type
6159 //=============================================================================
6161 char* SMESH_Gen_i::ComponentDataType()
6163 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6164 return CORBA::string_dup( "SMESH" );
6168 //=============================================================================
6170 * SMESH_Gen_i::IORToLocalPersistentID
6172 * Transform data from transient form to persistent
6174 //=============================================================================
6176 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6177 const char* IORString,
6178 CORBA::Boolean /*isMultiFile*/,
6179 CORBA::Boolean /*isASCII*/ )
6181 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6183 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6184 int anId = myStudyContext->findId( IORString );
6186 if(MYDEBUG) MESSAGE( "VSR " << anId )
6188 sprintf( strId, "%d", anId );
6189 return CORBA::string_dup( strId );
6192 return CORBA::string_dup( "" );
6195 //=============================================================================
6197 * SMESH_Gen_i::LocalPersistentIDToIOR
6199 * Transform data from persistent form to transient
6201 //=============================================================================
6203 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6204 const char* aLocalPersistentID,
6205 CORBA::Boolean /*isMultiFile*/,
6206 CORBA::Boolean /*isASCII*/ )
6208 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6210 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6211 int anId = atoi( aLocalPersistentID );
6212 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6214 return CORBA::string_dup( "" );
6217 //=======================================================================
6218 //function : RegisterObject
6220 //=======================================================================
6222 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6224 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6225 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6226 return myStudyContext->addObject( string( iorString.in() ) );
6231 //================================================================================
6233 * \brief Return id of registered object
6234 * \param theObject - the Object
6235 * \retval int - Object id
6237 //================================================================================
6239 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6241 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6242 string iorString = GetORB()->object_to_string( theObject );
6243 return myStudyContext->findId( iorString );
6248 //=============================================================================
6250 * SMESH_Gen_i::SetName
6252 * Set a new object name
6254 //=============================================================================
6256 void SMESH_Gen_i::SetName(const char* theIOR,
6257 const char* theName)
6259 if ( theIOR && strcmp( theIOR, "" ) ) {
6260 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6261 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6262 if ( !aSO->_is_nil() ) {
6263 SetName( aSO, theName );
6268 // Version information
6269 char* SMESH_Gen_i::getVersion()
6271 #if SMESH_DEVELOPMENT
6272 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6274 return CORBA::string_dup(SMESH_VERSION_STR);
6278 //=================================================================================
6279 // function : Move()
6280 // purpose : Moves objects to the specified position.
6281 // Is used in the drag-n-drop functionality.
6282 //=================================================================================
6284 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6285 SALOMEDS::SObject_ptr where,
6288 if ( CORBA::is_nil( where ) ) return;
6290 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6291 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6292 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6293 std::string dataType = father->ComponentDataType();
6294 if ( dataType != "SMESH" ) return; // not a SMESH component
6296 SALOMEDS::SObject_var objAfter;
6297 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6298 // insert at given row -> find insertion position
6299 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6301 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6302 if ( i == row && useCaseIt->More() ) {
6303 objAfter = useCaseIt->Value();
6307 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6308 SALOMEDS::SObject_var sobj = what[i];
6309 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6310 // insert the object to the use case tree
6311 if ( !CORBA::is_nil( objAfter ) )
6312 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6314 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6317 //================================================================================
6319 * \brief Returns true if algorithm can be used to mesh a given geometry
6320 * \param [in] theAlgoType - the algorithm type
6321 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6322 * \param [in] theGeomObject - the geometry to mesh
6323 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6324 * else, returns \c True if at least one shape is meshable
6325 * \return CORBA::Boolean - can or can't
6327 //================================================================================
6329 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6330 const char* theLibName,
6331 GEOM::GEOM_Object_ptr theGeomObject,
6332 CORBA::Boolean toCheckAll)
6336 std::string aPlatformLibName;
6337 GenericHypothesisCreator_i* aCreator =
6338 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6341 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6342 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6343 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6350 SMESH_CATCH( SMESH::doNothing );
6353 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6358 //================================================================================
6360 * \brief Collect indices of elements, which are located inside the sphere
6362 //================================================================================
6364 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6365 SMESH::ElementType theElemType,
6371 SMESH::long_array_var aResult = new SMESH::long_array();
6372 if ( meshPart->_is_nil() )
6373 return aResult._retn();
6375 // 1. Create geometrical object
6376 gp_Pnt aP( theX, theY, theZ );
6377 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6379 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6381 if ( lst.size() > 0 ) {
6382 aResult->length( lst.size() );
6383 for ( size_t i = 0; i < lst.size(); i++ ) {
6384 aResult[i] = lst[i];
6387 return aResult._retn();
6390 //================================================================================
6392 * \brief Collect indices of elements, which are located inside the box
6394 //================================================================================
6396 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6397 SMESH::ElementType theElemType,
6398 CORBA::Double theX1,
6399 CORBA::Double theY1,
6400 CORBA::Double theZ1,
6401 CORBA::Double theX2,
6402 CORBA::Double theY2,
6403 CORBA::Double theZ2)
6405 SMESH::long_array_var aResult = new SMESH::long_array();
6406 if( meshPart->_is_nil() )
6407 return aResult._retn();
6409 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6410 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6412 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6414 if( lst.size() > 0 ) {
6415 aResult->length( lst.size() );
6416 for ( size_t i = 0; i < lst.size(); i++ ) {
6417 aResult[i] = lst[i];
6420 return aResult._retn();
6423 //================================================================================
6425 * \brief Collect indices of elements, which are located inside the cylinder
6427 //================================================================================
6429 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6430 SMESH::ElementType theElemType,
6434 CORBA::Double theDX,
6435 CORBA::Double theDY,
6436 CORBA::Double theDZ,
6438 CORBA::Double theR )
6440 SMESH::long_array_var aResult = new SMESH::long_array();
6441 if( meshPart->_is_nil() )
6442 return aResult._retn();
6444 gp_Pnt aP( theX, theY, theZ );
6445 gp_Vec aV( theDX, theDY, theDZ );
6446 gp_Ax2 anAxes (aP, aV);
6448 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6450 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6452 if( lst.size() > 0 ) {
6453 aResult->length( lst.size() );
6454 for ( size_t i = 0; i < lst.size(); i++ ) {
6455 aResult[i] = lst[i];
6458 return aResult._retn();
6461 //================================================================================
6463 * \brief Collect indices of elements, which are located inside the geom object
6465 //================================================================================
6467 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6468 SMESH::ElementType theElemType,
6469 GEOM::GEOM_Object_ptr theGeom,
6470 CORBA::Double theTolerance )
6472 SMESH::long_array_var aResult = new SMESH::long_array();
6473 if( meshPart->_is_nil() || theGeom->_is_nil() )
6474 return aResult._retn();
6476 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6478 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6480 if( lst.size() > 0 ) {
6481 aResult->length( lst.size() );
6482 for ( size_t i = 0; i < lst.size(); i++ ) {
6483 aResult[i] = lst[i];
6486 return aResult._retn();
6489 //================================================================================
6491 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6493 //================================================================================
6495 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6496 SMESH::ElementType theElemType,
6497 const TopoDS_Shape& theShape,
6498 double* theTolerance) {
6500 std::vector<long> res;
6501 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6503 if ( mesh->_is_nil() )
6506 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6510 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6515 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6516 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6517 anElementsOnShape->SetAllNodes( true );
6518 anElementsOnShape->SetMesh( meshDS );
6519 anElementsOnShape->SetShape( theShape, aType );
6522 anElementsOnShape->SetTolerance(*theTolerance);
6524 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6525 if ( !msource->_is_nil() ) { // Mesh case
6526 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6528 while ( elemIt->more() ) {
6529 const SMDS_MeshElement* anElem = elemIt->next();
6530 long anId = anElem->GetID();
6531 if ( anElementsOnShape->IsSatisfy( anId ) )
6532 res.push_back( anId );
6536 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6537 if ( !gsource->_is_nil() ) {
6538 if(theElemType == SMESH::NODE) {
6539 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6540 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6541 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6542 long anId = node->GetID();
6543 if ( anElementsOnShape->IsSatisfy( anId ) )
6544 res.push_back( anId );
6547 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6548 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6549 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6550 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6551 long anId = elem->GetID();
6552 if ( anElementsOnShape->IsSatisfy( anId ) )
6553 res.push_back( anId );
6558 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6559 if ( !smsource->_is_nil() ) {
6560 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6561 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6562 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6564 long anId = elem->GetID();
6565 if ( anElementsOnShape->IsSatisfy( anId ) )
6566 res.push_back( anId );