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::CreateMeshesFromMED( const char* theFileName,
1320 SMESH::DriverMED_ReadStatus& theStatus )
1322 checkFileReadable( theFileName );
1325 char bname[ _MAX_FNAME ];
1326 _splitpath( theFileName, NULL, NULL, bname, NULL );
1327 string aFileName = bname;
1329 string aFileName = basename( const_cast<char *>( theFileName ));
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)
1348 SALOMEDS::StudyBuilder_var aStudyBuilder;
1349 aStudyBuilder = getStudyServant()->NewBuilder();
1350 aStudyBuilder->NewCommand(); // There is a transaction
1352 aResult->length( aNames.size() );
1355 // Iterate through all meshes and create mesh objects
1356 for ( const std::string & meshName : aNames )
1359 if (i > 0) aPythonDump << ", ";
1362 SMESH::SMESH_Mesh_var mesh = createMesh();
1364 // publish mesh in the study
1365 SALOMEDS::SObject_wrap aSO;
1366 if ( CanPublishInStudy( mesh ) )
1367 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1370 if ( !aSO->_is_nil() ) {
1373 aPythonDump << "mesh_" << i;
1376 // Read mesh data (groups are published automatically by ImportMEDFile())
1377 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1378 ASSERT( meshServant );
1379 SMESH::DriverMED_ReadStatus status1 =
1380 meshServant->ImportMEDFile( theFileName, meshName.c_str() );
1381 if (status1 > theStatus)
1382 theStatus = status1;
1384 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1385 meshServant->GetImpl().GetMeshDS()->Modified();
1387 if ( !aStudyBuilder->_is_nil() )
1388 aStudyBuilder->CommitCommand();
1391 // Update Python script
1392 aPythonDump << "], status) = " << this << ".CreateMeshesFromMED( r'" << theFileName << "' )";
1394 // Dump creation of groups
1395 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1396 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1398 return aResult._retn();
1401 //=============================================================================
1403 * SMESH_Gen_i::CreateMeshFromSTL
1405 * Create mesh and import data from STL file
1407 //=============================================================================
1409 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1411 Unexpect aCatch(SALOME_SalomeException);
1412 checkFileReadable( theFileName );
1414 SMESH::SMESH_Mesh_var aMesh = createMesh();
1417 char bname[ _MAX_FNAME ];
1418 _splitpath( theFileName, NULL, NULL, bname, NULL );
1419 string aFileName = bname;
1421 string aFileName = basename( const_cast<char *>(theFileName) );
1423 // publish mesh in the study
1424 if ( CanPublishInStudy( aMesh ) ) {
1425 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1426 aStudyBuilder->NewCommand(); // There is a transaction
1427 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1428 aStudyBuilder->CommitCommand();
1429 if ( !aSO->_is_nil() ) {
1430 // Update Python script
1431 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1435 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1437 aServant->ImportSTLFile( theFileName );
1438 aServant->GetImpl().GetMeshDS()->Modified();
1439 return aMesh._retn();
1442 //================================================================================
1444 * \brief Create meshes and import data from the CGSN file
1446 //================================================================================
1448 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1449 SMESH::DriverMED_ReadStatus& theStatus)
1451 Unexpect aCatch(SALOME_SalomeException);
1452 checkFileReadable( theFileName );
1454 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1457 // Retrieve nb meshes from the file
1458 DriverCGNS_Read myReader;
1459 myReader.SetFile( theFileName );
1460 Driver_Mesh::Status aStatus;
1461 int nbMeshes = myReader.GetNbMeshes(aStatus);
1462 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1464 aResult->length( nbMeshes );
1466 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1469 TPythonDump aPythonDump(this);
1470 aPythonDump << "([";
1472 if (theStatus == SMESH::DRS_OK)
1474 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1475 aStudyBuilder->NewCommand(); // There is a transaction
1479 // Iterate through all meshes and create mesh objects
1480 for ( ; i < nbMeshes; ++i )
1483 if (i > 0) aPythonDump << ", ";
1486 SMESH::SMESH_Mesh_var mesh = createMesh();
1487 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1489 // Read mesh data (groups are published automatically by ImportMEDFile())
1490 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1491 ASSERT( meshServant );
1493 SMESH::DriverMED_ReadStatus status1 =
1494 meshServant->ImportCGNSFile( theFileName, i, meshName );
1495 if (status1 > theStatus)
1496 theStatus = status1;
1498 meshServant->GetImpl().GetMeshDS()->Modified();
1499 // publish mesh in the study
1500 SALOMEDS::SObject_wrap aSO;
1501 if ( CanPublishInStudy( mesh ) )
1502 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1505 if ( !aSO->_is_nil() ) {
1509 aPythonDump << "mesh_" << i;
1512 aStudyBuilder->CommitCommand();
1515 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1517 // Dump creation of groups
1518 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1519 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1521 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1524 return aResult._retn();
1527 //================================================================================
1529 * \brief Create a mesh and import data from a GMF file
1531 //================================================================================
1533 SMESH::SMESH_Mesh_ptr
1534 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1535 CORBA::Boolean theMakeRequiredGroups,
1536 SMESH::ComputeError_out theError)
1538 Unexpect aCatch(SALOME_SalomeException);
1539 checkFileReadable( theFileName );
1541 SMESH::SMESH_Mesh_var aMesh = createMesh();
1543 char bname[ _MAX_FNAME ];
1544 _splitpath( theFileName, NULL, NULL, bname, NULL );
1545 string aFileName = bname;
1547 string aFileName = basename( const_cast<char *>(theFileName) );
1549 // publish mesh in the study
1550 if ( CanPublishInStudy( aMesh ) ) {
1551 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1552 aStudyBuilder->NewCommand(); // There is a transaction
1553 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1554 aStudyBuilder->CommitCommand();
1555 if ( !aSO->_is_nil() ) {
1556 // Update Python script
1557 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1558 << theFileName << "', "
1559 << theMakeRequiredGroups << " )";
1562 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1564 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1565 aServant->GetImpl().GetMeshDS()->Modified();
1566 return aMesh._retn();
1570 //=============================================================================
1572 * SMESH_Gen_i::IsReadyToCompute
1574 * Return true if mesh contains enough data to be computed
1576 //=============================================================================
1578 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1579 GEOM::GEOM_Object_ptr theShapeObject )
1581 Unexpect aCatch(SALOME_SalomeException);
1582 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1584 if ( CORBA::is_nil( theShapeObject ) )
1585 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1586 SALOME::BAD_PARAM );
1587 if ( CORBA::is_nil( theMesh ) )
1588 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1589 SALOME::BAD_PARAM );
1592 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1593 ASSERT( meshServant );
1594 if ( meshServant ) {
1595 // get local TopoDS_Shape
1596 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1597 // call implementation
1598 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1599 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1602 catch ( SALOME_Exception& S_ex ) {
1603 INFOS( "catch exception "<< S_ex.what() );
1608 //================================================================================
1610 * \brief Find SObject for an algo
1612 //================================================================================
1614 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1617 SALOMEDS::Study_var aStudy = getStudyServant();
1618 if ( !aStudy->_is_nil() ) {
1619 // find algo in the study
1620 CORBA::String_var compDataType = ComponentDataType();
1621 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1622 if ( !father->_is_nil() ) {
1623 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1624 for ( ; itBig->More(); itBig->Next() ) {
1625 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1626 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1627 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1628 for ( ; algoIt->More(); algoIt->Next() ) {
1629 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1630 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1631 if ( !CORBA::is_nil( algoIOR )) {
1632 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1633 if ( impl && impl->GetImpl() == algo )
1634 return algoSO._retn();
1636 } // loop on algo SO's
1639 } // SMESH component iterator
1643 return SALOMEDS::SObject::_nil();
1646 //================================================================================
1648 * \brief Return errors of mesh computation
1650 //================================================================================
1652 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1653 GEOM::GEOM_Object_ptr theSubObject )
1655 Unexpect aCatch(SALOME_SalomeException);
1656 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1658 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1659 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1661 if ( CORBA::is_nil( theMesh ) )
1662 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1664 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1666 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1669 if(theMesh->HasShapeToMesh())
1670 shape = GeomObjectToShape( theSubObject );
1672 shape = SMESH_Mesh::PseudoShape();
1674 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1676 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1679 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1680 const bool includeSelf = true, complexShapeFirst = true;
1681 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1683 while ( smIt->more() )
1686 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1688 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1689 if ( error && !error->IsOK() )
1691 if ( !( error->myAlgo ) &&
1692 !( error->myAlgo = sm->GetAlgo() ))
1694 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1695 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1696 errStruct.comment = error->myComment.c_str();
1697 errStruct.subShapeID = sm->GetId();
1698 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1699 if ( !algoSO->_is_nil() ) {
1700 CORBA::String_var algoName = algoSO->GetName();
1701 errStruct.algoName = algoName;
1704 errStruct.algoName = error->myAlgo->GetName();
1706 errStruct.hasBadMesh = error->HasBadElems();
1709 error_array->length( nbErr );
1712 catch ( SALOME_Exception& S_ex ) {
1713 INFOS( "catch exception "<< S_ex.what() );
1716 return error_array._retn();
1719 //================================================================================
1721 * \brief Return mesh elements preventing computation of a subshape
1723 //================================================================================
1725 SMESH::MeshPreviewStruct*
1726 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1727 CORBA::Short theSubShapeID )
1729 Unexpect aCatch(SALOME_SalomeException);
1730 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1732 if ( CORBA::is_nil( theMesh ) )
1733 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1735 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1738 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1740 // mesh implementation
1741 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1742 // submesh by subshape id
1743 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1746 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1747 if ( error && error->HasBadElems() )
1749 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1750 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1752 // get nodes of elements and count elements
1753 TNode2LocalIDMap mapNode2LocalID;
1754 list< TNodeLocalID > connectivity;
1755 int i, nbElements = 0, nbConnNodes = 0;
1757 const list<const SMDS_MeshElement*>& badElems =
1758 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1759 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1760 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1761 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1763 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1764 while ( nIt->more() )
1765 connectivity.push_back
1766 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1768 // fill node coords and assign local ids to the nodes
1769 int nbNodes = mapNode2LocalID.size();
1770 result->nodesXYZ.length( nbNodes );
1771 TNodeLocalID node2ID = mapNode2LocalID.begin();
1772 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1773 node2ID->second = i;
1774 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1775 result->nodesXYZ[i].x = node->X();
1776 result->nodesXYZ[i].y = node->Y();
1777 result->nodesXYZ[i].z = node->Z();
1779 // fill connectivity
1780 result->elementConnectivities.length( nbConnNodes );
1781 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1782 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1783 result->elementConnectivities[i] = (*connIt)->second;
1785 // fill element types
1786 result->elementTypes.length( nbElements );
1787 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1789 const SMDS_MeshElement* elem = *elemIt;
1790 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1791 result->elementTypes[i].isPoly = elem->IsPoly();
1792 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1798 catch ( SALOME_Exception& S_ex ) {
1799 INFOS( "catch exception "<< S_ex.what() );
1802 return result._retn();
1805 //================================================================================
1807 * \brief Create a group of elements preventing computation of a sub-shape
1809 //================================================================================
1811 SMESH::ListOfGroups*
1812 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1813 CORBA::Short theSubShapeID,
1814 const char* theGroupName )
1816 Unexpect aCatch(SALOME_SalomeException);
1818 SMESH::ListOfGroups_var groups;
1820 if ( CORBA::is_nil( theMesh ) )
1821 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1824 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1826 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1827 TPythonDump(this) << groups << " = " << this
1828 << ".MakeGroupsOfBadInputElements( "
1829 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1832 catch ( SALOME_Exception& S_ex ) {
1833 INFOS( "catch exception "<< S_ex.what() );
1835 return groups._retn();
1838 //================================================================================
1840 * \brief Returns errors of hypotheses definition
1841 * \param theMesh - the mesh
1842 * \param theSubObject - the main or sub- shape
1843 * \retval SMESH::algo_error_array* - sequence of errors
1845 //================================================================================
1847 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1848 GEOM::GEOM_Object_ptr theSubObject )
1850 Unexpect aCatch(SALOME_SalomeException);
1851 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1853 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1854 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1856 if ( CORBA::is_nil( theMesh ) )
1857 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1859 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1861 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1862 ASSERT( meshServant );
1863 if ( meshServant ) {
1864 TopoDS_Shape myLocShape;
1865 if(theMesh->HasShapeToMesh())
1866 myLocShape = GeomObjectToShape( theSubObject );
1868 myLocShape = SMESH_Mesh::PseudoShape();
1870 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1871 list< ::SMESH_Gen::TAlgoStateError > error_list;
1872 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1873 // call ::SMESH_Gen::GetAlgoState()
1874 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1875 error_array->length( error_list.size() );
1877 for ( error = error_list.begin(); error != error_list.end(); ++error )
1879 // fill AlgoStateError structure
1880 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1881 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1882 errStruct.algoDim = error->_algoDim;
1883 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1884 errStruct.algoName = "";
1885 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1886 if ( !algoSO->_is_nil() ) {
1887 CORBA::String_var algoName = algoSO->GetName();
1888 errStruct.algoName = algoName.in();
1893 catch ( SALOME_Exception& S_ex ) {
1894 INFOS( "catch exception "<< S_ex.what() );
1896 return error_array._retn();
1899 //=============================================================================
1901 * SMESH_Gen_i::GetSubShapesId
1903 * Get sub-shapes unique ID's list
1905 //=============================================================================
1908 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1909 const SMESH::object_array& theListOfSubShapeObject )
1911 Unexpect aCatch(SALOME_SalomeException);
1912 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1914 SMESH::long_array_var shapesId = new SMESH::long_array;
1917 if ( CORBA::is_nil( theMainShapeObject ) )
1918 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1922 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1923 TopTools_IndexedMapOfShape myIndexToShape;
1924 TopExp::MapShapes(myMainShape,myIndexToShape);
1926 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1928 GEOM::GEOM_Object_var aShapeObject
1929 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1930 if ( CORBA::is_nil( aShapeObject ) )
1931 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1932 SALOME::BAD_PARAM );
1934 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1935 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1937 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1938 setId.insert(myIndexToShape.FindIndex(F));
1939 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1941 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1943 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1944 setId.insert(myIndexToShape.FindIndex(E));
1945 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1947 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1949 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1950 setId.insert(myIndexToShape.FindIndex(V));
1951 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1954 shapesId->length(setId.size());
1955 set<int>::iterator iind;
1957 for (iind = setId.begin(); iind != setId.end(); iind++)
1959 if(MYDEBUG) SCRUTE((*iind));
1960 shapesId[i] = (*iind);
1961 if(MYDEBUG) SCRUTE(shapesId[i]);
1965 catch (SALOME_Exception& S_ex)
1967 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1970 return shapesId._retn();
1973 //=============================================================================
1975 * SMESH_Gen_i::Compute
1977 * Compute mesh on a shape
1979 //=============================================================================
1981 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1982 GEOM::GEOM_Object_ptr theShapeObject )
1985 Unexpect aCatch(SALOME_SalomeException);
1986 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1988 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1989 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1990 SALOME::BAD_PARAM );
1992 if ( CORBA::is_nil( theMesh ) )
1993 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1994 SALOME::BAD_PARAM );
1996 // Update Python script
1997 TPythonDump(this) << "isDone = " << this << ".Compute( "
1998 << theMesh << ", " << theShapeObject << ")";
2002 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2003 ASSERT( meshServant );
2004 if ( meshServant ) {
2005 if ( isGeomModifIcon( theMesh ))
2006 meshServant->Clear();
2008 meshServant->Load();
2009 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2010 meshServant->CheckGeomModif();
2011 // get local TopoDS_Shape
2012 TopoDS_Shape myLocShape;
2013 if(theMesh->HasShapeToMesh())
2014 myLocShape = GeomObjectToShape( theShapeObject );
2016 myLocShape = SMESH_Mesh::PseudoShape();
2017 // call implementation compute
2018 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2019 myGen.PrepareCompute( myLocMesh, myLocShape );
2020 int how = ::SMESH_Gen::COMPACT_MESH;
2021 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2022 how |= ::SMESH_Gen::SHAPE_ONLY;
2023 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2024 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2025 myLocMesh.GetMeshDS()->Modified();
2026 UpdateIcons( theMesh );
2028 HighLightInvalid( theMesh, /*isInvalid=*/false );
2032 catch ( std::bad_alloc& ) {
2033 INFOS( "Compute(): lack of memory" );
2035 catch ( SALOME_Exception& S_ex ) {
2036 INFOS( "Compute(): catch exception "<< S_ex.what() );
2039 INFOS( "Compute(): unknown exception " );
2044 //=============================================================================
2046 * SMESH_Gen_i::CancelCompute
2048 * Cancel Compute mesh on a shape
2050 //=============================================================================
2052 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2053 GEOM::GEOM_Object_ptr theShapeObject )
2055 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2057 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2058 TopoDS_Shape myLocShape;
2059 if(theMesh->HasShapeToMesh())
2060 myLocShape = GeomObjectToShape( theShapeObject );
2062 myLocShape = SMESH_Mesh::PseudoShape();
2063 myGen.CancelCompute( myLocMesh, myLocShape);
2067 //=============================================================================
2069 * SMESH_Gen_i::Precompute
2071 * Compute mesh as preview till indicated dimension on shape
2073 //=============================================================================
2075 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2076 GEOM::GEOM_Object_ptr theShapeObject,
2077 SMESH::Dimension theDimension,
2078 SMESH::long_array& theShapesId)
2080 Unexpect aCatch(SALOME_SalomeException);
2081 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2083 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2084 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2085 SALOME::BAD_PARAM );
2087 if ( CORBA::is_nil( theMesh ) )
2088 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2089 SALOME::BAD_PARAM );
2091 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2094 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2095 meshServant->Load();
2096 ASSERT( meshServant );
2097 if ( meshServant ) {
2098 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2099 meshServant->CheckGeomModif();
2100 // get local TopoDS_Shape
2101 TopoDS_Shape myLocShape;
2102 if(theMesh->HasShapeToMesh())
2103 myLocShape = GeomObjectToShape( theShapeObject );
2105 return result._retn();
2107 // call implementation compute
2108 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2110 ::MeshDimension aDim = (MeshDimension)theDimension;
2111 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2113 int nbShapeId = shapeIds.size();
2114 theShapesId.length( nbShapeId );
2115 // iterates on shapes and collect mesh entities into mesh preview
2116 TSetOfInt::const_iterator idIt = shapeIds.begin();
2117 TSetOfInt::const_iterator idEnd = shapeIds.end();
2118 std::map< int, int > mapOfShIdNb;
2119 std::set< SMESH_TLink > setOfEdge;
2120 std::list< SMDSAbs_ElementType > listOfElemType;
2121 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2122 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2123 TNode2LocalIDMap mapNode2LocalID;
2124 list< TNodeLocalID > connectivity;
2125 int i, nbConnNodes = 0;
2126 std::set< const SMESH_subMesh* > setOfVSubMesh;
2127 // iterates on shapes
2128 for ( ; idIt != idEnd; idIt++ )
2130 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2132 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2133 if ( !sm || !sm->IsMeshComputed() )
2136 const TopoDS_Shape& aSh = sm->GetSubShape();
2137 const int shDim = myGen.GetShapeDim( aSh );
2138 if ( shDim < 1 || shDim > theDimension )
2141 mapOfShIdNb[ *idIt ] = 0;
2142 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2144 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2145 if ( !smDS ) continue;
2147 if ( theDimension == SMESH::DIM_2D )
2149 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2150 while ( faceIt->more() )
2152 const SMDS_MeshElement* face = faceIt->next();
2153 int aNbNode = face->NbNodes();
2155 aNbNode /= 2; // do not take into account additional middle nodes
2157 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2158 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2160 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2161 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2163 listOfElemType.push_back( SMDSAbs_Edge );
2164 connectivity.push_back
2165 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2166 connectivity.push_back
2167 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2173 else if ( theDimension == SMESH::DIM_1D )
2175 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2176 while ( nodeIt->more() )
2178 listOfElemType.push_back( SMDSAbs_Node );
2179 connectivity.push_back
2180 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2182 // add corner nodes by first vertex from edge
2183 SMESH_subMeshIteratorPtr edgeSmIt =
2184 sm->getDependsOnIterator(/*includeSelf*/false,
2185 /*complexShapeFirst*/false);
2186 while ( edgeSmIt->more() )
2188 SMESH_subMesh* vertexSM = edgeSmIt->next();
2189 // check that vertex is not already treated
2190 if ( !setOfVSubMesh.insert( vertexSM ).second )
2192 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2195 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2196 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2197 while ( nodeIt->more() )
2199 listOfElemType.push_back( SMDSAbs_Node );
2200 connectivity.push_back
2201 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2207 // fill node coords and assign local ids to the nodes
2208 int nbNodes = mapNode2LocalID.size();
2209 result->nodesXYZ.length( nbNodes );
2210 TNodeLocalID node2ID = mapNode2LocalID.begin();
2211 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2212 node2ID->second = i;
2213 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2214 result->nodesXYZ[i].x = node->X();
2215 result->nodesXYZ[i].y = node->Y();
2216 result->nodesXYZ[i].z = node->Z();
2218 // fill connectivity
2219 result->elementConnectivities.length( nbConnNodes );
2220 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2221 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2222 result->elementConnectivities[i] = (*connIt)->second;
2225 // fill element types
2226 result->elementTypes.length( listOfElemType.size() );
2227 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2228 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2229 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2231 SMDSAbs_ElementType elemType = *typeIt;
2232 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2233 result->elementTypes[i].isPoly = false;
2234 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2237 // correct number of shapes
2238 theShapesId.length( mapOfShIdNb.size() );
2242 catch ( std::bad_alloc& ) {
2243 INFOS( "Precompute(): lack of memory" );
2245 catch ( SALOME_Exception& S_ex ) {
2246 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2249 INFOS( "Precompute(): unknown exception " );
2251 return result._retn();
2255 //=============================================================================
2257 * SMESH_Gen_i::Evaluate
2259 * Evaluate mesh on a shape
2261 //=============================================================================
2263 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2264 GEOM::GEOM_Object_ptr theShapeObject)
2266 Unexpect aCatch(SALOME_SalomeException);
2267 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2269 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2270 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2272 if ( CORBA::is_nil( theMesh ) )
2273 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2275 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2276 nbels->length(SMESH::Entity_Last);
2277 int i = SMESH::Entity_Node;
2278 for (; i < SMESH::Entity_Last; i++)
2281 // Update Python script
2282 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2283 << theMesh << ", " << theShapeObject << ")";
2287 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2288 ASSERT( meshServant );
2289 if ( meshServant ) {
2290 meshServant->Load();
2291 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2292 meshServant->CheckGeomModif();
2293 // get local TopoDS_Shape
2294 TopoDS_Shape myLocShape;
2295 if(theMesh->HasShapeToMesh())
2296 myLocShape = GeomObjectToShape( theShapeObject );
2298 myLocShape = SMESH_Mesh::PseudoShape();
2299 // call implementation compute
2300 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2301 MapShapeNbElems aResMap;
2302 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2303 MapShapeNbElemsItr anIt = aResMap.begin();
2304 for(; anIt!=aResMap.end(); anIt++) {
2305 const vector<smIdType>& aVec = (*anIt).second;
2306 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2307 smIdType nbElem = aVec[i];
2308 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2310 SMESH_subMesh* sm = anIt->first;
2311 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2312 const SMESH_Algo* algo = sm->GetAlgo();
2313 if ( (algo && !error.get()) || error->IsOK() )
2314 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2318 nbels[i] += aVec[i];
2322 return nbels._retn();
2325 catch ( std::bad_alloc& ) {
2326 INFOS( "Evaluate(): lack of memory" );
2328 catch ( SALOME_Exception& S_ex ) {
2329 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2332 INFOS( "Evaluate(): unknown exception " );
2335 return nbels._retn();
2338 //================================================================================
2340 * \brief Return geometrical object the given element is built on
2341 * \param theMesh - the mesh the element is in
2342 * \param theElementID - the element ID
2343 * \param theGeomName - the name of the result geom object if it is not yet published
2344 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2346 //================================================================================
2348 GEOM::GEOM_Object_ptr
2349 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2350 SMESH::smIdType theElementID,
2351 const char* theGeomName)
2353 Unexpect aCatch(SALOME_SalomeException);
2355 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2356 if ( !geom->_is_nil() ) {
2357 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2358 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2360 // try to find the corresponding SObject
2361 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2362 if ( SObj->_is_nil() ) // submesh can be not found even if published
2364 // try to find published submesh
2365 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2366 if ( !geom->IsMainShape() && list->length() == 1 ) {
2367 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2368 SALOMEDS::ChildIterator_wrap it;
2369 if ( !mainSO->_is_nil() ) {
2370 it = getStudyServant()->NewChildIterator( mainSO );
2372 if ( !it->_is_nil() ) {
2373 for ( it->InitEx(true); it->More(); it->Next() ) {
2374 SALOMEDS::SObject_wrap so = it->Value();
2375 CORBA::Object_var obj = SObjectToObject( so );
2376 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2377 if ( !subGeom->_is_nil() ) {
2378 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2379 if ( subList->length() == 1 && list[0] == subList[0] ) {
2389 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2390 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2392 // return only published geometry
2393 if ( !SObj->_is_nil() ) {
2394 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2395 CORBA::Object_var obj = SObjectToObject( SObj );
2396 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2400 return GEOM::GEOM_Object::_nil();
2403 //================================================================================
2405 * \brief Return geometrical object the given element is built on.
2406 * \param theMesh - the mesh the element is in
2407 * \param theElementID - the element ID
2408 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2410 //================================================================================
2412 GEOM::GEOM_Object_ptr
2413 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2414 SMESH::smIdType theElementID)
2416 Unexpect aCatch(SALOME_SalomeException);
2417 if ( CORBA::is_nil( theMesh ) )
2418 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2420 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2421 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2423 // get a core mesh DS
2424 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2425 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2427 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2428 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2429 // find the element in mesh
2430 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2431 // find a shape id by the element
2432 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2433 // get a geom object by the shape id
2434 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2435 if ( geom->_is_nil() ) {
2436 // try to find a published sub-shape
2437 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2438 SALOMEDS::ChildIterator_wrap it;
2439 if ( !mainSO->_is_nil() ) {
2440 it = getStudyServant()->NewChildIterator( mainSO );
2442 if ( !it->_is_nil() ) {
2443 for ( it->InitEx(true); it->More(); it->Next() ) {
2444 SALOMEDS::SObject_wrap so = it->Value();
2445 CORBA::Object_var obj = SObjectToObject( so );
2446 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2447 if ( !subGeom->_is_nil() ) {
2448 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2449 if ( subList->length() == 1 && shapeID == subList[0] ) {
2457 if ( geom->_is_nil() ) {
2459 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2460 if ( !op->_is_nil() )
2461 geom = op->GetSubShape( mainShape, shapeID );
2466 if ( !geom->_is_nil() ) {
2467 GeomObjectToShape( geom ); // let geom client remember the found shape
2468 return geom._retn();
2473 return GEOM::GEOM_Object::_nil();
2476 //================================================================================
2478 * SMESH_Gen_i::Concatenate
2480 * Concatenate the given meshes into one mesh
2482 //================================================================================
2484 SMESH::SMESH_Mesh_ptr
2485 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2486 CORBA::Boolean theUniteIdenticalGroups,
2487 CORBA::Boolean theMergeNodesAndElements,
2488 CORBA::Double theMergeTolerance,
2489 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2491 return ConcatenateCommon(theMeshesArray,
2492 theUniteIdenticalGroups,
2493 theMergeNodesAndElements,
2499 //================================================================================
2501 * SMESH_Gen_i::ConcatenateWithGroups
2503 * Concatenate the given meshes into one mesh
2504 * Create the groups of all elements from initial meshes
2506 //================================================================================
2508 SMESH::SMESH_Mesh_ptr
2509 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2510 CORBA::Boolean theUniteIdenticalGroups,
2511 CORBA::Boolean theMergeNodesAndElements,
2512 CORBA::Double theMergeTolerance,
2513 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2515 return ConcatenateCommon(theMeshesArray,
2516 theUniteIdenticalGroups,
2517 theMergeNodesAndElements,
2523 //================================================================================
2525 * SMESH_Gen_i::ConcatenateCommon
2527 * Concatenate the given meshes into one mesh
2529 //================================================================================
2531 SMESH::SMESH_Mesh_ptr
2532 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2533 CORBA::Boolean theUniteIdenticalGroups,
2534 CORBA::Boolean theMergeNodesAndElements,
2535 CORBA::Double theMergeTolerance,
2536 CORBA::Boolean theCommonGroups,
2537 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2539 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2540 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2542 // create mesh if theMeshToAppendTo not provided
2543 SMESH::SMESH_Mesh_var newMesh;
2544 if ( CORBA::is_nil( theMeshToAppendTo ))
2545 newMesh = CreateEmptyMesh();
2547 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2548 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2549 if ( !newImpl ) return newMesh._retn();
2552 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2553 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2555 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2556 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2557 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2558 TGroupsMap groupsMap;
2559 TListOfNewGroups listOfNewGroups;
2561 if ( !CORBA::is_nil( theMeshToAppendTo ))
2563 // fill groupsMap with existing groups
2564 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2565 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2567 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2568 if ( !group->_is_nil() )
2570 CORBA::String_var name = group->GetName();
2571 SMESH::ElementType type = group->GetType();
2572 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2577 ::SMESH_MeshEditor newEditor( &locMesh );
2578 ::SMESH_MeshEditor::ElemFeatures elemType;
2580 // loop on sub-meshes
2581 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2583 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2584 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2585 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2586 if ( !initImpl ) continue;
2587 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2591 // assure that IDs increment by one during iteration
2592 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2593 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2594 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2595 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2597 initMeshDS->Modified();
2598 initMeshDS->CompactMesh();
2601 // remember nb of elements before filling in
2602 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2606 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2607 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2608 while ( elemIt->more() )
2610 SMESH_NodeXYZ node = elemIt->next();
2611 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2616 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2617 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2619 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2620 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2621 while ( elemIt->more() )
2623 const SMDS_MeshElement* elem = elemIt->next();
2624 elemType.myNodes.resize( elem->NbNodes() );
2626 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2627 for ( int k = 0; itNodes->more(); k++)
2629 const SMDS_MeshNode* node = itNodes->next();
2630 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2633 // creates a corresponding element on existent nodes in new mesh
2634 newElems[ elem->GetID() ] =
2635 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2637 newEditor.ClearLastCreated(); // forget the history
2640 // create groups of just added elements
2641 SMESH::SMESH_Group_var newGroup;
2642 SMESH::ElementType groupType;
2643 if ( theCommonGroups )
2646 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2648 // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2649 static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2650 "Update names of ElementType's!!!" );
2652 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2654 for( groupType = SMESH::NODE;
2655 groupType < SMESH::NB_ELEMENT_TYPES;
2656 groupType = (SMESH::ElementType)( groupType + 1 ))
2658 if ( curState[ groupType ] <= prevState[ groupType ])
2659 continue; // no elements of groupType added from the i-th mesh
2661 // make a group name
2662 std::string groupName = "Gr";
2663 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2665 CORBA::String_var name = meshSO->GetName();
2669 groupName += typeNames[ groupType ];
2671 // make and fill a group
2672 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2673 std::vector< const SMDS_MeshElement* > & elemVec =
2674 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2675 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2677 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2679 for ( size_t j = 0; j < elemVec.size(); ++j )
2681 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2682 grpDS->Add( elemVec[j] );
2686 listOfNewGroups.clear();
2687 listOfNewGroups.push_back( newGroup );
2688 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2693 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2697 SMESH::SMESH_GroupBase_ptr group;
2698 CORBA::String_var groupName;
2699 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2701 // loop on groups of a source mesh
2702 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2703 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2705 group = listOfGroups[iG];
2706 groupType = group->GetType();
2707 groupName = group->GetName();
2708 std::string name = groupName.in();
2710 // convert a list of IDs
2711 newIDs->length( group->Size() );
2712 std::vector< const SMDS_MeshElement* > & elemVec =
2713 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2714 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2716 while ( itGrElems->more() )
2718 const SMDS_MeshElement* elem = itGrElems->next();
2719 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2721 newIDs[ nbElems++ ] = newElem->GetID();
2723 newIDs->length( nbElems );
2725 // check that a current group name and type don't have identical ones in final mesh
2726 listOfNewGroups.clear();
2727 TNameAndType nameAndType( name, groupType );
2728 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2729 if ( anIter == groupsMap.end() )
2731 // add a new group in the mesh
2732 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2733 newGroup->Add( newIDs );
2735 listOfNewGroups.push_back( newGroup );
2736 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2738 else if ( theUniteIdenticalGroups )
2740 // unite identical groups
2741 TListOfNewGroups& aNewGroups = anIter->second;
2742 aNewGroups.front()->Add( newIDs );
2746 // rename identical groups
2747 newGroup = newImpl->CreateGroup( groupType, groupName );
2748 newGroup->Add( newIDs );
2750 TListOfNewGroups& newGroups = anIter->second;
2751 std::string newGroupName;
2752 if ( newGroups.size() == 1 )
2754 newGroupName = name + "_1";
2755 newGroups.front()->SetName( newGroupName.c_str() );
2757 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2758 newGroup->SetName( newGroupName.c_str() );
2759 newGroups.push_back( newGroup );
2762 } // if an IDSource is a mesh
2765 if ( theMergeNodesAndElements ) // merge nodes
2767 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2768 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2769 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2770 /*SeparateCornersAndMedium=*/ false );
2771 newEditor.MergeNodes( groupsOfNodes );
2773 newEditor.MergeEqualElements();
2776 // Update Python script
2777 pythonDump << newMesh << " = " << this
2778 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2779 << theMeshesArray << ", "
2780 << theUniteIdenticalGroups << ", "
2781 << theMergeNodesAndElements << ", "
2782 << TVar( theMergeTolerance ) << ", "
2783 << theMeshToAppendTo << " )";
2785 pPythonDump.reset(); // enable python dump from GetGroups()
2787 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2788 if ( !newMesh->_is_nil() )
2790 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2793 // IPAL21468 Change icon of compound because it need not be computed.
2794 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2795 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2797 newMeshDS->Modified();
2799 return newMesh._retn();
2802 //================================================================================
2804 * \brief Create a mesh by copying a part of another mesh
2805 * \param meshPart - a part of mesh to copy
2806 * \param toCopyGroups - to create in the new mesh groups
2807 * the copied elements belongs to
2808 * \param toKeepIDs - to preserve IDs of the copied elements or not
2809 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2811 //================================================================================
2813 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2814 const char* meshName,
2815 CORBA::Boolean toCopyGroups,
2816 CORBA::Boolean toKeepIDs)
2818 Unexpect aCatch(SALOME_SalomeException);
2820 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2821 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2823 // 1. Get source mesh
2825 if ( CORBA::is_nil( meshPart ))
2826 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2828 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2829 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2831 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2833 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2835 // 2. Make a new mesh
2837 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2838 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2840 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2841 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2842 if ( !meshSO->_is_nil() )
2844 SetName( meshSO, meshName, "Mesh" );
2845 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2847 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2848 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2849 ::SMESH_MeshEditor::ElemFeatures elemType;
2851 // 3. Get elements to copy
2853 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2854 TIDSortedElemSet srcElems;
2855 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2856 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2859 srcElemIt = srcMeshDS->elementsIterator();
2860 srcNodeIt = srcMeshDS->nodesIterator();
2864 SMESH::smIdType_array_var ids = meshPart->GetIDs();
2865 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2867 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2868 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2869 srcElems.insert( elem );
2873 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2874 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2875 srcElems.insert( elem );
2877 if ( srcElems.empty() )
2878 return newMesh._retn();
2880 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2881 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2886 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2887 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2888 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2890 const SMDS_MeshNode *nSrc, *nTgt;
2891 vector< const SMDS_MeshNode* > nodes;
2892 while ( srcElemIt->more() )
2894 const SMDS_MeshElement * elem = srcElemIt->next();
2896 nodes.resize( elem->NbNodes());
2897 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2899 for ( iN = 0; nIt->more(); ++iN )
2901 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2902 nTgt = newMeshDS->FindNode( nSrc->GetID());
2904 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2909 for ( iN = 0; nIt->more(); ++iN )
2911 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2912 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2914 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2915 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2919 if ( elem->GetType() != SMDSAbs_Node )
2921 elemType.Init( elem, /*basicOnly=*/false );
2922 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2924 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2925 if ( toCopyGroups && !toKeepIDs )
2926 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2928 } // while ( srcElemIt->more() )
2930 // 4(b). Copy free nodes
2932 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2934 while ( srcNodeIt->more() )
2936 nSrc = srcNodeIt->next();
2937 if ( nSrc->NbInverseElements() == 0 )
2940 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2942 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2949 int nbNewGroups = 0;
2952 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2953 while ( gIt->more() )
2955 SMESH_Group* group = gIt->next();
2956 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2958 // Check group type. We copy nodal groups containing nodes of copied element
2959 SMDSAbs_ElementType groupType = groupDS->GetType();
2960 if ( groupType != SMDSAbs_Node &&
2961 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2962 continue; // group type differs from types of meshPart
2964 // Find copied elements in the group
2965 vector< const SMDS_MeshElement* > groupElems;
2966 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2969 const SMDS_MeshElement* foundElem;
2970 if ( groupType == SMDSAbs_Node )
2972 while ( eIt->more() )
2973 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2974 groupElems.push_back( foundElem );
2978 while ( eIt->more() )
2979 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2980 groupElems.push_back( foundElem );
2985 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2986 if ( e2eMap.empty() ) continue;
2987 smIdType minID = e2eMap.begin()->first->GetID();
2988 smIdType maxID = e2eMap.rbegin()->first->GetID();
2989 TE2EMap::iterator e2e;
2990 while ( eIt->more() && groupElems.size() < e2eMap.size())
2992 const SMDS_MeshElement* e = eIt->next();
2993 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2994 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2995 groupElems.push_back( e2e->second );
2999 if ( !groupElems.empty() )
3001 SMESH::SMESH_Group_var newGroupObj =
3002 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3003 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3005 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3006 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3007 for ( unsigned i = 0; i < groupElems.size(); ++i )
3008 smdsGroup.Add( groupElems[i] );
3016 newMeshDS->Modified();
3018 *pyDump << newMesh << " = " << this
3019 << ".CopyMesh( " << meshPart << ", "
3020 << "'" << meshName << "', "
3021 << toCopyGroups << ", "
3022 << toKeepIDs << ")";
3024 pyDumpDeleter.reset(); // allow dump in GetGroups()
3026 if ( nbNewGroups > 0 ) // dump created groups
3027 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3029 return newMesh._retn();
3033 namespace // utils for CopyMeshWithGeom()
3035 typedef std::map< std::string, std::string > TStr2StrMap;
3036 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3037 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3038 typedef std::map< std::string, int > TName2IndexMap;
3040 //================================================================================
3042 * \brief Return a new sub-shape corresponding to an old one
3044 //================================================================================
3048 SMESH_Mesh_i* mySrcMesh_i;
3049 SMESH_Mesh_i* myNewMesh_i;
3050 SMESH_Gen_i* myGen_i;
3054 TStr2StrMap myOld2NewEntryMap; // map of study entries
3056 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3057 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3058 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3061 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3063 // not directly relating to shape search
3064 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3066 //================================================================================
3068 * \brief Constructor
3070 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3071 SMESH_Mesh_i* newMesh_i,
3072 SMESH_Gen_i* smeshGen_i )
3073 : mySrcMesh_i( srcMesh_i ),
3074 myNewMesh_i( newMesh_i ),
3075 myGen_i ( smeshGen_i ),
3076 myToPublish( smeshGen_i->IsEnablePublish() ),
3077 myGIPMapDone( false )
3079 // retrieve from the study shape mapping made thanks to
3080 // "Set presentation parameters and sub-shapes from arguments" option
3082 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3083 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3084 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3085 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3086 if ( newSO->_is_nil() )
3088 myToPublish = false;
3091 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3093 CORBA::String_var oldEntry = oldSO->GetID();
3094 CORBA::String_var newEntry = newSO->GetID();
3095 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3096 std::string( newEntry.in() )));
3097 std::string newMainEntry = newEntry.in();
3099 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3100 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3101 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3102 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3103 /*groupsOnly=*/false );
3104 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3106 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3107 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3108 bool refFound = false;
3109 for ( ; anIter->More(); anIter->Next() )
3111 SALOMEDS::SObject_wrap so = anIter->Value();
3112 if ( so->ReferencedObject( oldSO.inout() ))
3114 oldEntry = oldSO->GetID();
3115 newEntry = newSO->GetID();
3116 if (( refFound = ( newMainEntry != oldEntry.in() )))
3117 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3118 std::string( newEntry.in() )));
3123 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3124 if ( father->_is_equivalent( mainShapeNew ))
3126 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3127 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3128 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3129 CORBA::String_var name = newSO->GetName();
3131 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3137 //================================================================================
3139 * \brief Find a new sub-shape corresponding to an old one
3141 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3144 return GEOM::GEOM_Object::_duplicate( oldShape );
3146 GEOM::GEOM_Object_var newShape;
3148 if ( CORBA::is_nil( oldShape ))
3149 return newShape._retn();
3151 if ( !isChildOfOld( oldShape ))
3152 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3154 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3155 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3157 // try to find by entry or name
3160 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3161 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3162 if ( o2nID != myOld2NewEntryMap.end() )
3164 newShape = getShapeByEntry( o2nID->second );
3166 if ( newShape->_is_nil() )
3168 CORBA::String_var name = oldShape->GetName();
3169 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3170 if ( n2ind != myName2SubshapeIndex.end() )
3172 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3173 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3174 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3175 if ( oldIndices->length() == 0 ||
3176 newIndices->length() == 0 ||
3177 getShapeType( myNewMesh_i, newIndices[0] ) !=
3178 getShapeType( mySrcMesh_i, oldIndices[0] ))
3179 newShape = GEOM::GEOM_Object::_nil();
3184 if ( newShape->_is_nil() )
3186 // try to construct a new sub-shape using myGIPMap
3188 std::vector< int > newIndices;
3189 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3190 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3192 findNewIDs( oldIndices[i], newIndices );
3194 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3197 newShape = getInPlace( oldShape );
3199 if ( !newIndices.empty() && newShape->_is_nil() )
3201 // search for a sub-shape with same ids
3202 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3203 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3204 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3205 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3207 if ( newShape->_is_nil() )
3210 // create a new shape
3211 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3213 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3215 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3216 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3218 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3219 newIndicesList->length( newIndices.size() );
3220 for ( size_t i = 0; i < newIndices.size(); ++i )
3221 newIndicesList[ i ] = newIndices[ i ];
3222 grOp->UnionIDs( newShape, newIndicesList );
3226 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3227 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3236 if ( !newShape->_is_nil() && myToPublish )
3238 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3239 if ( !newEntry.in() || !newEntry.in()[0] )
3241 CORBA::String_var name = oldShape->GetName();
3242 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3243 newEntry = newShape->GetStudyEntry();
3244 oldEntry = oldShape->GetStudyEntry();
3245 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3246 std::string( newEntry.in() )));
3250 return newShape._retn();
3253 //================================================================================
3255 * \brief Return a study entry of a new shape by study entry of the old one
3257 std::string FindNew( const std::string & oldEntry )
3262 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3263 if ( o2nID != myOld2NewEntryMap.end() )
3264 return o2nID->second;
3266 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3267 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3270 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3271 if ( newShape->_is_nil() )
3272 return std::string();
3274 CORBA::String_var newEntry = newShape->GetStudyEntry();
3275 return newEntry.in();
3278 //================================================================================
3280 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3281 * Return zero if not found or there are more than one new ID
3283 int FindNew( int oldID )
3292 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3294 if ( myGIPMap[ oldID ].length() == 1 )
3296 newID = myGIPMap[ oldID ][ 0 ];
3298 else if ( myGIPMap[ oldID ].length() > 1 &&
3299 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3301 // select a meshed VERTEX
3302 SMESH_subMesh* newSM;
3303 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3304 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3305 ( !newSM->IsEmpty() ))
3306 newID = myGIPMap[ oldID ][ i ];
3312 //================================================================================
3314 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3315 * Return zero if the old shape is not kept as is in the new shape.
3317 int FindNewNotChanged( SMESH_subMesh* oldSM )
3320 return oldSM->GetId();
3322 int newID = FindNew( oldSM->GetId() );
3326 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3330 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3331 // one new sub-shape of the same type.
3333 if ( oldSM->DependsOn().size() !=
3334 newSM->DependsOn().size() )
3337 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3338 while ( srcSMIt->more() )
3340 oldSM = srcSMIt->next();
3341 int newSubID = FindNew( oldSM->GetId() );
3342 if ( getShapeType( myNewMesh_i, newSubID ) !=
3343 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3349 //================================================================================
3351 * \brief Return shape by study entry
3353 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3355 GEOM::GEOM_Object_var shape;
3356 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3357 if ( !so->_is_nil() )
3359 CORBA::Object_var obj = so->GetObject();
3360 shape = GEOM::GEOM_Object::_narrow( obj );
3362 return shape._retn();
3365 //================================================================================
3367 * \brief Fill myGIPMap by calling GetInPlaceMap()
3371 if ( !myGIPMapDone )
3373 myGIPMapDone = true;
3375 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3376 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3377 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3378 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3381 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3385 myGIPMap = new GEOM::ListOfListOfLong();
3390 //================================================================================
3392 * \brief Get new sub-shape by calling GetInPlace()
3394 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3396 GEOM::GEOM_Object_var newShape;
3398 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3399 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3400 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3403 newShape = op->GetInPlace( mainShapeNew, oldShape );
3408 return newShape._retn();
3411 //================================================================================
3413 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3414 * number of found IDs
3416 int findNewIDs( int oldID, std::vector< int >& newIDs )
3418 size_t prevNbIDs = newIDs.size();
3420 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3422 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3423 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3425 return newIDs.size() - prevNbIDs;
3428 //================================================================================
3430 * \brief Check if an object relates to the old shape
3432 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3434 if ( CORBA::is_nil( oldShape ))
3436 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3437 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3438 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3439 mainShapeOld1->_is_equivalent( oldShape ));
3442 //================================================================================
3444 * \brief Return shape type by shape ID
3446 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3448 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3449 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3450 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3453 //================================================================================
3455 * \brief Store a source sub-shape for which a counterpart not found and
3456 * a smesh object invalid due to that
3458 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3459 SALOMEDS::SObject_wrap smeshSO )
3461 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3462 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3464 CORBA::String_var smeshEntry = smeshSO->GetID();
3465 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3469 //================================================================================
3471 * \brief Store a source sub-shape for which a counterpart not found and
3472 * a smesh object invalid due to that
3474 void AddInvalid( std::string geomEntry,
3475 SALOMEDS::SObject_wrap smeshSO )
3477 if ( !geomEntry.empty() )
3479 CORBA::String_var smeshEntry = smeshSO->GetID();
3480 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3484 //================================================================================
3486 * \brief Store a source sub-shape for which a counterpart not found and
3487 * a smesh object invalid due to that
3489 void AddInvalid( int oldGeomID,
3490 SALOMEDS::SObject_wrap smeshSO )
3492 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3493 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3496 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3497 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3499 SMESH_Comment geomName( typeName[ shapeType ]);
3500 geomName << " #" << oldGeomID;
3502 CORBA::String_var smeshEntry = smeshSO->GetID();
3503 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3506 //================================================================================
3508 * \brief Return entries of a source sub-shape for which a counterpart not found and
3509 * of smesh objects invalid due to that
3511 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3512 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3515 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3516 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3518 nbSO += 1 + entry2entrySet->second.size();
3520 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3521 theInvalidEntries->length ( nbSO );
3522 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3524 entry2entrySet = myInvalidMap.begin();
3525 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3527 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3529 std::set< std::string > & entrySet = entry2entrySet->second;
3530 std::set< std::string >::iterator entry = entrySet.begin();
3531 for ( ; entry != entrySet.end(); ++entry )
3533 theInvalidEntries[ iEntry++ ] = entry->c_str();
3535 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3536 if ( !so->_is_nil() )
3537 theInvalidMeshSObjects[ iSO++ ] = so;
3542 }; // struct ShapeMapper
3544 //================================================================================
3546 * \brief Append an item to a CORBA sequence
3548 template < class CORBA_seq, class ITEM >
3549 void append( CORBA_seq& seq, ITEM item )
3551 if ( !CORBA::is_nil( item ))
3553 seq->length( 1 + seq->length() );
3554 seq[ seq->length() - 1 ] = item;
3557 } // namespace // utils for CopyMeshWithGeom()
3559 //================================================================================
3561 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3562 * \param [in] sourceMesh - a mesh to copy
3563 * \param [in] newGeometry - a new geometry
3564 * \param [in] toCopyGroups - to create groups in the new mesh
3565 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3566 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3567 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3568 * \param [out] newMesh - return a new mesh
3569 * \param [out] newGroups - return new groups
3570 * \param [out] newSubmeshes - return new sub-meshes
3571 * \param [out] newHypotheses - return new algorithms and hypotheses
3572 * \param [out] invalidEntries - return study entries of objects whose
3573 * counterparts are not found in the newGeometry, followed by entries
3574 * of mesh sub-objects that are invalid because they depend on a not found
3575 * preceding sub-shape
3576 * \return CORBA::Boolean - is a success
3578 //================================================================================
3580 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3581 GEOM::GEOM_Object_ptr theNewGeometry,
3582 const char* theMeshName,
3583 CORBA::Boolean theToCopyGroups,
3584 CORBA::Boolean theToReuseHypotheses,
3585 CORBA::Boolean theToCopyElements,
3586 SMESH::SMESH_Mesh_out theNewMesh,
3587 SMESH::ListOfGroups_out theNewGroups,
3588 SMESH::submesh_array_out theNewSubmeshes,
3589 SMESH::ListOfHypothesis_out theNewHypotheses,
3590 SMESH::string_array_out theInvalidEntries)
3592 if ( CORBA::is_nil( theSourceMesh ) ||
3593 CORBA::is_nil( theNewGeometry ))
3594 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3596 if ( !theSourceMesh->HasShapeToMesh() )
3597 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3602 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3604 theNewMesh = CreateMesh( theNewGeometry );
3605 theNewGroups = new SMESH::ListOfGroups();
3606 theNewSubmeshes = new SMESH::submesh_array();
3607 theNewHypotheses = new SMESH::ListOfHypothesis();
3608 theInvalidEntries = new SMESH::string_array();
3610 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3612 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3613 GEOM::GEOM_Object_var geom, newGeom;
3614 SALOMEDS::SObject_wrap so;
3616 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3617 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3620 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3622 // treat hypotheses of mesh and sub-meshes
3623 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3624 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3626 bool isSubMesh = ( iSM < smList->length() );
3629 // create a new sub-mesh
3630 SMESH::SMESH_subMesh_var newSM;
3631 geom = smList[iSM]->GetSubShape();
3632 so = ObjectToSObject( smList[iSM] );
3633 CORBA::String_var name;
3634 if ( !so->_is_nil() )
3635 name = so->GetName();
3636 newGeom = shapeMapper.FindNew( geom );
3637 if ( newGeom->_is_nil() )
3639 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3640 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3645 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3647 append( theNewSubmeshes, newSM );
3649 if ( newGeom->_is_nil() )
3650 continue; // don't assign hypotheses
3654 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3656 so = ObjectToSObject( theNewMesh );
3657 SetName( so, theMeshName, "Mesh" );
3660 // assign hypotheses
3661 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3662 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3664 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3665 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3667 // get geometry hyp depends on
3668 std::vector< std::string > entryArray;
3669 std::vector< int > subIDArray;
3670 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3672 if ( !theToReuseHypotheses || dependsOnGeom )
3674 // create a new hypothesis
3675 CORBA::String_var type = hyp->GetName();
3676 CORBA::String_var lib = hyp->GetLibName();
3677 CORBA::String_var data = hyp_i->SaveTo();
3680 hyp = CreateHypothesis( type, lib );
3681 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3682 hyp_i->LoadFrom( data.in() );
3683 append( theNewHypotheses, hyp );
3687 // update geometry hyp depends on
3688 if ( dependsOnGeom )
3690 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3692 if ( !entryArray[ iGeo ].empty() )
3694 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3695 if ( newEntry.empty() )
3698 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3699 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3701 entryArray[ iGeo ] = newEntry;
3704 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3706 if ( subIDArray[ iGeo ] > 0 )
3708 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3712 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3713 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3715 subIDArray[ iGeo ] = newID;
3718 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3722 CORBA::String_var errorText;
3723 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3724 if ( errorText.in()[0] )
3727 } // loop on hypotheses
3728 } // loop on sub-meshes and mesh
3731 // copy mesh elements, keeping IDs
3732 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3733 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3735 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3736 ::SMESH_MeshEditor::ElemFeatures elemData;
3738 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3739 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3740 /*vertexLast=*/false);
3741 while ( srcSMIt->more() )
3743 SMESH_subMesh* srcSM = srcSMIt->next();
3744 if ( srcSM->IsEmpty() )
3745 continue; // not yet computed
3746 int newID = shapeMapper.FindNewNotChanged( srcSM );
3750 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3751 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3752 while ( nIt->more() )
3754 SMESH_NodeXYZ node( nIt->next() );
3755 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3757 const SMDS_PositionPtr pos = node->GetPosition();
3758 const double* uv = pos->GetParameters();
3759 switch ( pos->GetTypeOfPosition() )
3761 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3762 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3763 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3764 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3768 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3769 while( eIt->more() )
3771 const SMDS_MeshElement* e = eIt->next();
3772 elemData.Init( e, /*basicOnly=*/false );
3773 elemData.SetID( e->GetID() );
3774 elemData.myNodes.resize( e->NbNodes() );
3775 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3777 for ( iN = 0; nnIt->more(); ++iN )
3779 const SMDS_MeshNode* srcNode = nnIt->next();
3780 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3781 if ( !elemData.myNodes[ iN ])
3784 if ( iN == elemData.myNodes.size() )
3785 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3786 newMeshDS->SetMeshElementOnShape( newElem, newID );
3788 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3789 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3792 newMeshDS->Modified();
3798 TStr2StrMap old2newGroupMap;
3800 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3802 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3803 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3804 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3806 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3807 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3808 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3810 CORBA::String_var name = groups[ i ]->GetName();
3811 SMESH::ElementType elemType = groups[ i ]->GetType();
3813 SMESH::SMESH_GroupBase_var newGroup;
3815 if ( !stdlGroup->_is_nil() )
3817 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3819 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3820 const bool isElem = ( elemType != SMESH::NODE );
3821 CORBA::ULong iE = 0;
3822 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3823 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3825 if ( iE < elemIDs->length() )
3827 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3828 stdlGroup->Add( elemIDs );
3829 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3833 else if ( !geomGroup->_is_nil() )
3835 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3836 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3837 if ( newGeom->_is_nil() )
3839 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3840 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3845 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3848 else if ( !fltrGroup->_is_nil() )
3850 // replace geometry in a filter
3851 SMESH::Filter_var filter = fltrGroup->GetFilter();
3852 SMESH::Filter::Criteria_var criteria;
3853 filter->GetCriteria( criteria.out() );
3855 bool isMissingGroup = false;
3856 std::vector< std::string > badEntries;
3858 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3860 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3861 switch ( criteria[ iCr ].Type )
3863 case SMESH::FT_BelongToMeshGroup:
3865 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3866 btgg->SetGroupID( thresholdID );
3867 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3868 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3869 if ( refGroupSO->_is_nil() )
3871 CORBA::String_var refID = refGroupSO->GetID();
3872 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3873 if ( o2nID == old2newGroupMap.end() )
3875 isMissingGroup = true; // corresponding new group not yet created
3878 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3880 if ( o2nID->second.empty() ) // new referred group is invalid
3881 badEntries.push_back( refID.in() );
3884 case SMESH::FT_BelongToGeom:
3885 case SMESH::FT_BelongToPlane:
3886 case SMESH::FT_BelongToCylinder:
3887 case SMESH::FT_BelongToGenSurface:
3888 case SMESH::FT_LyingOnGeom:
3890 std::string newID = shapeMapper.FindNew( thresholdID );
3891 criteria[ iCr ].ThresholdID = newID.c_str();
3892 if ( newID.empty() )
3893 badEntries.push_back( thresholdID );
3896 case SMESH::FT_ConnectedElements:
3898 if ( thresholdID && thresholdID[0] )
3900 std::string newID = shapeMapper.FindNew( thresholdID );
3901 criteria[ iCr ].ThresholdID = newID.c_str();
3902 if ( newID.empty() )
3903 badEntries.push_back( thresholdID );
3909 } // loop on criteria
3911 if ( isMissingGroup && i < nbGroups )
3913 // to treat the group again
3914 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3918 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3919 newFilter->SetCriteria( criteria );
3921 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3922 newFilter->UnRegister();
3924 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3925 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3926 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3928 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3930 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3933 if ( !badEntries.empty() )
3936 } // treat a group on filter
3938 append( theNewGroups, newGroup );
3940 // fill old2newGroupMap
3941 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3942 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3943 if ( !srcSO->_is_nil() )
3945 CORBA::String_var srcID, newID("");
3946 srcID = srcSO->GetID();
3947 if ( !newSO->_is_nil() )
3948 newID = newSO->GetID();
3949 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3950 std::string( newID.in() )));
3953 if ( newGroup->_is_nil() )
3958 newMeshDS->CompactMesh();
3961 if ( !theMeshName || !theMeshName[0] )
3963 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3964 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3965 CORBA::String_var oldName = soOld->GetName();
3966 SetName( soNew, oldName.in(), "Mesh" );
3968 // mark invalid objects
3969 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3971 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3972 highLightInvalid( invalidSObjects[i].in(), true );
3975 << theNewMesh << ", "
3976 << theNewGroups << ", "
3977 << *theNewSubmeshes.ptr() << ", "
3978 << *theNewHypotheses.ptr() << ", "
3979 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3980 << theSourceMesh << ", "
3981 << theNewGeometry << ", "
3982 << "'" << theMeshName << "', "
3983 << theToCopyGroups << ", "
3984 << theToReuseHypotheses << ", "
3985 << theToCopyElements << " )";
3987 SMESH_CATCH( SMESH::throwCorbaException );
3992 //================================================================================
3994 * \brief Get version of MED format being used.
3996 //================================================================================
3998 char* SMESH_Gen_i::GetMEDFileVersion()
4000 MED::TInt majeur, mineur, release;
4001 majeur = mineur = release = 0;
4002 MED::GetVersionRelease(majeur, mineur, release);
4003 std::ostringstream version;
4004 version << majeur << "." << mineur << "." << release;
4005 return CORBA::string_dup( version.str().c_str() );
4008 //================================================================================
4010 * SMESH_Gen_i::GetMEDVersion
4012 * Get MED version of the file by its name
4014 //================================================================================
4016 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4018 std::string version = MED::GetMEDVersion( theFileName );
4019 return CORBA::string_dup( version.c_str() );
4022 //================================================================================
4024 * SMESH_Gen_i::CheckCompatibility
4026 * Check compatibility of file with MED format being used, read only.
4028 //================================================================================
4030 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4032 return MED::CheckCompatibility( theFileName );
4035 //================================================================================
4037 * SMESH_Gen_i::CheckWriteCompatibility
4039 * Check compatibility of file with MED format being used, for append on write.
4041 //================================================================================
4043 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4045 return MED::CheckCompatibility( theFileName, true );
4048 //================================================================================
4050 * SMESH_Gen_i::GetMeshNames
4052 * Get names of meshes defined in file with the specified name
4054 //================================================================================
4055 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4058 SMESH::string_array_var aResult = new SMESH::string_array();
4059 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4061 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4063 aResult->length( aNbMeshes );
4064 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4065 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4066 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4069 return aResult._retn();
4072 //=============================================================================
4076 * Save SMESH module's data
4078 //=============================================================================
4080 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4085 Kernel_Utils::Localizer loc;
4087 if (!myStudyContext)
4090 // Store study contents as a set of python commands
4093 SALOMEDS::Study_var aStudy = getStudyServant();
4095 // Declare a byte stream
4096 SALOMEDS::TMPFile_var aStreamFile;
4098 // Obtain a temporary dir
4099 TCollection_AsciiString tmpDir =
4100 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4102 // Create a sequence of files processed
4103 SALOMEDS_Tool::ListOfFiles aFileSeq;
4104 aFileSeq.reserve( NUM_TMP_FILES );
4106 TCollection_AsciiString aStudyName( "" );
4108 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4110 // Set names of temporary files
4111 TCollection_AsciiString filename =
4112 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4113 TCollection_AsciiString meshfile =
4114 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4115 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4116 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4117 filename = tmpDir + filename;
4118 meshfile = tmpDir + meshfile;
4121 HDFdataset* aDataset;
4122 HDFgroup* aTopGroup;
4124 HDFgroup* aSubGroup;
4125 HDFgroup* aSubSubGroup;
4126 hdf_size aSize[ 1 ];
4129 //Remove the files if they exist: BugID: 11225
4130 #ifndef WIN32 /* unix functionality */
4131 TCollection_AsciiString cmd("rm -f \"");
4133 TCollection_AsciiString cmd("del /F \"");
4143 system(cmd.ToCString());
4145 // MED writer to be used by storage process
4146 DriverMED_W_SMESHDS_Mesh writer;
4147 writer.SetFile( meshfile.ToCString() );
4148 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4151 // SetStoreName() to groups before storing hypotheses to let them refer to
4152 // groups using "store name", which is "Group <group_persistent_id>"
4154 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4155 for ( ; itBig->More(); itBig->Next() ) {
4156 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4157 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4158 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4159 if ( !CORBA::is_nil( anObject ) ) {
4160 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4161 if ( !myMesh->_is_nil() ) {
4162 myMesh->Load(); // load from study file if not yet done
4163 TPythonDump pd(this); // not to dump GetGroups()
4164 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4165 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4167 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4170 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4171 int anId = myStudyContext->findId( string( objStr.in() ) );
4173 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4174 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4175 aGrpBaseDS->SetStoreName( grpName );
4185 // ---> create HDF file
4186 aFile = new HDFfile( (char*) filename.ToCString() );
4187 aFile->CreateOnDisk();
4189 // --> iterator for top-level objects
4190 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4191 for ( ; itBig->More(); itBig->Next() ) {
4192 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4194 // --> hypotheses root branch (only one for the study)
4195 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4196 // create hypotheses root HDF group
4197 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4198 aTopGroup->CreateOnDisk();
4200 // iterator for all hypotheses
4201 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4202 for ( ; it->More(); it->Next() ) {
4203 SALOMEDS::SObject_wrap mySObject = it->Value();
4204 CORBA::Object_var anObject = SObjectToObject( mySObject );
4205 if ( !CORBA::is_nil( anObject ) ) {
4206 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4207 if ( !myHyp->_is_nil() ) {
4208 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4210 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4211 std::string hypname = hn.in();
4212 std::string libname = ln.in();
4214 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4215 // WIN32 and ".so" for X-system) must be deleted
4216 int libname_len = libname.length();
4218 if( libname_len > 4 )
4219 libname.resize( libname_len - 4 );
4221 // PAL17753 (Regression: missing hypothesis in restored study)
4222 // "lib" also should be removed from the beginning
4223 if( libname_len > 6 )
4224 libname = libname.substr( 3, libname_len - 3 - 3 );
4226 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4227 CORBA::String_var hypdata = myImpl->SaveTo();
4228 int id = myStudyContext->findId( string( objStr.in() ));
4230 // for each hypothesis create HDF group basing on its id
4231 char hypGrpName[30];
4232 sprintf( hypGrpName, "Hypothesis %d", id );
4233 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4234 aGroup->CreateOnDisk();
4235 // --> type name of hypothesis
4236 aSize[ 0 ] = hypname.length() + 1;
4237 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4238 aDataset->CreateOnDisk();
4239 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4240 aDataset->CloseOnDisk();
4241 // --> server plugin library name of hypothesis
4242 aSize[ 0 ] = libname.length() + 1;
4243 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4244 aDataset->CreateOnDisk();
4245 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4246 aDataset->CloseOnDisk();
4247 // --> persistent data of hypothesis
4248 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4249 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4250 aDataset->CreateOnDisk();
4251 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4252 aDataset->CloseOnDisk();
4253 // close hypothesis HDF group
4254 aGroup->CloseOnDisk();
4259 // close hypotheses root HDF group
4260 aTopGroup->CloseOnDisk();
4262 // --> algorithms root branch (only one for the study)
4263 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4264 // create algorithms root HDF group
4265 aTopGroup = new HDFgroup( "Algorithms", aFile );
4266 aTopGroup->CreateOnDisk();
4268 // iterator for all algorithms
4269 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4270 for ( ; it->More(); it->Next() ) {
4271 SALOMEDS::SObject_wrap mySObject = it->Value();
4272 CORBA::Object_var anObject = SObjectToObject( mySObject );
4273 if ( !CORBA::is_nil( anObject ) ) {
4274 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4275 if ( !myHyp->_is_nil() ) {
4276 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4278 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4279 std::string hypname = hn.in();
4280 std::string libname = ln.in();
4282 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4283 // WIN32 and ".so" for X-system) must be deleted
4284 int libname_len = libname.length();
4286 if( libname_len > 4 )
4287 libname.resize( libname_len - 4 );
4289 // PAL17753 (Regression: missing hypothesis in restored study)
4290 // "lib" also should be removed from the beginning
4291 if( libname_len > 6 )
4292 libname = libname.substr( 3, libname_len - 3 - 3 );
4294 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4295 CORBA::String_var hypdata = myImpl->SaveTo();
4296 int id = myStudyContext->findId( string( objStr.in() ) );
4298 // for each algorithm create HDF group basing on its id
4299 char hypGrpName[30];
4300 sprintf( hypGrpName, "Algorithm %d", id );
4301 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4302 aGroup->CreateOnDisk();
4303 // --> type name of algorithm
4304 aSize[0] = hypname.length() + 1;
4305 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4306 aDataset->CreateOnDisk();
4307 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4308 aDataset->CloseOnDisk();
4309 // --> server plugin library name of hypothesis
4310 aSize[0] = libname.length() + 1;
4311 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4312 aDataset->CreateOnDisk();
4313 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4314 aDataset->CloseOnDisk();
4315 // --> persistent data of algorithm
4316 aSize[0] = strlen( hypdata.in() ) + 1;
4317 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4318 aDataset->CreateOnDisk();
4319 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4320 aDataset->CloseOnDisk();
4321 // close algorithm HDF group
4322 aGroup->CloseOnDisk();
4327 // close algorithms root HDF group
4328 aTopGroup->CloseOnDisk();
4330 // --> mesh objects roots branches
4331 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4332 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4333 if ( !CORBA::is_nil( anObject ) ) {
4334 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4335 if ( !myMesh->_is_nil() ) {
4336 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4338 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4339 int id = myStudyContext->findId( string( objStr.in() ) );
4340 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4341 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4342 bool hasShape = myLocMesh.HasShapeToMesh();
4344 // for each mesh open the HDF group basing on its id
4345 char meshGrpName[ 30 ];
4346 sprintf( meshGrpName, "Mesh %d", id );
4347 aTopGroup = new HDFgroup( meshGrpName, aFile );
4348 aTopGroup->CreateOnDisk();
4350 // --> put dataset to hdf file which is a flag that mesh has data
4351 string strHasData = "0";
4352 // check if the mesh is not empty
4353 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4354 // write mesh data to med file
4355 writer.SetMesh( mySMESHDSMesh );
4356 writer.SetMeshId( id );
4359 aSize[ 0 ] = strHasData.length() + 1;
4360 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4361 aDataset->CreateOnDisk();
4362 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4363 aDataset->CloseOnDisk();
4366 // for each mesh open the HDF group basing on its auto color parameter
4367 char meshAutoColorName[ 30 ];
4368 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4370 anAutoColor[0] = myImpl->GetAutoColor();
4372 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4373 aDataset->CreateOnDisk();
4374 aDataset->WriteOnDisk( anAutoColor );
4375 aDataset->CloseOnDisk();
4377 // issue 0020693. Store _isModified flag
4378 int isModified = myLocMesh.GetIsModified();
4380 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4381 aDataset->CreateOnDisk();
4382 aDataset->WriteOnDisk( &isModified );
4383 aDataset->CloseOnDisk();
4385 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4386 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4388 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4389 aDataset->CreateOnDisk();
4390 aDataset->WriteOnDisk( &meshPersistentId );
4391 aDataset->CloseOnDisk();
4393 // Store SMESH_Mesh_i::_mainShapeTick
4394 int shapeTick = myImpl->MainShapeTick();
4396 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4397 aDataset->CreateOnDisk();
4398 aDataset->WriteOnDisk( &shapeTick );
4399 aDataset->CloseOnDisk();
4401 // write reference on a shape if exists
4402 SALOMEDS::SObject_wrap myRef;
4403 bool shapeRefFound = false;
4404 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4406 SALOMEDS::SObject_wrap myShape;
4407 bool ok = myRef->ReferencedObject( myShape.inout() );
4409 CORBA::Object_var shapeObj = myShape->GetObject();
4410 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4411 CORBA::String_var myRefOnObject = myShape->GetID();
4412 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4413 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4414 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4415 aDataset->CreateOnDisk();
4416 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4417 aDataset->CloseOnDisk();
4423 std::string info = myImpl->FileInfoToString();
4424 if ( !info.empty() )
4426 aSize[ 0 ] = info.size();
4427 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4428 aDataset->CreateOnDisk();
4429 aDataset->WriteOnDisk( (char*) info.data() );
4430 aDataset->CloseOnDisk();
4433 // write applied hypotheses if exist
4434 SALOMEDS::SObject_wrap myHypBranch;
4435 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4436 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4437 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4439 if ( found && (shapeRefFound || !hasShape) ) {
4440 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4441 aGroup->CreateOnDisk();
4443 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4445 for ( ; it->More(); it->Next() ) {
4446 SALOMEDS::SObject_wrap mySObject = it->Value();
4447 SALOMEDS::SObject_wrap myRefOnHyp;
4448 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4450 // san - it is impossible to recover applied hypotheses
4451 // using their entries within Load() method,
4452 // for there are no AttributeIORs in the study when Load() is working.
4453 // Hence, it is better to store persistent IDs of hypotheses as references to them
4455 //string myRefOnObject = myRefOnHyp->GetID();
4456 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4457 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4458 int id = myStudyContext->findId( string( objStr.in() ) );
4459 //if ( myRefOnObject.length() > 0 ) {
4460 //aSize[ 0 ] = myRefOnObject.length() + 1;
4461 char hypName[ 30 ], hypId[ 30 ];
4462 sprintf( hypName, "Hyp %d", ++hypNb );
4463 sprintf( hypId, "%d", id );
4464 aSize[ 0 ] = strlen( hypId ) + 1;
4465 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4466 aDataset->CreateOnDisk();
4467 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4468 aDataset->WriteOnDisk( hypId );
4469 aDataset->CloseOnDisk();
4473 aGroup->CloseOnDisk();
4476 // write applied algorithms if exist
4477 SALOMEDS::SObject_wrap myAlgoBranch;
4478 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4479 myAlgoBranch.inout() );
4480 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4481 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4483 if ( found && (shapeRefFound || !hasShape)) {
4484 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4485 aGroup->CreateOnDisk();
4487 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4489 for ( ; it->More(); it->Next() ) {
4490 SALOMEDS::SObject_wrap mySObject = it->Value();
4491 SALOMEDS::SObject_wrap myRefOnAlgo;
4492 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4494 // san - it is impossible to recover applied algorithms
4495 // using their entries within Load() method,
4496 // for there are no AttributeIORs in the study when Load() is working.
4497 // Hence, it is better to store persistent IDs of algorithms as references to them
4499 //string myRefOnObject = myRefOnAlgo->GetID();
4500 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4501 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4502 int id = myStudyContext->findId( string( objStr.in() ) );
4503 //if ( myRefOnObject.length() > 0 ) {
4504 //aSize[ 0 ] = myRefOnObject.length() + 1;
4505 char algoName[ 30 ], algoId[ 30 ];
4506 sprintf( algoName, "Algo %d", ++algoNb );
4507 sprintf( algoId, "%d", id );
4508 aSize[ 0 ] = strlen( algoId ) + 1;
4509 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4510 aDataset->CreateOnDisk();
4511 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4512 aDataset->WriteOnDisk( algoId );
4513 aDataset->CloseOnDisk();
4517 aGroup->CloseOnDisk();
4520 // --> submesh objects sub-branches
4522 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4523 SALOMEDS::SObject_wrap mySubmeshBranch;
4524 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4526 if ( found ) // check if there is shape reference in submeshes
4528 bool hasShapeRef = false;
4529 SALOMEDS::ChildIterator_wrap itSM =
4530 aStudy->NewChildIterator( mySubmeshBranch );
4531 for ( ; itSM->More(); itSM->Next() ) {
4532 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4533 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4534 mySubRef->ReferencedObject( myShape.inout() );
4535 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4538 { // remove one submesh
4539 if ( shapeRefFound )
4540 { // unassign hypothesis
4541 SMESH::SMESH_subMesh_var mySubMesh =
4542 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4543 if ( !mySubMesh->_is_nil() ) {
4544 int shapeID = mySubMesh->GetId();
4545 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4546 const list<const SMESHDS_Hypothesis*>& hypList =
4547 mySMESHDSMesh->GetHypothesis( S );
4548 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4549 while ( hyp != hypList.end() ) {
4550 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4551 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4555 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4557 } // loop on submeshes of a type
4558 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4559 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4562 } // end check if there is shape reference in submeshes
4564 char name_meshgroup[ 30 ];
4565 if ( i == GetSubMeshOnVertexTag() )
4566 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4567 else if ( i == GetSubMeshOnEdgeTag() )
4568 strcpy( name_meshgroup, "SubMeshes On Edge" );
4569 else if ( i == GetSubMeshOnWireTag() )
4570 strcpy( name_meshgroup, "SubMeshes On Wire" );
4571 else if ( i == GetSubMeshOnFaceTag() )
4572 strcpy( name_meshgroup, "SubMeshes On Face" );
4573 else if ( i == GetSubMeshOnShellTag() )
4574 strcpy( name_meshgroup, "SubMeshes On Shell" );
4575 else if ( i == GetSubMeshOnSolidTag() )
4576 strcpy( name_meshgroup, "SubMeshes On Solid" );
4577 else if ( i == GetSubMeshOnCompoundTag() )
4578 strcpy( name_meshgroup, "SubMeshes On Compound" );
4580 // for each type of submeshes create container HDF group
4581 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4582 aGroup->CreateOnDisk();
4584 // iterator for all submeshes of given type
4585 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4586 for ( ; itSM->More(); itSM->Next() ) {
4587 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4588 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4589 if ( !CORBA::is_nil( anSubObject ))
4591 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4592 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4593 int subid = myStudyContext->findId( string( objStr.in() ) );
4595 // for each mesh open the HDF group basing on its id
4596 char submeshGrpName[ 30 ];
4597 sprintf( submeshGrpName, "SubMesh %d", subid );
4598 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4599 aSubGroup->CreateOnDisk();
4601 // write reference on a shape, already checked if it exists
4602 SALOMEDS::SObject_wrap mySubRef, myShape;
4603 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4604 mySubRef->ReferencedObject( myShape.inout() );
4605 string myRefOnObject = myShape->GetID();
4606 if ( myRefOnObject.length() > 0 ) {
4607 aSize[ 0 ] = myRefOnObject.length() + 1;
4608 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4609 aDataset->CreateOnDisk();
4610 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4611 aDataset->CloseOnDisk();
4614 // write applied hypotheses if exist
4615 SALOMEDS::SObject_wrap mySubHypBranch;
4616 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4617 mySubHypBranch.inout() );
4619 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4620 aSubSubGroup->CreateOnDisk();
4622 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4624 for ( ; it->More(); it->Next() ) {
4625 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4626 SALOMEDS::SObject_wrap myRefOnHyp;
4627 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4629 //string myRefOnObject = myRefOnHyp->GetID();
4630 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4631 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4632 int id = myStudyContext->findId( string( objStr.in() ) );
4633 //if ( myRefOnObject.length() > 0 ) {
4634 //aSize[ 0 ] = myRefOnObject.length() + 1;
4635 char hypName[ 30 ], hypId[ 30 ];
4636 sprintf( hypName, "Hyp %d", ++hypNb );
4637 sprintf( hypId, "%d", id );
4638 aSize[ 0 ] = strlen( hypId ) + 1;
4639 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4640 aDataset->CreateOnDisk();
4641 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4642 aDataset->WriteOnDisk( hypId );
4643 aDataset->CloseOnDisk();
4647 aSubSubGroup->CloseOnDisk();
4650 // write applied algorithms if exist
4651 SALOMEDS::SObject_wrap mySubAlgoBranch;
4652 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4653 mySubAlgoBranch.inout() );
4655 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4656 aSubSubGroup->CreateOnDisk();
4658 SALOMEDS::ChildIterator_wrap it =
4659 aStudy->NewChildIterator( mySubAlgoBranch );
4661 for ( ; it->More(); it->Next() ) {
4662 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4663 SALOMEDS::SObject_wrap myRefOnAlgo;
4664 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4666 //string myRefOnObject = myRefOnAlgo->GetID();
4667 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4668 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4669 int id = myStudyContext->findId( string( objStr.in() ) );
4670 //if ( myRefOnObject.length() > 0 ) {
4671 //aSize[ 0 ] = myRefOnObject.length() + 1;
4672 char algoName[ 30 ], algoId[ 30 ];
4673 sprintf( algoName, "Algo %d", ++algoNb );
4674 sprintf( algoId, "%d", id );
4675 aSize[ 0 ] = strlen( algoId ) + 1;
4676 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4677 aDataset->CreateOnDisk();
4678 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4679 aDataset->WriteOnDisk( algoId );
4680 aDataset->CloseOnDisk();
4684 aSubSubGroup->CloseOnDisk();
4686 // close submesh HDF group
4687 aSubGroup->CloseOnDisk();
4690 // close container of submeshes by type HDF group
4691 aGroup->CloseOnDisk();
4695 // store submesh order if any
4696 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4697 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4698 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4699 char order_list[ 30 ];
4700 strcpy( order_list, "Mesh Order" );
4701 // count number of submesh ids
4703 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4704 for ( ; idIt != theOrderIds.end(); idIt++ )
4705 nbIDs += (*idIt).size();
4706 // number of values = number of IDs +
4707 // number of lists (for separators) - 1
4708 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4709 idIt = theOrderIds.begin();
4710 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4711 const TListOfInt& idList = *idIt;
4712 if (idIt != theOrderIds.begin()) // not first list
4713 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4714 // dump submesh ids from current list
4715 TListOfInt::const_iterator id_smId = idList.begin();
4716 for( ; id_smId != idList.end(); id_smId++ )
4717 smIDs[ i++ ] = *id_smId;
4720 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4722 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4723 aDataset->CreateOnDisk();
4724 aDataset->WriteOnDisk( smIDs );
4725 aDataset->CloseOnDisk();
4729 if ( !theOrderIds.empty() && isNewOrederVersion )
4731 // convert ids to entries
4732 std::list< std::list< std::string > > orderEntryLists;
4733 for ( const TListOfInt& idList : theOrderIds )
4735 orderEntryLists.emplace_back();
4736 std::list< std::string > & entryList = orderEntryLists.back();
4737 for ( const int& id : idList )
4739 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4740 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4741 SALOMEDS::SObject_var so = ObjectToSObject( go );
4742 if ( !so->_is_nil() )
4744 CORBA::String_var entry = so->GetID();
4745 entryList.emplace_back( entry.in() );
4749 // convert orderEntryLists to string
4750 std::ostringstream ostream;
4751 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4752 std::string orderEntryString = ostream.str();
4755 aSize[ 0 ] = orderEntryString.size() + 1;
4756 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4757 aDataset->CreateOnDisk();
4758 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4759 aDataset->CloseOnDisk();
4762 // groups root sub-branch
4763 SALOMEDS::SObject_wrap myGroupsBranch;
4764 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4765 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4767 char name_group[ 30 ];
4768 if ( i == GetNodeGroupsTag() )
4769 strcpy( name_group, "Groups of Nodes" );
4770 else if ( i == GetEdgeGroupsTag() )
4771 strcpy( name_group, "Groups of Edges" );
4772 else if ( i == GetFaceGroupsTag() )
4773 strcpy( name_group, "Groups of Faces" );
4774 else if ( i == GetVolumeGroupsTag() )
4775 strcpy( name_group, "Groups of Volumes" );
4776 else if ( i == Get0DElementsGroupsTag() )
4777 strcpy( name_group, "Groups of 0D Elements" );
4778 else if ( i == GetBallElementsGroupsTag() )
4779 strcpy( name_group, "Groups of Balls" );
4781 aGroup = new HDFgroup( name_group, aTopGroup );
4782 aGroup->CreateOnDisk();
4784 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4785 for ( ; it->More(); it->Next() ) {
4786 SALOMEDS::SObject_wrap mySObject = it->Value();
4787 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4788 if ( !CORBA::is_nil( aSubObject ) ) {
4789 SMESH_GroupBase_i* myGroupImpl =
4790 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4793 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4797 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4798 int anId = myStudyContext->findId( string( objStr.in() ) );
4800 // For each group, create a dataset named "Group <group_persistent_id>"
4801 // and store the group's user name into it
4802 const char* grpName = aGrpBaseDS->GetStoreName();
4803 CORBA::String_var aUserName = myGroupImpl->GetName();
4804 aSize[ 0 ] = strlen( aUserName ) + 1;
4806 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4807 aDataset->CreateOnDisk();
4808 aDataset->WriteOnDisk( aUserName );
4809 aDataset->CloseOnDisk();
4812 // For each group, create a dataset named "Group <group_persistent_id> Color"
4813 // and store the group's color into it
4814 char grpColorName[ 30 ];
4815 sprintf( grpColorName, "ColorGroup %d", anId );
4816 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4818 anRGB[ 0 ] = aColor.R;
4819 anRGB[ 1 ] = aColor.G;
4820 anRGB[ 2 ] = aColor.B;
4822 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4823 aDataset->CreateOnDisk();
4824 aDataset->WriteOnDisk( anRGB );
4825 aDataset->CloseOnDisk();
4827 // Pass SMESHDS_Group to MED writer
4828 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4830 writer.AddGroup( aGrpDS );
4832 // write reference on a shape if exists
4833 SMESHDS_GroupOnGeom* aGeomGrp =
4834 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4836 SALOMEDS::SObject_wrap mySubRef, myShape;
4837 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4838 mySubRef->ReferencedObject( myShape.inout() ) &&
4839 !CORBA::is_nil( myShape->GetObject() ))
4841 CORBA::String_var myRefOnObject = myShape->GetID();
4842 if ( myRefOnObject.in()[0] ) {
4843 char aRefName[ 30 ];
4844 sprintf( aRefName, "Ref on shape %d", anId);
4845 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4846 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4847 aDataset->CreateOnDisk();
4848 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4849 aDataset->CloseOnDisk();
4852 else // shape ref is invalid:
4854 // save a group on geometry as ordinary group
4855 writer.AddGroup( aGeomGrp );
4858 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4859 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4861 std::string str = aFilterGrp_i->FilterToString();
4862 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4863 aSize[ 0 ] = str.length() + 1;
4864 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4865 aDataset->CreateOnDisk();
4866 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4867 aDataset->CloseOnDisk();
4871 aGroup->CloseOnDisk();
4875 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4877 // Flush current mesh information into MED file
4880 // save info on nb of elements
4881 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4883 // maybe a shape was deleted in the study
4884 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4885 TopoDS_Shape nullShape;
4886 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4889 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4894 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4895 aGroup->CreateOnDisk();
4897 // each element belongs to one or none submesh,
4898 // so for each node/element, we store a submesh ID
4900 // Store submesh IDs
4901 for ( int isNode = 0; isNode < 2; ++isNode )
4903 SMDS_ElemIteratorPtr eIt =
4904 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4905 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4908 std::vector<int> smIDs; smIDs.reserve( nbElems );
4909 while ( eIt->more() )
4910 if ( const SMDS_MeshElement* e = eIt->next())
4911 smIDs.push_back( e->getshapeId() );
4913 aSize[ 0 ] = nbElems;
4914 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4915 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4916 aDataset->CreateOnDisk();
4917 aDataset->WriteOnDisk( & smIDs[0] );
4918 aDataset->CloseOnDisk();
4921 aGroup->CloseOnDisk();
4923 // Store node positions on sub-shapes (SMDS_Position):
4924 // ----------------------------------------------------
4926 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4927 aGroup->CreateOnDisk();
4929 // in aGroup, create 5 datasets to contain:
4930 // "Nodes on Edges" - ID of node on edge
4931 // "Edge positions" - U parameter on node on edge
4932 // "Nodes on Faces" - ID of node on face
4933 // "Face U positions" - U parameter of node on face
4934 // "Face V positions" - V parameter of node on face
4936 // Find out nb of nodes on edges and faces
4937 // Collect corresponding sub-meshes
4938 int nbEdgeNodes = 0, nbFaceNodes = 0;
4939 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4940 // loop on SMESHDS_SubMesh'es
4941 while ( smIt->more() )
4943 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4944 if ( aSubMesh->IsComplexSubmesh() )
4945 continue; // submesh containing other submeshs
4946 smIdType nbNodes = aSubMesh->NbNodes();
4947 if ( nbNodes == 0 ) continue;
4949 int aShapeID = aSubMesh->GetID();
4950 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4952 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4953 // write only SMDS_FacePosition and SMDS_EdgePosition
4954 switch ( aShapeType ) {
4956 nbFaceNodes += nbNodes;
4957 aFaceSM.push_back( aSubMesh );
4960 nbEdgeNodes += nbNodes;
4961 aEdgeSM.push_back( aSubMesh );
4967 // Treat positions on edges or faces
4968 for ( int onFace = 0; onFace < 2; onFace++ )
4970 // Create arrays to store in datasets
4971 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4972 if (!nbNodes) continue;
4973 int* aNodeIDs = new int [ nbNodes ];
4974 double* aUPos = new double [ nbNodes ];
4975 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4978 // loop on sub-meshes
4979 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4980 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4981 for ( ; itSM != pListSM->end(); itSM++ )
4983 SMESHDS_SubMesh* aSubMesh = (*itSM);
4985 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4986 // loop on nodes in aSubMesh
4987 while ( itNode->more() )
4990 const SMDS_MeshNode* node = itNode->next();
4991 aNodeIDs [ iNode ] = node->GetID();
4994 const SMDS_PositionPtr pos = node->GetPosition();
4995 if ( onFace ) { // on FACE
4996 SMDS_FacePositionPtr fPos = pos;
4998 aUPos[ iNode ] = fPos->GetUParameter();
4999 aVPos[ iNode ] = fPos->GetVParameter();
5006 SMDS_EdgePositionPtr ePos = pos;
5008 aUPos[ iNode ] = ePos->GetUParameter();
5014 } // loop on nodes in aSubMesh
5015 } // loop on sub-meshes
5020 aSize[ 0 ] = nbNodes;
5022 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5023 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5024 aDataset->CreateOnDisk();
5025 aDataset->WriteOnDisk( aNodeIDs );
5026 aDataset->CloseOnDisk();
5029 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5030 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5031 aDataset->CreateOnDisk();
5032 aDataset->WriteOnDisk( aUPos );
5033 aDataset->CloseOnDisk();
5036 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5037 aDataset->CreateOnDisk();
5038 aDataset->WriteOnDisk( aVPos );
5039 aDataset->CloseOnDisk();
5044 if ( aVPos ) delete [] aVPos;
5046 } // treat positions on edges or faces
5048 // close "Node Positions" group
5049 aGroup->CloseOnDisk();
5051 } // if ( there are submeshes in SMESHDS_Mesh )
5054 // close mesh HDF group
5055 aTopGroup->CloseOnDisk();
5063 aFile->CloseOnDisk();
5066 // Convert temporary files to stream
5067 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5069 // Remove temporary files and directory
5071 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5073 return aStreamFile._retn();
5076 //=============================================================================
5078 * SMESH_Gen_i::SaveASCII
5080 * Save SMESH module's data in ASCII format
5082 //=============================================================================
5084 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5086 bool isMultiFile ) {
5087 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5088 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5089 return aStreamFile._retn();
5091 //after usual saving needs to encipher binary to text string
5092 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5093 int size = aStreamFile.in().length();
5094 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5095 for ( int i = 0; i < size; i++ )
5096 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5098 buffer[size * 3] = '\0';
5100 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5102 return anAsciiStreamFile._retn();
5105 //=============================================================================
5109 * Load SMESH module's data
5111 //=============================================================================
5113 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5114 const SALOMEDS::TMPFile& theStream,
5118 UpdateStudy(); // load geom data
5119 Kernel_Utils::Localizer loc;
5121 SALOMEDS::Study_var aStudy = getStudyServant();
5123 // Get temporary files location
5124 TCollection_AsciiString tmpDir =
5125 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5127 // Convert the stream into sequence of files to process
5128 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5131 TCollection_AsciiString aStudyName( "" );
5132 if ( isMultiFile ) {
5133 CORBA::WString_var url = aStudy->URL();
5134 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5135 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5137 // Set names of temporary files
5138 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5139 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5143 HDFdataset* aDataset;
5144 HDFgroup* aTopGroup;
5146 HDFgroup* aSubGroup;
5147 HDFgroup* aSubSubGroup;
5150 // ---> open HDF file
5151 aFile = new HDFfile( (char*) filename.ToCString() );
5153 aFile->OpenOnDisk( HDF_RDONLY );
5155 catch ( HDFexception ) {
5156 INFOS( "Load(): " << filename << " not found!" );
5160 TPythonDump pd(this); // prevent dump during loading
5162 // For PAL13473 ("Repetitive mesh") implementation.
5163 // New dependencies between SMESH objects are established:
5164 // now hypotheses can refer to meshes, shapes and other hypotheses.
5165 // To keep data consistent, the following order of data restoration
5167 // 1. Create hypotheses
5168 // 2. Create all meshes
5169 // 3. Load hypotheses' data
5172 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5173 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5174 list< SMESH::Filter_var > filters;
5176 // get total number of top-level groups
5177 int aNbGroups = aFile->nInternalObjects();
5178 if ( aNbGroups > 0 ) {
5179 // --> in first turn we should read&create hypotheses
5180 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5181 // open hypotheses root HDF group
5182 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5183 aTopGroup->OpenOnDisk();
5185 // get number of hypotheses
5186 int aNbObjects = aTopGroup->nInternalObjects();
5187 for ( int j = 0; j < aNbObjects; j++ ) {
5188 // try to identify hypothesis
5189 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5190 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5192 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5193 // open hypothesis group
5194 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5195 aGroup->OpenOnDisk();
5197 // --> get hypothesis id
5198 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5203 // get number of datasets
5204 int aNbSubObjects = aGroup->nInternalObjects();
5205 for ( int k = 0; k < aNbSubObjects; k++ ) {
5207 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5208 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5209 // --> get hypothesis name
5210 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5211 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5212 aDataset->OpenOnDisk();
5213 size = aDataset->GetSize();
5214 char* hypname_str = new char[ size ];
5215 aDataset->ReadFromDisk( hypname_str );
5216 hypname = string( hypname_str );
5217 delete [] hypname_str;
5218 aDataset->CloseOnDisk();
5220 // --> get hypothesis plugin library name
5221 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5222 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5223 aDataset->OpenOnDisk();
5224 size = aDataset->GetSize();
5225 char* libname_str = new char[ size ];
5226 aDataset->ReadFromDisk( libname_str );
5227 if(MYDEBUG) SCRUTE( libname_str );
5228 libname = string( libname_str );
5229 delete [] libname_str;
5230 aDataset->CloseOnDisk();
5232 // --> get hypothesis data
5233 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5234 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5235 aDataset->OpenOnDisk();
5236 size = aDataset->GetSize();
5237 char* hypdata_str = new char[ size ];
5238 aDataset->ReadFromDisk( hypdata_str );
5239 hypdata = string( hypdata_str );
5240 delete [] hypdata_str;
5241 aDataset->CloseOnDisk();
5244 // close hypothesis HDF group
5245 aGroup->CloseOnDisk();
5247 // --> restore hypothesis from data
5248 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5249 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5250 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5251 SMESH::SMESH_Hypothesis_var myHyp;
5253 try { // protect persistence mechanism against exceptions
5254 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5257 INFOS( "Exception during hypothesis creation" );
5260 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5262 // myImpl->LoadFrom( hypdata.c_str() );
5263 hypDataList.push_back( make_pair( myImpl, hypdata ));
5264 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5265 int newId = myStudyContext->findId( iorString.in() );
5266 myStudyContext->mapOldToNew( id, newId );
5269 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5273 // close hypotheses root HDF group
5274 aTopGroup->CloseOnDisk();
5278 // --> then we should read&create algorithms
5279 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5280 // open algorithms root HDF group
5281 aTopGroup = new HDFgroup( "Algorithms", aFile );
5282 aTopGroup->OpenOnDisk();
5284 // get number of algorithms
5285 int aNbObjects = aTopGroup->nInternalObjects();
5286 for ( int j = 0; j < aNbObjects; j++ ) {
5287 // try to identify algorithm
5288 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5289 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5291 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5292 // open algorithm group
5293 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5294 aGroup->OpenOnDisk();
5296 // --> get algorithm id
5297 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5302 // get number of datasets
5303 int aNbSubObjects = aGroup->nInternalObjects();
5304 for ( int k = 0; k < aNbSubObjects; k++ ) {
5306 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5307 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5308 // --> get algorithm name
5309 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5310 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5311 aDataset->OpenOnDisk();
5312 size = aDataset->GetSize();
5313 char* hypname_str = new char[ size ];
5314 aDataset->ReadFromDisk( hypname_str );
5315 hypname = string( hypname_str );
5316 delete [] hypname_str;
5317 aDataset->CloseOnDisk();
5319 // --> get algorithm plugin library name
5320 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5321 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5322 aDataset->OpenOnDisk();
5323 size = aDataset->GetSize();
5324 char* libname_str = new char[ size ];
5325 aDataset->ReadFromDisk( libname_str );
5326 if(MYDEBUG) SCRUTE( libname_str );
5327 libname = string( libname_str );
5328 delete [] libname_str;
5329 aDataset->CloseOnDisk();
5331 // --> get algorithm data
5332 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5333 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5334 aDataset->OpenOnDisk();
5335 size = aDataset->GetSize();
5336 char* hypdata_str = new char[ size ];
5337 aDataset->ReadFromDisk( hypdata_str );
5338 if(MYDEBUG) SCRUTE( hypdata_str );
5339 hypdata = string( hypdata_str );
5340 delete [] hypdata_str;
5341 aDataset->CloseOnDisk();
5344 // close algorithm HDF group
5345 aGroup->CloseOnDisk();
5347 // --> restore algorithm from data
5348 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5349 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5350 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5351 SMESH::SMESH_Hypothesis_var myHyp;
5353 try { // protect persistence mechanism against exceptions
5354 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5356 catch( SALOME::SALOME_Exception& ex )
5358 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5361 INFOS( "Exception during hypothesis creation" );
5364 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5366 //myImpl->LoadFrom( hypdata.c_str() );
5367 hypDataList.push_back( make_pair( myImpl, hypdata ));
5368 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5369 int newId = myStudyContext->findId( iorString.in() );
5370 myStudyContext->mapOldToNew( id, newId );
5373 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5377 // close algorithms root HDF group
5378 aTopGroup->CloseOnDisk();
5382 // --> the rest groups should be meshes
5383 for ( int i = 0; i < aNbGroups; i++ ) {
5384 // identify next group
5385 char meshName[ HDF_NAME_MAX_LEN+1 ];
5386 aFile->InternalObjectIndentify( i, meshName );
5388 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5390 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5394 // open mesh HDF group
5395 aTopGroup = new HDFgroup( meshName, aFile );
5396 aTopGroup->OpenOnDisk();
5398 // get number of child HDF objects
5399 int aNbObjects = aTopGroup->nInternalObjects();
5400 if ( aNbObjects > 0 ) {
5402 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5403 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5404 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5405 if ( !myNewMeshImpl )
5407 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5409 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5410 int newId = myStudyContext->findId( iorString.in() );
5411 myStudyContext->mapOldToNew( id, newId );
5414 // try to read and set auto color flag
5415 char aMeshAutoColorName[ 30 ];
5416 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5417 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5419 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5420 aDataset->OpenOnDisk();
5421 size = aDataset->GetSize();
5422 int* anAutoColor = new int[ size ];
5423 aDataset->ReadFromDisk( anAutoColor );
5424 aDataset->CloseOnDisk();
5425 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5426 delete [] anAutoColor;
5429 // try to read and set reference to shape
5430 GEOM::GEOM_Object_var aShapeObject;
5431 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5432 // load mesh "Ref on shape" - it's an entry to SObject
5433 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5434 aDataset->OpenOnDisk();
5435 size = aDataset->GetSize();
5436 char* refFromFile = new char[ size ];
5437 aDataset->ReadFromDisk( refFromFile );
5438 aDataset->CloseOnDisk();
5439 if ( strlen( refFromFile ) > 0 ) {
5440 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5441 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5442 if ( !CORBA::is_nil( shapeObject ) ) {
5443 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5444 if ( !aShapeObject->_is_nil() )
5445 myNewMeshImpl->SetShape( aShapeObject );
5448 delete [] refFromFile;
5451 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5452 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5454 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5455 aDataset->OpenOnDisk();
5456 size = aDataset->GetSize();
5457 int* meshPersistentId = new int[ size ];
5458 aDataset->ReadFromDisk( meshPersistentId );
5459 aDataset->CloseOnDisk();
5460 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5461 delete [] meshPersistentId;
5464 // Restore SMESH_Mesh_i::_mainShapeTick
5465 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5467 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5468 aDataset->OpenOnDisk();
5469 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5470 aDataset->ReadFromDisk( shapeTick );
5471 aDataset->CloseOnDisk();
5474 // Restore file info
5475 if ( aTopGroup->ExistInternalObject( "file info" ))
5477 aDataset = new HDFdataset( "file info", aTopGroup );
5478 aDataset->OpenOnDisk();
5479 size = aDataset->GetSize();
5480 std::string info( size, ' ');
5481 aDataset->ReadFromDisk( (char*) info.data() );
5482 aDataset->CloseOnDisk();
5483 myNewMeshImpl->FileInfoFromString( info );
5489 // As all objects that can be referred by hypothesis are created,
5490 // we can restore hypothesis data
5492 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5493 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5495 SMESH_Hypothesis_i* hyp = hyp_data->first;
5496 string & data = hyp_data->second;
5497 hyp->LoadFrom( data.c_str() );
5500 // Restore the rest mesh data
5502 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5503 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5505 aTopGroup = meshi_group->second;
5506 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5508 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5509 bool hasData = false;
5512 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5513 int newId = myStudyContext->findId( iorString.in() );
5514 int meshOldId = myStudyContext->getOldId( newId );
5516 // try to find mesh data dataset
5517 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5518 // load mesh "has data" flag
5519 aDataset = new HDFdataset( "Has data", aTopGroup );
5520 aDataset->OpenOnDisk();
5521 size = aDataset->GetSize();
5522 char* strHasData = new char[ size ];
5523 aDataset->ReadFromDisk( strHasData );
5524 aDataset->CloseOnDisk();
5525 if ( strcmp( strHasData, "1") == 0 ) {
5528 delete [] strHasData;
5531 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5532 // nodes and elements are not yet put into sub-meshes)
5533 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5534 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5535 aGroup->OpenOnDisk();
5536 // get number of applied algorithms
5537 int aNbSubObjects = aGroup->nInternalObjects();
5538 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5539 for ( int j = 0; j < aNbSubObjects; j++ ) {
5540 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5541 aGroup->InternalObjectIndentify( j, name_dataset );
5542 // check if it is an algorithm
5543 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5544 aDataset = new HDFdataset( name_dataset, aGroup );
5545 aDataset->OpenOnDisk();
5546 size = aDataset->GetSize();
5547 char* refFromFile = new char[ size ];
5548 aDataset->ReadFromDisk( refFromFile );
5549 aDataset->CloseOnDisk();
5550 // san - it is impossible to recover applied algorithms using their entries within Load() method
5551 int id = atoi( refFromFile );
5552 delete [] refFromFile;
5553 string anIOR = myStudyContext->getIORbyOldId( id );
5554 if ( !anIOR.empty() ) {
5555 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5556 if ( !CORBA::is_nil( hypObject ) ) {
5557 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5558 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5559 || !myNewMeshImpl->HasShapeToMesh()) )
5560 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5565 aGroup->CloseOnDisk();
5568 // try to get applied hypotheses
5569 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5570 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5571 aGroup->OpenOnDisk();
5572 // get number of applied hypotheses
5573 int aNbSubObjects = aGroup->nInternalObjects();
5574 for ( int j = 0; j < aNbSubObjects; j++ ) {
5575 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5576 aGroup->InternalObjectIndentify( j, name_dataset );
5577 // check if it is a hypothesis
5578 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5579 aDataset = new HDFdataset( name_dataset, aGroup );
5580 aDataset->OpenOnDisk();
5581 size = aDataset->GetSize();
5582 char* refFromFile = new char[ size ];
5583 aDataset->ReadFromDisk( refFromFile );
5584 aDataset->CloseOnDisk();
5585 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5586 int id = atoi( refFromFile );
5587 delete [] refFromFile;
5588 string anIOR = myStudyContext->getIORbyOldId( id );
5589 if ( !anIOR.empty() ) {
5590 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5591 if ( !CORBA::is_nil( hypObject ) ) {
5592 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5593 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5594 || !myNewMeshImpl->HasShapeToMesh()) )
5595 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5600 aGroup->CloseOnDisk();
5603 // --> try to find SUB-MESHES containers for each type of submesh
5604 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5605 const char* name_meshgroup = 0;
5606 if ( j == GetSubMeshOnVertexTag() )
5607 name_meshgroup = "SubMeshes On Vertex";
5608 else if ( j == GetSubMeshOnEdgeTag() )
5609 name_meshgroup = "SubMeshes On Edge";
5610 else if ( j == GetSubMeshOnWireTag() )
5611 name_meshgroup = "SubMeshes On Wire";
5612 else if ( j == GetSubMeshOnFaceTag() )
5613 name_meshgroup = "SubMeshes On Face";
5614 else if ( j == GetSubMeshOnShellTag() )
5615 name_meshgroup = "SubMeshes On Shell";
5616 else if ( j == GetSubMeshOnSolidTag() )
5617 name_meshgroup = "SubMeshes On Solid";
5618 else if ( j == GetSubMeshOnCompoundTag() )
5619 name_meshgroup = "SubMeshes On Compound";
5621 // try to get submeshes container HDF group
5622 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5623 // open submeshes containers HDF group
5624 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5625 aGroup->OpenOnDisk();
5627 // get number of submeshes
5628 int aNbSubMeshes = aGroup->nInternalObjects();
5629 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5631 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5632 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5633 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5634 // --> get submesh id
5635 int subid = atoi( name_submeshgroup + 7 );
5638 // open submesh HDF group
5639 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5640 aSubGroup->OpenOnDisk();
5642 // try to read and set reference to subshape
5643 GEOM::GEOM_Object_var aSubShapeObject;
5644 SMESH::SMESH_subMesh_var aSubMesh;
5646 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5647 // load submesh "Ref on shape" - it's an entry to SObject
5648 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5649 aDataset->OpenOnDisk();
5650 size = aDataset->GetSize();
5651 char* refFromFile = new char[ size ];
5652 aDataset->ReadFromDisk( refFromFile );
5653 aDataset->CloseOnDisk();
5654 if ( strlen( refFromFile ) > 0 ) {
5655 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5656 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5657 if ( !CORBA::is_nil( subShapeObject ) ) {
5658 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5659 if ( !aSubShapeObject->_is_nil() )
5660 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5661 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5662 if ( aSubMesh->_is_nil() )
5664 string iorSubString = GetORB()->object_to_string( aSubMesh );
5665 int newSubId = myStudyContext->findId( iorSubString );
5666 myStudyContext->mapOldToNew( subid, newSubId );
5669 delete [] refFromFile;
5672 if ( aSubMesh->_is_nil() )
5675 // try to get applied algorithms
5676 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5677 // open "applied algorithms" HDF group
5678 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5679 aSubSubGroup->OpenOnDisk();
5680 // get number of applied algorithms
5681 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5682 for ( int l = 0; l < aNbSubObjects; l++ ) {
5683 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5684 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5685 // check if it is an algorithm
5686 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5687 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5688 aDataset->OpenOnDisk();
5689 size = aDataset->GetSize();
5690 char* refFromFile = new char[ size ];
5691 aDataset->ReadFromDisk( refFromFile );
5692 aDataset->CloseOnDisk();
5694 int id = atoi( refFromFile );
5695 string anIOR = myStudyContext->getIORbyOldId( id );
5696 if ( !anIOR.empty() ) {
5697 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5698 if ( !CORBA::is_nil( hypObject ) ) {
5699 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5700 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5701 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5704 delete [] refFromFile;
5707 // close "applied algorithms" HDF group
5708 aSubSubGroup->CloseOnDisk();
5711 // try to get applied hypotheses
5712 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5713 // open "applied hypotheses" HDF group
5714 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5715 aSubSubGroup->OpenOnDisk();
5716 // get number of applied hypotheses
5717 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5718 for ( int l = 0; l < aNbSubObjects; l++ ) {
5719 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5720 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5721 // check if it is a hypothesis
5722 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5723 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5724 aDataset->OpenOnDisk();
5725 size = aDataset->GetSize();
5726 char* refFromFile = new char[ size ];
5727 aDataset->ReadFromDisk( refFromFile );
5728 aDataset->CloseOnDisk();
5730 int id = atoi( refFromFile );
5731 string anIOR = myStudyContext->getIORbyOldId( id );
5732 if ( !anIOR.empty() ) {
5733 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5734 if ( !CORBA::is_nil( hypObject ) ) {
5735 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5736 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5737 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5740 delete [] refFromFile;
5743 // close "APPLIED HYPOTHESES" hdf group
5744 aSubSubGroup->CloseOnDisk();
5747 // close SUB-MESH hdf group
5748 aSubGroup->CloseOnDisk();
5751 // close SUB-MESHES containers hdf group
5752 aGroup->CloseOnDisk();
5756 // try to get GROUPS
5757 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5758 char name_group[ 30 ];
5759 if ( ii == GetNodeGroupsTag() )
5760 strcpy( name_group, "Groups of Nodes" );
5761 else if ( ii == GetEdgeGroupsTag() )
5762 strcpy( name_group, "Groups of Edges" );
5763 else if ( ii == GetFaceGroupsTag() )
5764 strcpy( name_group, "Groups of Faces" );
5765 else if ( ii == GetVolumeGroupsTag() )
5766 strcpy( name_group, "Groups of Volumes" );
5767 else if ( ii == Get0DElementsGroupsTag() )
5768 strcpy( name_group, "Groups of 0D Elements" );
5769 else if ( ii == GetBallElementsGroupsTag() )
5770 strcpy( name_group, "Groups of Balls" );
5772 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5773 aGroup = new HDFgroup( name_group, aTopGroup );
5774 aGroup->OpenOnDisk();
5775 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5776 // within aGroup->ExistInternalObject( name )
5777 std::vector< std::string > subNames;
5778 TColStd_MapOfAsciiString mapOfNames;
5779 aGroup->GetAllObjects( subNames );
5780 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5781 mapOfNames.Add( subNames[ iN ].c_str() );
5783 for ( size_t j = 0; j < subNames.size(); j++ ) {
5784 const std::string& name_dataset = subNames[ j ];
5785 // check if it is a group
5786 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5789 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5792 int groupID = -1; // group local ID (also persistent)
5794 groupID = atoi( endptr + 1 );
5795 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5796 aDataset->OpenOnDisk();
5798 // Retrieve actual group name
5799 size = aDataset->GetSize();
5800 char* nameFromFile = new char[ size ];
5801 aDataset->ReadFromDisk( nameFromFile );
5802 aDataset->CloseOnDisk();
5804 // Try to find a shape reference
5805 TopoDS_Shape aShape;
5806 char aRefName[ 30 ];
5807 sprintf( aRefName, "Ref on shape %d", subid);
5808 if ( mapOfNames.Contains( aRefName ))
5810 // load mesh "Ref on shape" - it's an entry to SObject
5811 aDataset = new HDFdataset( aRefName, aGroup );
5812 aDataset->OpenOnDisk();
5813 size = aDataset->GetSize();
5814 char* refFromFile = new char[ size ];
5815 aDataset->ReadFromDisk( refFromFile );
5816 aDataset->CloseOnDisk();
5817 if ( strlen( refFromFile ) > 0 ) {
5818 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5819 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5820 if ( !CORBA::is_nil( shapeObject ) ) {
5821 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5822 if ( !aShapeObject->_is_nil() )
5823 aShape = GeomObjectToShape( aShapeObject );
5826 delete [] refFromFile;
5828 // Try to read a filter of SMESH_GroupOnFilter
5829 SMESH::Filter_var filter;
5830 SMESH_PredicatePtr predicate;
5831 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5832 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5834 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5835 aDataset->OpenOnDisk();
5836 size = aDataset->GetSize();
5837 char* persistStr = new char[ size ];
5838 aDataset->ReadFromDisk( persistStr );
5839 aDataset->CloseOnDisk();
5840 if ( strlen( persistStr ) > 0 ) {
5841 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5842 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5843 filters.push_back( filter );
5845 delete [] persistStr;
5848 // Create group servant
5849 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5850 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5851 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5852 delete [] nameFromFile;
5853 // Obtain a SMESHDS_Group object
5854 if ( aNewGroup->_is_nil() )
5857 CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
5858 string iorSubString(iorSubStringVar.in());
5859 int newSubId = myStudyContext->findId( iorSubString );
5860 myStudyContext->mapOldToNew( subid, newSubId );
5862 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5866 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5867 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5869 aFilterGroup->SetFilter( filter );
5870 filter->UnRegister();
5872 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5873 if ( !aGroupBaseDS )
5876 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5879 // Read color of the group
5880 char aGroupColorName[ 30 ];
5881 sprintf( aGroupColorName, "ColorGroup %d", subid);
5882 if ( mapOfNames.Contains( aGroupColorName ))
5884 aDataset = new HDFdataset( aGroupColorName, aGroup );
5885 aDataset->OpenOnDisk();
5886 size = aDataset->GetSize();
5887 double* anRGB = new double[ size ];
5888 aDataset->ReadFromDisk( anRGB );
5889 aDataset->CloseOnDisk();
5890 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5891 aGroupBaseDS->SetColor( aColor );
5896 aGroup->CloseOnDisk();
5900 // instead of reading mesh data, we read only brief information of all
5901 // objects: mesh, groups, sub-meshes (issue 0021208)
5904 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5905 meshfile.ToCString(), filename.ToCString(),
5909 // read Sub-Mesh ORDER if any
5910 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5911 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5912 aDataset->OpenOnDisk();
5913 size = aDataset->GetSize();
5914 int* smIDs = new int[ size ];
5915 aDataset->ReadFromDisk( smIDs );
5916 aDataset->CloseOnDisk();
5917 TListOfListOfInt anOrderIds;
5918 anOrderIds.push_back( TListOfInt() );
5919 for ( int i = 0; i < size; i++ )
5920 if ( smIDs[ i ] < 0 ) // is separator
5921 anOrderIds.push_back( TListOfInt() );
5923 anOrderIds.back().push_back(smIDs[ i ]);
5925 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5928 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5930 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5931 aDataset->OpenOnDisk();
5932 size = aDataset->GetSize();
5933 std::string dataString; dataString.resize( size );
5934 aDataset->ReadFromDisk((char*) dataString.data() );
5935 aDataset->CloseOnDisk();
5937 std::list< std::list< std::string > > orderEntryLists;
5938 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
5940 TListOfListOfInt anOrderIds;
5941 for ( const std::list< std::string >& entryList : orderEntryLists )
5943 anOrderIds.emplace_back();
5944 for ( const std::string & entry : entryList )
5946 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
5947 TopoDS_Shape shape = GeomObjectToShape( go );
5948 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
5949 anOrderIds.back().emplace_back( sm->GetId() );
5952 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5956 // update hyps needing full mesh data restored (issue 20918)
5957 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5959 SMESH_Hypothesis_i* hyp = hyp_data->first;
5960 hyp->UpdateAsMeshesRestored();
5963 // notify algos on completed restoration to set sub-mesh event listeners
5964 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5966 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5967 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5969 TopoDS_Shape myLocShape;
5970 if(myLocMesh.HasShapeToMesh())
5971 myLocShape = myLocMesh.GetShapeToMesh();
5973 myLocShape = SMESH_Mesh::PseudoShape();
5975 myLocMesh.GetSubMesh(myLocShape)->
5976 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5979 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5980 list< SMESH::Filter_var >::iterator f = filters.begin();
5981 for ( ; f != filters.end(); ++f )
5982 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5983 fi->FindBaseObjects();
5988 aTopGroup->CloseOnDisk();
5991 aFile->CloseOnDisk();
5994 // Remove temporary files created from the stream
5997 SMESH_File meshFile( meshfile.ToCString() );
5998 if ( !meshFile ) // no meshfile exists
6000 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6004 Engines::Container_var container = GetContainerRef();
6005 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6007 container_i->registerTemporaryFile( filename.ToCString() );
6008 container_i->registerTemporaryFile( meshfile.ToCString() );
6009 container_i->registerTemporaryFile( tmpDir.ToCString() );
6014 // creation of tree nodes for all data objects in the study
6015 // to support tree representation customization and drag-n-drop:
6016 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6017 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6018 useCaseBuilder->SetRootCurrent();
6019 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6020 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6021 for (it->InitEx(true); it->More(); it->Next()) {
6022 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6029 //=============================================================================
6031 * SMESH_Gen_i::LoadASCII
6033 * Load SMESH module's data in ASCII format
6035 //=============================================================================
6037 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6038 const SALOMEDS::TMPFile& theStream,
6040 bool isMultiFile ) {
6041 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6042 return Load( theComponent, theStream, theURL, isMultiFile );
6044 //before call main ::Load method it's need for decipher text format to
6045 //binary ( "|xx" => x' )
6046 int size = theStream.length();
6047 if ( int((size / 3 )*3) != size ) //error size of buffer
6050 int real_size = int(size / 3);
6052 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6055 unsigned int c = -1;
6056 for ( int i = 0; i < real_size; i++ )
6058 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6059 sscanf( tmp, "%x", &c );
6060 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6063 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6065 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6068 //=============================================================================
6070 * SMESH_Gen_i::Close
6072 * Clears study-connected data when it is closed
6074 //=============================================================================
6076 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6078 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6080 // Clear study contexts data
6081 myStudyContext->Clear();
6083 // remove the tmp files meshes are loaded from
6084 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6086 // Clean trace of API methods calls
6092 //=============================================================================
6094 * SMESH_Gen_i::ComponentDataType
6096 * Get component data type
6098 //=============================================================================
6100 char* SMESH_Gen_i::ComponentDataType()
6102 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6103 return CORBA::string_dup( "SMESH" );
6107 //=============================================================================
6109 * SMESH_Gen_i::IORToLocalPersistentID
6111 * Transform data from transient form to persistent
6113 //=============================================================================
6115 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6116 const char* IORString,
6117 CORBA::Boolean /*isMultiFile*/,
6118 CORBA::Boolean /*isASCII*/ )
6120 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6122 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6123 int anId = myStudyContext->findId( IORString );
6125 if(MYDEBUG) MESSAGE( "VSR " << anId )
6127 sprintf( strId, "%d", anId );
6128 return CORBA::string_dup( strId );
6131 return CORBA::string_dup( "" );
6134 //=============================================================================
6136 * SMESH_Gen_i::LocalPersistentIDToIOR
6138 * Transform data from persistent form to transient
6140 //=============================================================================
6142 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6143 const char* aLocalPersistentID,
6144 CORBA::Boolean /*isMultiFile*/,
6145 CORBA::Boolean /*isASCII*/ )
6147 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6149 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6150 int anId = atoi( aLocalPersistentID );
6151 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6153 return CORBA::string_dup( "" );
6156 //=======================================================================
6157 //function : RegisterObject
6159 //=======================================================================
6161 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6163 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6164 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6165 return myStudyContext->addObject( string( iorString.in() ) );
6170 //================================================================================
6172 * \brief Return id of registered object
6173 * \param theObject - the Object
6174 * \retval int - Object id
6176 //================================================================================
6178 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6180 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6181 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6182 string iorStringCpp(iorString.in());
6183 return myStudyContext->findId( iorStringCpp );
6188 //=============================================================================
6190 * SMESH_Gen_i::SetName
6192 * Set a new object name
6194 //=============================================================================
6196 void SMESH_Gen_i::SetName(const char* theIOR,
6197 const char* theName)
6199 if ( theIOR && strcmp( theIOR, "" ) ) {
6200 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6201 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6202 if ( !aSO->_is_nil() ) {
6203 SetName( aSO, theName );
6208 // Version information
6209 char* SMESH_Gen_i::getVersion()
6211 #if SMESH_DEVELOPMENT
6212 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6214 return CORBA::string_dup(SMESH_VERSION_STR);
6218 //=================================================================================
6219 // function : Move()
6220 // purpose : Moves objects to the specified position.
6221 // Is used in the drag-n-drop functionality.
6222 //=================================================================================
6224 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6225 SALOMEDS::SObject_ptr where,
6228 if ( CORBA::is_nil( where ) ) return;
6230 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6231 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6232 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6233 std::string dataType = father->ComponentDataType();
6234 if ( dataType != "SMESH" ) return; // not a SMESH component
6236 SALOMEDS::SObject_var objAfter;
6237 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6238 // insert at given row -> find insertion position
6239 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6241 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6242 if ( i == row && useCaseIt->More() ) {
6243 objAfter = useCaseIt->Value();
6247 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6248 SALOMEDS::SObject_var sobj = what[i];
6249 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6250 // insert the object to the use case tree
6251 if ( !CORBA::is_nil( objAfter ) )
6252 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6254 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6257 //================================================================================
6259 * \brief Returns true if algorithm can be used to mesh a given geometry
6260 * \param [in] theAlgoType - the algorithm type
6261 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6262 * \param [in] theGeomObject - the geometry to mesh
6263 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6264 * else, returns \c True if at least one shape is meshable
6265 * \return CORBA::Boolean - can or can't
6267 //================================================================================
6269 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6270 const char* theLibName,
6271 GEOM::GEOM_Object_ptr theGeomObject,
6272 CORBA::Boolean toCheckAll)
6276 std::string aPlatformLibName;
6277 GenericHypothesisCreator_i* aCreator =
6278 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6281 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6282 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6283 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6290 SMESH_CATCH( SMESH::doNothing );
6293 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6298 //================================================================================
6300 * \brief Collect indices of elements, which are located inside the sphere
6302 //================================================================================
6304 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6305 SMESH::ElementType theElemType,
6311 SMESH::long_array_var aResult = new SMESH::long_array();
6312 if ( meshPart->_is_nil() )
6313 return aResult._retn();
6315 // 1. Create geometrical object
6316 gp_Pnt aP( theX, theY, theZ );
6317 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6319 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6321 if ( lst.size() > 0 ) {
6322 aResult->length( lst.size() );
6323 for ( size_t i = 0; i < lst.size(); i++ ) {
6324 aResult[i] = lst[i];
6327 return aResult._retn();
6330 //================================================================================
6332 * \brief Collect indices of elements, which are located inside the box
6334 //================================================================================
6336 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6337 SMESH::ElementType theElemType,
6338 CORBA::Double theX1,
6339 CORBA::Double theY1,
6340 CORBA::Double theZ1,
6341 CORBA::Double theX2,
6342 CORBA::Double theY2,
6343 CORBA::Double theZ2)
6345 SMESH::long_array_var aResult = new SMESH::long_array();
6346 if( meshPart->_is_nil() )
6347 return aResult._retn();
6349 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6350 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6352 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6354 if( lst.size() > 0 ) {
6355 aResult->length( lst.size() );
6356 for ( size_t i = 0; i < lst.size(); i++ ) {
6357 aResult[i] = lst[i];
6360 return aResult._retn();
6363 //================================================================================
6365 * \brief Collect indices of elements, which are located inside the cylinder
6367 //================================================================================
6369 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6370 SMESH::ElementType theElemType,
6374 CORBA::Double theDX,
6375 CORBA::Double theDY,
6376 CORBA::Double theDZ,
6378 CORBA::Double theR )
6380 SMESH::long_array_var aResult = new SMESH::long_array();
6381 if( meshPart->_is_nil() )
6382 return aResult._retn();
6384 gp_Pnt aP( theX, theY, theZ );
6385 gp_Vec aV( theDX, theDY, theDZ );
6386 gp_Ax2 anAxes (aP, aV);
6388 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6390 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6392 if( lst.size() > 0 ) {
6393 aResult->length( lst.size() );
6394 for ( size_t i = 0; i < lst.size(); i++ ) {
6395 aResult[i] = lst[i];
6398 return aResult._retn();
6401 //================================================================================
6403 * \brief Collect indices of elements, which are located inside the geom object
6405 //================================================================================
6407 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6408 SMESH::ElementType theElemType,
6409 GEOM::GEOM_Object_ptr theGeom,
6410 CORBA::Double theTolerance )
6412 SMESH::long_array_var aResult = new SMESH::long_array();
6413 if( meshPart->_is_nil() || theGeom->_is_nil() )
6414 return aResult._retn();
6416 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6418 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6420 if( lst.size() > 0 ) {
6421 aResult->length( lst.size() );
6422 for ( size_t i = 0; i < lst.size(); i++ ) {
6423 aResult[i] = lst[i];
6426 return aResult._retn();
6429 //================================================================================
6431 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6433 //================================================================================
6435 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6436 SMESH::ElementType theElemType,
6437 const TopoDS_Shape& theShape,
6438 double* theTolerance) {
6440 std::vector<long> res;
6441 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6443 if ( mesh->_is_nil() )
6446 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6450 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6455 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6456 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6457 anElementsOnShape->SetAllNodes( true );
6458 anElementsOnShape->SetMesh( meshDS );
6459 anElementsOnShape->SetShape( theShape, aType );
6462 anElementsOnShape->SetTolerance(*theTolerance);
6464 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6465 if ( !msource->_is_nil() ) { // Mesh case
6466 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6468 while ( elemIt->more() ) {
6469 const SMDS_MeshElement* anElem = elemIt->next();
6470 long anId = anElem->GetID();
6471 if ( anElementsOnShape->IsSatisfy( anId ) )
6472 res.push_back( anId );
6476 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6477 if ( !gsource->_is_nil() ) {
6478 if(theElemType == SMESH::NODE) {
6479 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6480 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6481 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6482 long anId = node->GetID();
6483 if ( anElementsOnShape->IsSatisfy( anId ) )
6484 res.push_back( anId );
6487 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6488 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6489 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6490 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6491 long anId = elem->GetID();
6492 if ( anElementsOnShape->IsSatisfy( anId ) )
6493 res.push_back( anId );
6498 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6499 if ( !smsource->_is_nil() ) {
6500 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6501 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6502 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6504 long anId = elem->GetID();
6505 if ( anElementsOnShape->IsSatisfy( anId ) )
6506 res.push_back( anId );