1 // Copyright (C) 2007-2023 CEA, EDF, 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>
52 // Have to be included before std headers
54 #include <structmember.h>
61 #include <libgen.h> // for basename function
65 #define LibHandle HMODULE
66 #define LoadLib( name ) LoadLibrary( name )
67 #define GetProc GetProcAddress
68 #define UnLoadLib( handle ) FreeLibrary( handle );
70 #define LibHandle void*
72 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
73 #else // DYNLOAD_LOCAL
74 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
75 #endif // DYNLOAD_LOCAL
77 #define UnLoadLib( handle ) dlclose( handle );
80 #include "SMESH_Gen_i.hxx"
81 #include "SMESH_version.h"
83 #include "DriverMED_W_SMESHDS_Mesh.h"
84 #include "DriverMED_R_SMESHDS_Mesh.h"
86 #include "DriverCGNS_Read.hxx"
88 #include "MED_Factory.hxx"
89 #include "SMDS_EdgePosition.hxx"
90 #include "SMDS_FacePosition.hxx"
91 #include "SMDS_SetIterator.hxx"
92 #include "SMDS_SpacePosition.hxx"
93 #include "SMDS_VertexPosition.hxx"
94 #include "SMESHDS_Document.hxx"
95 #include "SMESHDS_Group.hxx"
96 #include "SMESHDS_GroupOnGeom.hxx"
97 #include "SMESH_Algo_i.hxx"
98 #include "SMESH_File.hxx"
99 #include "SMESH_Group.hxx"
100 #include "SMESH_Group_i.hxx"
101 #include "SMESH_Hypothesis.hxx"
102 #include "SMESH_Hypothesis_i.hxx"
103 #include "SMESH_Mesh.hxx"
104 #include "SMESH_MeshEditor.hxx"
105 #include "SMESH_Mesh_i.hxx"
106 #include "SMESH_PreMeshInfo.hxx"
107 #include "SMESH_PythonDump.hxx"
108 #include "SMESH_ControlsDef.hxx"
109 #include <SMESH_BoostTxtArchive.hxx>
110 #include <SMESH_SequentialMesh_i.hxx>
111 #include <SMESH_ParallelMesh_i.hxx>
113 // to pass CORBA exception through SMESH_TRY
114 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
115 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
117 #include CORBA_SERVER_HEADER(SMESH_Group)
118 #include CORBA_SERVER_HEADER(SMESH_Filter)
119 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
122 #include <GEOMImpl_Types.hxx>
123 #include <GEOM_Client.hxx>
125 #include <Basics_Utils.hxx>
126 #include <Basics_DirUtils.hxx>
128 #include <OpUtil.hxx>
129 #include <SALOMEDS_Tool.hxx>
130 #include <SALOME_Container_i.hxx>
131 #include <SALOME_LifeCycleCORBA.hxx>
132 #include <SALOME_NamingService.hxx>
133 #include <Utils_CorbaException.hxx>
134 #include <Utils_ExceptHandlers.hxx>
135 #include <Utils_SINGLETON.hxx>
136 #include <utilities.h>
138 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
139 #include CORBA_CLIENT_HEADER(SALOME_Session)
141 // helpers about SALOME::GenericObj
142 #include <SALOMEDS_wrap.hxx>
143 #include <SALOMEDS_Attributes_wrap.hxx>
144 #include <GEOM_wrap.hxx>
153 #include <boost/archive/text_oarchive.hpp>
154 #include <boost/serialization/list.hpp>
155 #include <boost/serialization/string.hpp>
156 #include <boost/filesystem.hpp>
158 namespace fs = boost::filesystem;
161 using SMESH::TPythonDump;
164 #define NUM_TMP_FILES 2
166 // Static variables definition
167 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
168 CORBA::ORB_var SMESH_Gen_i::myOrb;
169 PortableServer::POA_var SMESH_Gen_i::myPoa;
170 SALOME_NamingService_Abstract* SMESH_Gen_i::myNS = nullptr;
171 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = nullptr;
172 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = nullptr;
175 const int nbElemPerDiagonal = 10;
177 //=============================================================================
179 * GetServant [ static ]
181 * Get servant of the CORBA object
183 //=============================================================================
185 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
187 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
190 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
193 catch (PortableServer::POA::ObjectNotActive &ex)
195 MESSAGE("GetServant: ObjectNotActive");
198 catch (PortableServer::POA::WrongAdapter &ex)
200 MESSAGE("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
203 catch (PortableServer::POA::WrongPolicy &ex)
205 MESSAGE("GetServant: WrongPolicy");
210 MESSAGE( "GetServant - Unknown exception was caught!!!" );
215 //=============================================================================
217 * SObjectToObject [ static ]
219 * Get CORBA object corresponding to the SALOMEDS::SObject
221 //=============================================================================
223 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
225 SALOMEDS::GenericAttribute_wrap anAttr;
226 CORBA::Object_var anObj;
227 if ( !theSObject->_is_nil() ) {
229 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
230 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
231 CORBA::String_var aValue = anIOR->Value();
232 if( strcmp( aValue, "" ) != 0 )
233 anObj = GetORB()->string_to_object( aValue );
237 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
243 // Set Naming Service object
244 void SMESH_Gen_i::SetNS(SALOME_NamingService_Abstract *ns)
251 //=============================================================================
255 * Get SALOME_NamingService object
257 //=============================================================================
259 SALOME_NamingService_Abstract* SMESH_Gen_i::GetNS()
262 myNS = SINGLETON_<SALOME_NamingService>::Instance();
263 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
264 myNS->init_orb( GetORB() );
269 //=============================================================================
273 * Get SALOME_LifeCycleCORBA object
275 //=============================================================================
277 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
279 if ( myLCC == NULL ) {
280 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
285 //=============================================================================
287 * GetGeomEngine [ static ]
289 * Get GEOM::GEOM_Gen reference
291 //=============================================================================
293 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
295 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
296 if ( !CORBA::is_nil( go ))
301 //=============================================================================
303 * SMESH_Gen_i::SMESH_Gen_i
305 * Default constructor: not for use
307 //=============================================================================
309 SMESH_Gen_i::SMESH_Gen_i()
313 //=============================================================================
315 * SMESH_Gen_i::SMESH_Gen_i
317 * Standard constructor, used with Container
319 //=============================================================================
321 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
322 PortableServer::POA_ptr poa,
323 PortableServer::ObjectId* contId,
324 const char* instanceName,
325 const char* interfaceName,
327 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
330 myOrb = CORBA::ORB::_duplicate(orb);
331 myPoa = PortableServer::POA::_duplicate(poa);
334 _id = myPoa->activate_object( _thisObj );
336 myStudyContext = new StudyContext;
338 myIsEmbeddedMode = false;
339 myIsEnablePublish = true;
340 myShapeReader = NULL; // shape reader
342 myIsHistoricalPythonDump = true;
343 myToForgetMeshDataOnHypModif = false;
345 // set it in standalone mode only
346 //OSD::SetSignal( true );
348 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
349 // find out mode (embedded or standalone) here else
350 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
351 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
354 if ( SALOME_NamingService_Abstract* ns = GetNS() )
356 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
357 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
358 if ( !session->_is_nil() )
360 CORBA::String_var str_host = session->getHostname();
361 CORBA::Long s_pid = session->getPID();
362 string my_host = Kernel_Utils::GetHostname();
364 long my_pid = (long)_getpid();
366 long my_pid = (long) getpid();
368 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
374 //=============================================================================
376 * SMESH_Gen_i::~SMESH_Gen_i
380 //=============================================================================
382 SMESH_Gen_i::~SMESH_Gen_i()
384 // delete hypothesis creators
385 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
386 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
388 // same creator can be mapped under different names
389 GenericHypothesisCreator_i* creator = (*itHyp).second;
393 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
394 if ( creator == (*itHyp2).second )
395 (*itHyp2).second = 0;
397 myHypCreatorMap.clear();
399 // Clear study contexts data
400 delete myStudyContext;
402 // delete shape reader
404 delete myShapeReader;
407 //=============================================================================
409 * SMESH_Gen_i::getHypothesisCreator
411 * Get hypothesis creator
413 //=============================================================================
415 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
416 const char* theLibName,
417 std::string& thePlatformLibName)
419 std::string aPlatformLibName;
420 /* It's Need to translate lib name for WIN32 or X platform */
421 if ( theLibName && theLibName[0] != '\0' )
423 int libNameLen = strlen(theLibName);
424 //check for old format "libXXXXXXX.so"
425 if (libNameLen > 7 &&
426 !strncmp( theLibName, "lib", 3 ) &&
427 !strcmp( theLibName+libNameLen-3, ".so" ))
431 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
432 #elif defined(__APPLE__)
433 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
435 aPlatformLibName = theLibName;
440 //try to use new format
442 aPlatformLibName = theLibName;
443 aPlatformLibName += ".dll";
444 #elif defined(__APPLE__)
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
447 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
451 thePlatformLibName = aPlatformLibName;
453 Unexpect aCatch(SALOME_SalomeException);
454 MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
456 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
457 GenericHypothesisCreator_i* aCreator;
460 // check, if creator for this hypothesis type already exists
461 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
463 // load plugin library
464 MESSAGE("Loading server meshers plugin library ...");
467 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
468 SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
470 const char* path = aPlatformLibName.c_str();
473 const char* path = aPlatformLibName.c_str();
475 LibHandle libHandle = LoadLib( path );
479 // report any error, if occurred
481 const char* anError = dlerror();
482 throw(SALOME_Exception( anError ));
484 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
485 << aPlatformLibName));
489 // get method, returning hypothesis creator
490 MESSAGE("Find GetHypothesisCreator() method ...");
491 GetHypothesisCreator procHandle =
492 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
495 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
496 << aPlatformLibName ));
497 UnLoadLib(libHandle);
500 // get hypothesis creator
501 MESSAGE("Get Hypothesis Creator for " << theHypName);
502 aCreator = procHandle(theHypName);
505 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
506 << aPlatformLibName));
508 // map hypothesis creator to a hypothesis name
509 myHypCreatorMap[string(theHypName)] = aCreator;
514 return myHypCreatorMap[string(theHypName)];
517 catch (SALOME_Exception& S_ex)
519 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
524 //=============================================================================
526 * SMESH_Gen_i::createHypothesis
528 * Create hypothesis of given type
530 //=============================================================================
532 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
533 const char* theLibName)
535 SMESH_Hypothesis_i* myHypothesis_i = 0;
536 SMESH::SMESH_Hypothesis_var hypothesis_i;
537 std::string aPlatformLibName;
538 GenericHypothesisCreator_i* aCreator =
539 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
541 // create a new hypothesis object, store its ref. in studyContext
542 myHypothesis_i = aCreator->Create(myPoa, &myGen);
545 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
546 CORBA::String_var hypName = myHypothesis_i->GetName();
547 myHypCreatorMap[ hypName.in() ] = aCreator;
549 // activate the CORBA servant of hypothesis
550 hypothesis_i = myHypothesis_i->_this();
551 int nextId = RegisterObject( hypothesis_i );
552 MESSAGE( "Add hypo to map with id = "<< nextId );
554 return hypothesis_i._retn();
557 //=============================================================================
559 * SMESH_Gen_i::createMesh
561 * Create empty mesh on shape
563 //=============================================================================
565 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh(bool parallel /*=false*/)
567 Unexpect aCatch(SALOME_SalomeException);
568 MESSAGE( "SMESH_Gen_i::createMesh" );
570 // Get or create the GEOM_Client instance
572 // create a new mesh object servant, store it in a map in study context
573 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
574 // create a new mesh object
575 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
577 meshServant->SetImpl( dynamic_cast<SMESH_Mesh*>(myGen.CreateParallelMesh( myIsEmbeddedMode )));
579 meshServant->SetImpl( dynamic_cast<SMESH_Mesh*>(myGen.CreateMesh( myIsEmbeddedMode )));
582 // activate the CORBA servant of Mesh
583 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
584 int nextId = RegisterObject( mesh );
585 MESSAGE( "Add mesh to map with id = "<< nextId);
589 catch (SALOME_Exception& S_ex) {
590 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
592 return SMESH::SMESH_Mesh::_nil();
595 //=============================================================================
597 * SMESH_Gen_i::GetShapeReader
601 //=============================================================================
603 GEOM_Client* SMESH_Gen_i::GetShapeReader()
605 // create shape reader if necessary
606 if ( !myShapeReader )
607 myShapeReader = new GEOM_Client(GetContainerRef());
608 ASSERT( myShapeReader );
609 return myShapeReader;
612 //=============================================================================
614 * SMESH_Gen_i::SetGeomEngine
616 * Set GEOM::GEOM_Gen reference
618 //=============================================================================
620 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
622 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
625 //=============================================================================
627 * SMESH_Gen_i::SetEmbeddedMode
631 //=============================================================================
633 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
635 myIsEmbeddedMode = theMode;
637 if ( !myIsEmbeddedMode ) {
638 //PAL10867: disable signals catching with "noexcepthandler" option
639 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
640 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
644 if (SALOME::VerbosityActivated())
647 char* envDisableFPE = getenv("DISABLE_FPE");
648 if (envDisableFPE && atoi(envDisableFPE))
656 OSD::SetSignal( raiseFPE );
658 // else OSD::SetSignal() is called in GUI
662 //=============================================================================
664 * SMESH_Gen_i::IsEmbeddedMode
668 //=============================================================================
670 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
672 return myIsEmbeddedMode;
675 //=============================================================================
677 * SMESH_Gen_i::SetEnablePublish
679 * Set enable publishing in the study
681 //=============================================================================
683 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
685 myIsEnablePublish = theIsEnablePublish;
688 //=============================================================================
690 * SMESH_Gen_i::IsEnablePublish
692 * Check enable publishing
694 //=============================================================================
696 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
698 return myIsEnablePublish;
701 //=============================================================================
703 * SMESH_Gen_i::UpdateStudy
705 * Update study (needed at switching GEOM->SMESH)
707 //=============================================================================
709 void SMESH_Gen_i::UpdateStudy()
711 if ( !myStudyContext )
712 myStudyContext = new StudyContext;
714 SALOMEDS::Study_var aStudy = getStudyServant();
715 if ( !CORBA::is_nil( aStudy ) )
717 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
719 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
720 if( !GEOM_var->_is_nil() )
721 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
723 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
724 if( !GEOM_var->_is_nil() )
725 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
727 // NPAL16168, issue 0020210
728 // Let meshes update their data depending on GEOM groups that could change
729 CORBA::String_var compDataType = ComponentDataType();
730 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
731 if ( !me->_is_nil() ) {
732 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
733 for ( ; anIter->More(); anIter->Next() ) {
734 SALOMEDS::SObject_wrap so = anIter->Value();
735 CORBA::Object_var ior = SObjectToObject( so );
736 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
737 mesh->CheckGeomModif();
743 //================================================================================
745 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
747 //================================================================================
749 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
751 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
752 SALOMEDS::GenericAttribute_wrap attr;
753 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
755 SALOMEDS::AttributePixMap_wrap pm = attr;
756 CORBA::String_var ico = pm->GetPixMap();
757 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
762 //=================================================================================
763 // function : hasObjectInfo()
764 // purpose : shows if module provides information for its objects
765 //=================================================================================
767 bool SMESH_Gen_i::hasObjectInfo()
772 //=================================================================================
773 // function : getObjectInfo()
774 // purpose : returns an information for a given object by its entry
775 //=================================================================================
777 char* SMESH_Gen_i::getObjectInfo( const char* entry )
779 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
780 // for the rest, "module 'SMESH', ID=0:1:2:*"
784 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
785 CORBA::Object_var obj = SObjectToObject( so );
786 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
787 if ( isGeomModifIcon( mesh ))
789 txt << "The geometry was changed and the mesh needs to be recomputed";
794 CORBA::String_var compType = ComponentDataType();
795 txt << "module '" << compType << "', ID=" << entry;
797 return CORBA::string_dup( txt );
800 //=============================================================================
802 * SMESH_Gen_i::GetStudyContext
806 //=============================================================================
808 StudyContext* SMESH_Gen_i::GetStudyContext()
810 return myStudyContext;
813 //=============================================================================
815 * SMESH_Gen_i::CreateHypothesis
817 * Create hypothesis/algorithm of given type and publish it in the study
819 //=============================================================================
821 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
822 const char* theLibName )
824 Unexpect aCatch(SALOME_SalomeException);
825 // Create hypothesis/algorithm
826 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
828 // Publish hypothesis/algorithm in the study
829 if ( CanPublishInStudy( hyp ) ) {
830 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
831 if ( !aSO->_is_nil() ) {
832 // Update Python script
833 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
834 << theHypName << "', '" << theLibName << "')";
841 //================================================================================
843 * \brief Return a hypothesis initialized by given average length.
844 * \param theHypType - hypothesis type name
845 * \param theLibName - plugin library name
846 * \param theAverageLength - average length
847 * \param theQuadDominated - is quad-dominated flag
848 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
850 //================================================================================
852 SMESH::SMESH_Hypothesis_ptr
853 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
854 const char* theLibName,
855 CORBA::Double theAverageLength,
856 CORBA::Boolean theQuadDominated)
858 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
859 theAverageLength, theQuadDominated };
861 SMESH::SMESH_Hypothesis_var hyp =
862 GetHypothesisParameterValues( theHypType, theLibName,
863 SMESH::SMESH_Mesh::_nil(),
864 GEOM::GEOM_Object::_nil(),
866 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
868 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
869 << theHypType << "', '"
870 << theLibName << "', "
871 << theAverageLength << ", "
872 << theQuadDominated << " )";
877 //================================================================================
879 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
880 * existing on the given geometry or to size of the geometry.
881 * \param theHypType - hypothesis type name
882 * \param theLibName - plugin library name
883 * \param theMesh - The mesh of interest
884 * \param theGeom - The shape to get parameter values from
885 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
886 * in a study and used to compute the mesh, or a temporary one created just to pass
889 //================================================================================
891 SMESH::SMESH_Hypothesis_ptr
892 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
893 const char* theLibName,
894 SMESH::SMESH_Mesh_ptr theMesh,
895 GEOM::GEOM_Object_ptr theGeom,
896 const SMESH::HypInitParams& theParams)
898 Unexpect aCatch(SALOME_SalomeException);
900 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
901 if ( byMesh && CORBA::is_nil( theMesh ) )
902 return SMESH::SMESH_Hypothesis::_nil();
903 if ( byMesh && CORBA::is_nil( theGeom ) )
904 return SMESH::SMESH_Hypothesis::_nil();
906 // -----------------------------------------------
907 // find hypothesis used to mesh theGeom
908 // -----------------------------------------------
910 // get mesh and shape
911 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
912 TopoDS_Shape shape = GeomObjectToShape( theGeom );
913 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
914 return SMESH::SMESH_Hypothesis::_nil();
915 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
917 // create a temporary hypothesis to know its dimension
918 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
919 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
921 return SMESH::SMESH_Hypothesis::_nil();
922 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
925 // look for a hypothesis of theHypType used to mesh the shape
926 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
929 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
930 int nbLocalHyps = aHypList->length();
931 for ( int i = 0; i < nbLocalHyps; i++ ) {
932 CORBA::String_var hypName = aHypList[i]->GetName();
933 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
934 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
936 // check super shapes
937 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
938 while ( nbLocalHyps == 0 && itShape.More() ) {
939 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
940 if ( ! CORBA::is_nil( geomObj )) {
941 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
942 nbLocalHyps = aHypList->length();
943 for ( int i = 0; i < nbLocalHyps; i++ )
944 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
945 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
951 // let the temporary hypothesis find out somehow parameter values by mesh
952 if ( hyp->SetParametersByMesh( mesh, shape ))
953 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
957 ::SMESH_Hypothesis::TDefaults dflts;
958 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
959 dflts._nbSegments = myGen.GetDefaultNbSegments();
960 dflts._elemLength = theParams.averageLength;
961 dflts._quadDominated = theParams.quadDominated;
962 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
965 dflts._diagonal = mesh->GetShapeDiagonalSize();
967 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
968 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
969 dflts._shape = &shape;
972 // let the hypothesis initialize it's values
973 if ( hyp->SetParametersByDefaults( dflts, mesh ))
974 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
977 return SMESH::SMESH_Hypothesis::_nil();
980 //=============================================================================
982 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
983 * \param [in] theHyp - the hypothesis of interest
984 * \param [out] theMesh - the sole mesh using \a theHyp
985 * \param [out] theShape - the sole geometry \a theHyp is assigned to
986 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
988 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
989 * considered as SAME sub-mesh => result is \c true.
990 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
991 * a shape to which an hyp being edited is assigned.
993 //=============================================================================
995 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
996 SMESH::SMESH_Mesh_out theMesh,
997 GEOM::GEOM_Object_out theShape)
999 if ( CORBA::is_nil( theHyp ))
1002 // get Mesh component SO
1003 CORBA::String_var compDataType = ComponentDataType();
1004 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1005 if ( CORBA::is_nil( comp ))
1008 // look for child SO of meshes
1009 SMESH::SMESH_Mesh_var foundMesh;
1010 TopoDS_Shape foundShape;
1012 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1013 for ( ; meshIter->More() && isSole; meshIter->Next() )
1015 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1016 CORBA::Object_var obj = SObjectToObject( curSO );
1017 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1021 // look for a sole shape where theHyp is assigned
1022 bool isHypFound = false;
1023 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1024 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1025 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1027 const THypList& hyps = s2hypsIt.Value();
1028 THypList::const_iterator h = hyps.begin();
1029 for ( ; h != hyps.end(); ++h )
1030 if ( (*h)->GetID() == theHyp->GetId() )
1032 if ( h != hyps.end()) // theHyp found
1035 if ( ! foundShape.IsNull() &&
1036 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1038 foundShape.Nullify();
1042 foundShape = s2hypsIt.Key();
1044 } // loop on assigned hyps
1046 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1048 if ( !foundMesh->_is_nil() ) // not a sole mesh
1050 if ( !foundMesh->HasShapeToMesh() ||
1051 !mesh_i ->HasShapeToMesh() )
1053 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1057 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1058 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1059 isSole = s1->IsSame( s2 );
1062 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1068 ! foundMesh->_is_nil() &&
1069 ! foundShape.IsNull() )
1071 theMesh = foundMesh._retn();
1072 theShape = ShapeToGeomObject( foundShape );
1073 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1078 //=============================================================================
1080 * Set number of segments per diagonal of boundary box of geometry by which
1081 * default segment length of appropriate 1D hypotheses is defined
1083 //=============================================================================
1085 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1087 if ( theNbSegments > 0 )
1088 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1090 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1093 //=============================================================================
1095 * \brief Set default number of segments per edge
1097 //=============================================================================
1099 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1101 if ( theNbSegments > 0 )
1102 myGen.SetDefaultNbSegments( int(theNbSegments) );
1104 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1107 //=============================================================================
1109 * Set an option value
1111 //=============================================================================
1113 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1115 if ( name && value && strlen( value ) > 0 )
1118 if ( strcmp(name, "historical_python_dump") == 0 )
1120 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1121 msgToGUI = "preferences/SMESH/historical_python_dump/";
1122 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1124 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1126 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1127 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1128 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1130 else if ( strcmp(name, "default_grp_color") == 0 )
1134 // color must be presented as a string of following form:
1135 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1136 str = str.substr(1);
1137 for ( size_t i = 0; i < str.length()/2; i++ )
1138 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1139 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1141 else if ( value ) { // rgb color ("255,170,0", for example)
1142 string tempValue( value );
1143 char* colorValue = strtok( &tempValue[0], "," );
1144 while ( colorValue != NULL ) {
1145 int c_value = atoi( colorValue );
1146 if ( c_value >= 0 && c_value <= 255 )
1147 color.push_back( c_value );
1148 colorValue = strtok( NULL, "," );
1151 if ( color.size() == 3 ) { // color must have three valid component
1152 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1153 myDefaultGroupColor = value;
1154 msgToGUI = "preferences/SMESH/default_grp_color/";
1159 // update preferences in case if SetOption() is invoked from python console
1160 if ( !msgToGUI.empty() )
1162 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1163 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1164 if ( !CORBA::is_nil( session ) )
1165 session->emitMessageOneWay(msgToGUI.c_str());
1170 //=============================================================================
1172 * Return an option value
1174 //=============================================================================
1176 char* SMESH_Gen_i::GetOption(const char* name)
1180 if ( strcmp(name, "historical_python_dump") == 0 )
1182 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1184 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1186 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1188 if ( strcmp(name, "default_grp_color") == 0 )
1190 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1193 return CORBA::string_dup( "" );
1196 //=============================================================================
1198 * SMESH_Gen_i::CreateMesh
1200 * Create empty mesh on a shape and publish it in the study
1202 //=============================================================================
1204 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1206 Unexpect aCatch(SALOME_SalomeException);
1207 MESSAGE( "SMESH_Gen_i::CreateMesh(GEOM_Object_ptr)" );
1209 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1211 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1212 ASSERT( meshServant );
1213 meshServant->SetShape( theShapeObject );
1215 // publish mesh in the study
1216 if ( CanPublishInStudy( mesh ) ) {
1217 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1218 aStudyBuilder->NewCommand(); // There is a transaction
1219 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1220 aStudyBuilder->CommitCommand();
1221 if ( !aSO->_is_nil() ) {
1222 // Update Python script
1223 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1227 return mesh._retn();
1230 //=============================================================================
1232 * SMESH_Gen_i::CreateParallelMesh
1234 * Create empty parallel mesh on a shape and publish it in the study
1236 //=============================================================================
1238 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateParallelMesh( GEOM::GEOM_Object_ptr theShapeObject )
1240 Unexpect aCatch(SALOME_SalomeException);
1241 MESSAGE( "SMESH_Gen_i::CreateParallelMesh" );
1243 SMESH::SMESH_Mesh_var mesh = this->createMesh(true);
1245 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1246 ASSERT( meshServant );
1247 meshServant->SetShape( theShapeObject );
1249 // publish mesh in the study
1250 if ( CanPublishInStudy( mesh ) ) {
1251 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1252 aStudyBuilder->NewCommand(); // There is a transaction
1253 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1254 aStudyBuilder->CommitCommand();
1255 if ( !aSO->_is_nil() ) {
1256 // Update Python script
1257 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1261 return mesh._retn();
1264 //=============================================================================
1266 * SMESH_Gen_i::CreateEmptyMesh
1270 //=============================================================================
1272 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1274 Unexpect aCatch(SALOME_SalomeException);
1275 MESSAGE( "SMESH_Gen_i::CreateEmptyMesh" );
1277 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1279 // publish mesh in the study
1280 if ( CanPublishInStudy( mesh ) ) {
1281 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1282 aStudyBuilder->NewCommand(); // There is a transaction
1283 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1284 aStudyBuilder->CommitCommand();
1285 if ( !aSO->_is_nil() ) {
1286 // Update Python script
1287 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1291 return mesh._retn();
1296 //================================================================================
1298 * \brief Throw an exception in case if the file can't be read
1300 //================================================================================
1302 void checkFileReadable( const char* theFileName )
1304 SMESH_File f ( theFileName );
1307 if ( !f.error().empty() )
1308 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1310 THROW_SALOME_CORBA_EXCEPTION
1311 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1312 SALOME::BAD_PARAM );
1317 //=============================================================================
1319 * SMESH_Gen_i::CreateMeshFromUNV
1321 * Create mesh and import data from UNV file
1323 //=============================================================================
1325 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1327 Unexpect aCatch(SALOME_SalomeException);
1329 checkFileReadable( theFileName );
1331 SMESH::SMESH_Mesh_var aMesh = createMesh();
1333 // publish mesh in the study
1334 if ( CanPublishInStudy( aMesh ) ) {
1335 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1336 aStudyBuilder->NewCommand(); // There is a transaction
1337 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1338 aStudyBuilder->CommitCommand();
1339 if ( !aSO->_is_nil() ) {
1340 // Update Python script
1341 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1345 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1347 aServant->ImportUNVFile( theFileName );
1349 // Dump creation of groups
1350 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1352 aServant->GetImpl().GetMeshDS()->Modified();
1353 return aMesh._retn();
1356 //=============================================================================
1358 * SMESH_Gen_i::CreateMeshFromMED
1360 * Create mesh and import data from MED file
1362 //=============================================================================
1364 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1365 SMESH::DriverMED_ReadStatus& theStatus )
1367 checkFileReadable( theFileName );
1370 char bname[ _MAX_FNAME ];
1371 _splitpath( theFileName, NULL, NULL, bname, NULL );
1372 string aFileName = bname;
1374 string aFileName = basename( const_cast<char *>( theFileName ));
1376 // Retrieve mesh names from the file
1377 DriverMED_R_SMESHDS_Mesh myReader;
1378 myReader.SetFile( theFileName );
1379 myReader.SetMeshId( -1 );
1380 Driver_Mesh::Status aStatus;
1381 list<string> aNames = myReader.GetMeshNames(aStatus);
1382 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1383 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1385 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1388 TPythonDump aPythonDump(this);
1389 aPythonDump << "([";
1391 if (theStatus == SMESH::DRS_OK)
1393 SALOMEDS::StudyBuilder_var aStudyBuilder;
1394 aStudyBuilder = getStudyServant()->NewBuilder();
1395 aStudyBuilder->NewCommand(); // There is a transaction
1397 aResult->length( aNames.size() );
1400 // Iterate through all meshes and create mesh objects
1401 for ( const std::string & meshName : aNames )
1404 if (i > 0) aPythonDump << ", ";
1407 SMESH::SMESH_Mesh_var mesh = createMesh();
1409 // publish mesh in the study
1410 SALOMEDS::SObject_wrap aSO;
1411 if ( CanPublishInStudy( mesh ) )
1412 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1415 if ( !aSO->_is_nil() ) {
1418 aPythonDump << "mesh_" << i;
1421 // Read mesh data (groups are published automatically by ImportMEDFile())
1422 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1423 ASSERT( meshServant );
1424 SMESH::DriverMED_ReadStatus status1 =
1425 meshServant->ImportMEDFile( theFileName, meshName.c_str() );
1426 if (status1 > theStatus)
1427 theStatus = status1;
1429 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1430 meshServant->GetImpl().GetMeshDS()->Modified();
1432 if ( !aStudyBuilder->_is_nil() )
1433 aStudyBuilder->CommitCommand();
1436 // Update Python script
1437 aPythonDump << "], status) = " << this << ".CreateMeshesFromMED( r'" << theFileName << "' )";
1439 // Dump creation of groups
1440 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1441 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1443 return aResult._retn();
1446 //=============================================================================
1448 * SMESH_Gen_i::CreateMeshFromSTL
1450 * Create mesh and import data from STL file
1452 //=============================================================================
1454 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1456 Unexpect aCatch(SALOME_SalomeException);
1457 checkFileReadable( theFileName );
1459 SMESH::SMESH_Mesh_var aMesh = createMesh();
1462 char bname[ _MAX_FNAME ];
1463 _splitpath( theFileName, NULL, NULL, bname, NULL );
1464 string aFileName = bname;
1466 string aFileName = basename( const_cast<char *>(theFileName) );
1468 // publish mesh in the study
1469 if ( CanPublishInStudy( aMesh ) ) {
1470 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1471 aStudyBuilder->NewCommand(); // There is a transaction
1472 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1473 aStudyBuilder->CommitCommand();
1474 if ( !aSO->_is_nil() ) {
1475 // Update Python script
1476 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1480 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1482 aServant->ImportSTLFile( theFileName );
1483 aServant->GetImpl().GetMeshDS()->Modified();
1484 return aMesh._retn();
1487 //================================================================================
1489 * \brief Create meshes and import data from the CGSN file
1491 //================================================================================
1493 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1494 SMESH::DriverMED_ReadStatus& theStatus)
1496 Unexpect aCatch(SALOME_SalomeException);
1497 checkFileReadable( theFileName );
1499 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1502 // Retrieve nb meshes from the file
1503 DriverCGNS_Read myReader;
1504 myReader.SetFile( theFileName );
1505 Driver_Mesh::Status aStatus;
1506 int nbMeshes = myReader.GetNbMeshes(aStatus);
1507 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1509 aResult->length( nbMeshes );
1511 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1514 TPythonDump aPythonDump(this);
1515 aPythonDump << "([";
1517 if (theStatus == SMESH::DRS_OK)
1519 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1520 aStudyBuilder->NewCommand(); // There is a transaction
1524 // Iterate through all meshes and create mesh objects
1525 for ( ; i < nbMeshes; ++i )
1528 if (i > 0) aPythonDump << ", ";
1531 SMESH::SMESH_Mesh_var mesh = createMesh();
1532 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1534 // Read mesh data (groups are published automatically by ImportMEDFile())
1535 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1536 ASSERT( meshServant );
1538 SMESH::DriverMED_ReadStatus status1 =
1539 meshServant->ImportCGNSFile( theFileName, i, meshName );
1540 if (status1 > theStatus)
1541 theStatus = status1;
1543 meshServant->GetImpl().GetMeshDS()->Modified();
1544 // publish mesh in the study
1545 SALOMEDS::SObject_wrap aSO;
1546 if ( CanPublishInStudy( mesh ) )
1547 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1550 if ( !aSO->_is_nil() ) {
1554 aPythonDump << "mesh_" << i;
1557 aStudyBuilder->CommitCommand();
1560 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1562 // Dump creation of groups
1563 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1564 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1566 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1569 return aResult._retn();
1572 //================================================================================
1574 * \brief Create a mesh and import data from a GMF file
1576 //================================================================================
1578 SMESH::SMESH_Mesh_ptr
1579 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1580 CORBA::Boolean theMakeRequiredGroups,
1581 SMESH::ComputeError_out theError)
1583 Unexpect aCatch(SALOME_SalomeException);
1584 checkFileReadable( theFileName );
1586 SMESH::SMESH_Mesh_var aMesh = createMesh();
1588 char bname[ _MAX_FNAME ];
1589 _splitpath( theFileName, NULL, NULL, bname, NULL );
1590 string aFileName = bname;
1592 string aFileName = basename( const_cast<char *>(theFileName) );
1594 // publish mesh in the study
1595 if ( CanPublishInStudy( aMesh ) ) {
1596 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1597 aStudyBuilder->NewCommand(); // There is a transaction
1598 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1599 aStudyBuilder->CommitCommand();
1600 if ( !aSO->_is_nil() ) {
1601 // Update Python script
1602 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1603 << theFileName << "', "
1604 << theMakeRequiredGroups << " )";
1607 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1609 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1610 aServant->GetImpl().GetMeshDS()->Modified();
1611 return aMesh._retn();
1615 //=============================================================================
1617 * SMESH_Gen_i::IsReadyToCompute
1619 * Return true if mesh contains enough data to be computed
1621 //=============================================================================
1623 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1624 GEOM::GEOM_Object_ptr theShapeObject )
1626 Unexpect aCatch(SALOME_SalomeException);
1627 MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1629 if ( CORBA::is_nil( theShapeObject ) )
1630 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1631 SALOME::BAD_PARAM );
1632 if ( CORBA::is_nil( theMesh ) )
1633 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1634 SALOME::BAD_PARAM );
1637 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1638 ASSERT( meshServant );
1639 if ( meshServant ) {
1640 // get local TopoDS_Shape
1641 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1642 // call implementation
1643 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1644 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1647 catch ( SALOME_Exception& S_ex ) {
1648 INFOS( "catch exception "<< S_ex.what() );
1653 //================================================================================
1655 * \brief Find SObject for an algo
1657 //================================================================================
1659 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1662 SALOMEDS::Study_var aStudy = getStudyServant();
1663 if ( !aStudy->_is_nil() ) {
1664 // find algo in the study
1665 CORBA::String_var compDataType = ComponentDataType();
1666 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1667 if ( !father->_is_nil() ) {
1668 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1669 for ( ; itBig->More(); itBig->Next() ) {
1670 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1671 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1672 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1673 for ( ; algoIt->More(); algoIt->Next() ) {
1674 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1675 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1676 if ( !CORBA::is_nil( algoIOR )) {
1677 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1678 if ( impl && impl->GetImpl() == algo )
1679 return algoSO._retn();
1681 } // loop on algo SO's
1684 } // SMESH component iterator
1688 return SALOMEDS::SObject::_nil();
1691 //================================================================================
1693 * \brief Return errors of mesh computation
1695 //================================================================================
1697 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1698 GEOM::GEOM_Object_ptr theSubObject )
1700 Unexpect aCatch(SALOME_SalomeException);
1701 MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1703 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1704 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1706 if ( CORBA::is_nil( theMesh ) )
1707 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1709 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1711 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1714 if(theMesh->HasShapeToMesh())
1715 shape = GeomObjectToShape( theSubObject );
1717 shape = SMESH_Mesh::PseudoShape();
1719 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1721 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1724 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1725 const bool includeSelf = true, complexShapeFirst = true;
1726 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1728 while ( smIt->more() )
1731 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1733 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1734 if ( error && !error->IsOK() )
1736 if ( !( error->myAlgo ) &&
1737 !( error->myAlgo = sm->GetAlgo() ))
1739 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1740 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1741 errStruct.comment = error->myComment.c_str();
1742 errStruct.subShapeID = sm->GetId();
1743 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1744 if ( !algoSO->_is_nil() ) {
1745 CORBA::String_var algoName = algoSO->GetName();
1746 errStruct.algoName = algoName;
1749 errStruct.algoName = error->myAlgo->GetName();
1751 errStruct.hasBadMesh = error->HasBadElems();
1754 error_array->length( nbErr );
1757 catch ( SALOME_Exception& S_ex ) {
1758 INFOS( "catch exception "<< S_ex.what() );
1761 return error_array._retn();
1764 //================================================================================
1766 * \brief Return mesh elements preventing computation of a subshape
1768 //================================================================================
1770 SMESH::MeshPreviewStruct*
1771 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1772 CORBA::Short theSubShapeID )
1774 Unexpect aCatch(SALOME_SalomeException);
1775 MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1777 if ( CORBA::is_nil( theMesh ) )
1778 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1780 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1783 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1785 // mesh implementation
1786 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1787 // submesh by subshape id
1788 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1791 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1792 if ( error && error->HasBadElems() )
1794 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1795 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1797 // get nodes of elements and count elements
1798 TNode2LocalIDMap mapNode2LocalID;
1799 list< TNodeLocalID > connectivity;
1800 int i, nbElements = 0, nbConnNodes = 0;
1802 const list<const SMDS_MeshElement*>& badElems =
1803 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1804 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1805 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1806 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1808 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1809 while ( nIt->more() )
1810 connectivity.push_back
1811 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1813 // fill node coords and assign local ids to the nodes
1814 int nbNodes = mapNode2LocalID.size();
1815 result->nodesXYZ.length( nbNodes );
1816 TNodeLocalID node2ID = mapNode2LocalID.begin();
1817 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1818 node2ID->second = i;
1819 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1820 result->nodesXYZ[i].x = node->X();
1821 result->nodesXYZ[i].y = node->Y();
1822 result->nodesXYZ[i].z = node->Z();
1824 // fill connectivity
1825 result->elementConnectivities.length( nbConnNodes );
1826 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1827 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1828 result->elementConnectivities[i] = (*connIt)->second;
1830 // fill element types
1831 result->elementTypes.length( nbElements );
1832 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1834 const SMDS_MeshElement* elem = *elemIt;
1835 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1836 result->elementTypes[i].isPoly = elem->IsPoly();
1837 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1843 catch ( SALOME_Exception& S_ex ) {
1844 INFOS( "catch exception "<< S_ex.what() );
1847 return result._retn();
1850 //================================================================================
1852 * \brief Create a group of elements preventing computation of a sub-shape
1854 //================================================================================
1856 SMESH::ListOfGroups*
1857 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1858 CORBA::Short theSubShapeID,
1859 const char* theGroupName )
1861 Unexpect aCatch(SALOME_SalomeException);
1863 SMESH::ListOfGroups_var groups;
1865 if ( CORBA::is_nil( theMesh ) )
1866 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1869 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1871 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1872 TPythonDump(this) << groups << " = " << this
1873 << ".MakeGroupsOfBadInputElements( "
1874 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1877 catch ( SALOME_Exception& S_ex ) {
1878 INFOS( "catch exception "<< S_ex.what() );
1880 return groups._retn();
1883 //================================================================================
1885 * \brief Returns errors of hypotheses definition
1886 * \param theMesh - the mesh
1887 * \param theSubObject - the main or sub- shape
1888 * \retval SMESH::algo_error_array* - sequence of errors
1890 //================================================================================
1892 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1893 GEOM::GEOM_Object_ptr theSubObject )
1895 Unexpect aCatch(SALOME_SalomeException);
1896 MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1898 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1899 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1901 if ( CORBA::is_nil( theMesh ) )
1902 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1904 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1906 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1907 ASSERT( meshServant );
1908 if ( meshServant ) {
1909 TopoDS_Shape myLocShape;
1910 if(theMesh->HasShapeToMesh())
1911 myLocShape = GeomObjectToShape( theSubObject );
1913 myLocShape = SMESH_Mesh::PseudoShape();
1915 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1916 list< ::SMESH_Gen::TAlgoStateError > error_list;
1917 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1918 // call ::SMESH_Gen::GetAlgoState()
1919 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1920 error_array->length( error_list.size() );
1922 for ( error = error_list.begin(); error != error_list.end(); ++error )
1924 // fill AlgoStateError structure
1925 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1926 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1927 errStruct.algoDim = error->_algoDim;
1928 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1929 errStruct.algoName = "";
1930 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1931 if ( !algoSO->_is_nil() ) {
1932 CORBA::String_var algoName = algoSO->GetName();
1933 errStruct.algoName = algoName.in();
1938 catch ( SALOME_Exception& S_ex ) {
1939 INFOS( "catch exception "<< S_ex.what() );
1941 return error_array._retn();
1944 //=============================================================================
1946 * SMESH_Gen_i::GetSubShapesId
1948 * Get sub-shapes unique ID's list
1950 //=============================================================================
1953 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1954 const SMESH::object_array& theListOfSubShapeObject )
1956 Unexpect aCatch(SALOME_SalomeException);
1957 MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1959 SMESH::long_array_var shapesId = new SMESH::long_array;
1962 if ( CORBA::is_nil( theMainShapeObject ) )
1963 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1967 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1968 TopTools_IndexedMapOfShape myIndexToShape;
1969 TopExp::MapShapes(myMainShape,myIndexToShape);
1971 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1973 GEOM::GEOM_Object_var aShapeObject
1974 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1975 if ( CORBA::is_nil( aShapeObject ) )
1976 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1977 SALOME::BAD_PARAM );
1979 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1980 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1982 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1983 setId.insert(myIndexToShape.FindIndex(F));
1984 SCRUTE(myIndexToShape.FindIndex(F));
1986 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1988 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1989 setId.insert(myIndexToShape.FindIndex(E));
1990 SCRUTE(myIndexToShape.FindIndex(E));
1992 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1994 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1995 setId.insert(myIndexToShape.FindIndex(V));
1996 SCRUTE(myIndexToShape.FindIndex(V));
1999 shapesId->length(setId.size());
2000 set<int>::iterator iind;
2002 for (iind = setId.begin(); iind != setId.end(); iind++)
2005 shapesId[i] = (*iind);
2006 SCRUTE(shapesId[i]);
2010 catch (SALOME_Exception& S_ex)
2012 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2015 return shapesId._retn();
2018 //=============================================================================
2020 * SMESH_Gen_i::Compute
2022 * Compute mesh on a shape
2024 //=============================================================================
2026 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2027 GEOM::GEOM_Object_ptr theShapeObject )
2030 Unexpect aCatch(SALOME_SalomeException);
2031 MESSAGE( "SMESH_Gen_i::Compute" );
2033 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2034 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2035 SALOME::BAD_PARAM );
2037 if ( CORBA::is_nil( theMesh ) )
2038 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2039 SALOME::BAD_PARAM );
2041 // Update Python script
2042 TPythonDump(this) << "isDone = " << this << ".Compute( "
2043 << theMesh << ", " << theShapeObject << ")";
2047 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2048 ASSERT( meshServant );
2049 if ( meshServant ) {
2050 if ( isGeomModifIcon( theMesh ))
2051 meshServant->Clear();
2053 meshServant->Load();
2054 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2055 meshServant->CheckGeomModif();
2056 // get local TopoDS_Shape
2057 TopoDS_Shape myLocShape;
2058 if(theMesh->HasShapeToMesh())
2059 myLocShape = GeomObjectToShape( theShapeObject );
2061 myLocShape = SMESH_Mesh::PseudoShape();
2062 // call implementation compute
2063 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2064 myGen.PrepareCompute( myLocMesh, myLocShape );
2065 int how = ::SMESH_Gen::COMPACT_MESH;
2066 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2067 how |= ::SMESH_Gen::SHAPE_ONLY;
2068 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2069 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2070 myLocMesh.GetMeshDS()->Modified();
2071 UpdateIcons( theMesh );
2073 HighLightInvalid( theMesh, /*isInvalid=*/false );
2077 catch ( std::bad_alloc& ) {
2078 INFOS( "Compute(): lack of memory" );
2080 catch ( SALOME_Exception& S_ex ) {
2081 INFOS( "Compute(): catch exception "<< S_ex.what() );
2084 INFOS( "Compute(): unknown exception " );
2089 //=============================================================================
2091 * SMESH_Gen_i::CancelCompute
2093 * Cancel Compute mesh on a shape
2095 //=============================================================================
2097 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2098 GEOM::GEOM_Object_ptr theShapeObject )
2100 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2102 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2103 TopoDS_Shape myLocShape;
2104 if(theMesh->HasShapeToMesh())
2105 myLocShape = GeomObjectToShape( theShapeObject );
2107 myLocShape = SMESH_Mesh::PseudoShape();
2108 myGen.CancelCompute( myLocMesh, myLocShape);
2112 //=============================================================================
2114 * SMESH_Gen_i::Precompute
2116 * Compute mesh as preview till indicated dimension on shape
2118 //=============================================================================
2120 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2121 GEOM::GEOM_Object_ptr theShapeObject,
2122 SMESH::Dimension theDimension,
2123 SMESH::long_array& theShapesId)
2125 Unexpect aCatch(SALOME_SalomeException);
2126 MESSAGE( "SMESH_Gen_i::Precompute" );
2128 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2129 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2130 SALOME::BAD_PARAM );
2132 if ( CORBA::is_nil( theMesh ) )
2133 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2134 SALOME::BAD_PARAM );
2136 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2139 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2140 meshServant->Load();
2141 ASSERT( meshServant );
2142 if ( meshServant ) {
2143 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2144 meshServant->CheckGeomModif();
2145 // get local TopoDS_Shape
2146 TopoDS_Shape myLocShape;
2147 if(theMesh->HasShapeToMesh())
2148 myLocShape = GeomObjectToShape( theShapeObject );
2150 return result._retn();
2152 // call implementation compute
2153 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2155 ::MeshDimension aDim = (MeshDimension)theDimension;
2156 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2158 int nbShapeId = shapeIds.size();
2159 theShapesId.length( nbShapeId );
2160 // iterates on shapes and collect mesh entities into mesh preview
2161 TSetOfInt::const_iterator idIt = shapeIds.begin();
2162 TSetOfInt::const_iterator idEnd = shapeIds.end();
2163 std::map< int, int > mapOfShIdNb;
2164 std::set< SMESH_TLink > setOfEdge;
2165 std::list< SMDSAbs_ElementType > listOfElemType;
2166 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2167 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2168 TNode2LocalIDMap mapNode2LocalID;
2169 list< TNodeLocalID > connectivity;
2170 int i, nbConnNodes = 0;
2171 std::set< const SMESH_subMesh* > setOfVSubMesh;
2172 // iterates on shapes
2173 for ( ; idIt != idEnd; idIt++ )
2175 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2177 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2178 if ( !sm || !sm->IsMeshComputed() )
2181 const TopoDS_Shape& aSh = sm->GetSubShape();
2182 const int shDim = myGen.GetShapeDim( aSh );
2183 if ( shDim < 1 || shDim > theDimension )
2186 mapOfShIdNb[ *idIt ] = 0;
2187 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2189 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2190 if ( !smDS ) continue;
2192 if ( theDimension == SMESH::DIM_2D )
2194 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2195 while ( faceIt->more() )
2197 const SMDS_MeshElement* face = faceIt->next();
2198 int aNbNode = face->NbNodes();
2200 aNbNode /= 2; // do not take into account additional middle nodes
2202 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2203 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2205 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2206 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2208 listOfElemType.push_back( SMDSAbs_Edge );
2209 connectivity.push_back
2210 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2211 connectivity.push_back
2212 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2218 else if ( theDimension == SMESH::DIM_1D )
2220 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2221 while ( nodeIt->more() )
2223 listOfElemType.push_back( SMDSAbs_Node );
2224 connectivity.push_back
2225 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2227 // add corner nodes by first vertex from edge
2228 SMESH_subMeshIteratorPtr edgeSmIt =
2229 sm->getDependsOnIterator(/*includeSelf*/false,
2230 /*complexShapeFirst*/false);
2231 while ( edgeSmIt->more() )
2233 SMESH_subMesh* vertexSM = edgeSmIt->next();
2234 // check that vertex is not already treated
2235 if ( !setOfVSubMesh.insert( vertexSM ).second )
2237 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2240 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2241 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2242 while ( nodeIt->more() )
2244 listOfElemType.push_back( SMDSAbs_Node );
2245 connectivity.push_back
2246 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2252 // fill node coords and assign local ids to the nodes
2253 int nbNodes = mapNode2LocalID.size();
2254 result->nodesXYZ.length( nbNodes );
2255 TNodeLocalID node2ID = mapNode2LocalID.begin();
2256 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2257 node2ID->second = i;
2258 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2259 result->nodesXYZ[i].x = node->X();
2260 result->nodesXYZ[i].y = node->Y();
2261 result->nodesXYZ[i].z = node->Z();
2263 // fill connectivity
2264 result->elementConnectivities.length( nbConnNodes );
2265 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2266 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2267 result->elementConnectivities[i] = (*connIt)->second;
2270 // fill element types
2271 result->elementTypes.length( listOfElemType.size() );
2272 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2273 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2274 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2276 SMDSAbs_ElementType elemType = *typeIt;
2277 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2278 result->elementTypes[i].isPoly = false;
2279 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2282 // correct number of shapes
2283 theShapesId.length( mapOfShIdNb.size() );
2287 catch ( std::bad_alloc& ) {
2288 INFOS( "Precompute(): lack of memory" );
2290 catch ( SALOME_Exception& S_ex ) {
2291 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2294 INFOS( "Precompute(): unknown exception " );
2296 return result._retn();
2300 //=============================================================================
2302 * SMESH_Gen_i::Evaluate
2304 * Evaluate mesh on a shape
2306 //=============================================================================
2308 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2309 GEOM::GEOM_Object_ptr theShapeObject)
2311 Unexpect aCatch(SALOME_SalomeException);
2312 MESSAGE( "SMESH_Gen_i::Evaluate" );
2314 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2315 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2317 if ( CORBA::is_nil( theMesh ) )
2318 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2320 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2321 nbels->length(SMESH::Entity_Last);
2322 int i = SMESH::Entity_Node;
2323 for (; i < SMESH::Entity_Last; i++)
2326 // Update Python script
2327 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2328 << theMesh << ", " << theShapeObject << ")";
2332 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2333 ASSERT( meshServant );
2334 if ( meshServant ) {
2335 meshServant->Load();
2336 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2337 meshServant->CheckGeomModif();
2338 // get local TopoDS_Shape
2339 TopoDS_Shape myLocShape;
2340 if(theMesh->HasShapeToMesh())
2341 myLocShape = GeomObjectToShape( theShapeObject );
2343 myLocShape = SMESH_Mesh::PseudoShape();
2344 // call implementation compute
2345 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2346 MapShapeNbElems aResMap;
2347 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2348 MapShapeNbElemsItr anIt = aResMap.begin();
2349 for(; anIt!=aResMap.end(); anIt++) {
2350 const vector<smIdType>& aVec = (*anIt).second;
2351 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2352 smIdType nbElem = aVec[i];
2353 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2355 SMESH_subMesh* sm = anIt->first;
2356 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2357 const SMESH_Algo* algo = sm->GetAlgo();
2358 if ( (algo && !error.get()) || error->IsOK() )
2359 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2363 nbels[i] += aVec[i];
2367 return nbels._retn();
2370 catch ( std::bad_alloc& ) {
2371 INFOS( "Evaluate(): lack of memory" );
2373 catch ( SALOME_Exception& S_ex ) {
2374 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2377 INFOS( "Evaluate(): unknown exception " );
2380 return nbels._retn();
2383 //================================================================================
2385 * \brief Return geometrical object the given element is built on
2386 * \param theMesh - the mesh the element is in
2387 * \param theElementID - the element ID
2388 * \param theGeomName - the name of the result geom object if it is not yet published
2389 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2391 //================================================================================
2393 GEOM::GEOM_Object_ptr
2394 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2395 SMESH::smIdType theElementID,
2396 const char* theGeomName)
2398 Unexpect aCatch(SALOME_SalomeException);
2400 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2401 if ( !geom->_is_nil() ) {
2402 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2403 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2405 // try to find the corresponding SObject
2406 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2407 if ( SObj->_is_nil() ) // submesh can be not found even if published
2409 // try to find published submesh
2410 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2411 if ( !geom->IsMainShape() && list->length() == 1 ) {
2412 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2413 SALOMEDS::ChildIterator_wrap it;
2414 if ( !mainSO->_is_nil() ) {
2415 it = getStudyServant()->NewChildIterator( mainSO );
2417 if ( !it->_is_nil() ) {
2418 for ( it->InitEx(true); it->More(); it->Next() ) {
2419 SALOMEDS::SObject_wrap so = it->Value();
2420 CORBA::Object_var obj = SObjectToObject( so );
2421 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2422 if ( !subGeom->_is_nil() ) {
2423 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2424 if ( subList->length() == 1 && list[0] == subList[0] ) {
2434 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2435 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2437 // return only published geometry
2438 if ( !SObj->_is_nil() ) {
2439 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2440 CORBA::Object_var obj = SObjectToObject( SObj );
2441 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2445 return GEOM::GEOM_Object::_nil();
2448 //================================================================================
2450 * \brief Return geometrical object the given element is built on.
2451 * \param theMesh - the mesh the element is in
2452 * \param theElementID - the element ID
2453 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2455 //================================================================================
2457 GEOM::GEOM_Object_ptr
2458 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2459 SMESH::smIdType theElementID)
2461 Unexpect aCatch(SALOME_SalomeException);
2462 if ( CORBA::is_nil( theMesh ) )
2463 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2465 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2466 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2468 // get a core mesh DS
2469 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2470 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2472 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2473 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2474 // find the element in mesh
2475 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2476 // find a shape id by the element
2477 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2478 // get a geom object by the shape id
2479 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2480 if ( geom->_is_nil() ) {
2481 // try to find a published sub-shape
2482 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2483 SALOMEDS::ChildIterator_wrap it;
2484 if ( !mainSO->_is_nil() ) {
2485 it = getStudyServant()->NewChildIterator( mainSO );
2487 if ( !it->_is_nil() ) {
2488 for ( it->InitEx(true); it->More(); it->Next() ) {
2489 SALOMEDS::SObject_wrap so = it->Value();
2490 CORBA::Object_var obj = SObjectToObject( so );
2491 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2492 if ( !subGeom->_is_nil() ) {
2493 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2494 if ( subList->length() == 1 && shapeID == subList[0] ) {
2502 if ( geom->_is_nil() ) {
2504 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2505 if ( !op->_is_nil() )
2506 geom = op->GetSubShape( mainShape, shapeID );
2511 if ( !geom->_is_nil() ) {
2512 GeomObjectToShape( geom ); // let geom client remember the found shape
2513 return geom._retn();
2518 return GEOM::GEOM_Object::_nil();
2521 //================================================================================
2523 * SMESH_Gen_i::Concatenate
2525 * Concatenate the given meshes into one mesh
2527 //================================================================================
2529 SMESH::SMESH_Mesh_ptr
2530 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2531 CORBA::Boolean theUniteIdenticalGroups,
2532 CORBA::Boolean theMergeNodesAndElements,
2533 CORBA::Double theMergeTolerance,
2534 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2536 return ConcatenateCommon(theMeshesArray,
2537 theUniteIdenticalGroups,
2538 theMergeNodesAndElements,
2544 //================================================================================
2546 * SMESH_Gen_i::ConcatenateWithGroups
2548 * Concatenate the given meshes into one mesh
2549 * Create the groups of all elements from initial meshes
2551 //================================================================================
2553 SMESH::SMESH_Mesh_ptr
2554 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2555 CORBA::Boolean theUniteIdenticalGroups,
2556 CORBA::Boolean theMergeNodesAndElements,
2557 CORBA::Double theMergeTolerance,
2558 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2560 return ConcatenateCommon(theMeshesArray,
2561 theUniteIdenticalGroups,
2562 theMergeNodesAndElements,
2568 //================================================================================
2570 * SMESH_Gen_i::ConcatenateCommon
2572 * Concatenate the given meshes into one mesh
2574 //================================================================================
2576 SMESH::SMESH_Mesh_ptr
2577 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2578 CORBA::Boolean theUniteIdenticalGroups,
2579 CORBA::Boolean theMergeNodesAndElements,
2580 CORBA::Double theMergeTolerance,
2581 CORBA::Boolean theCommonGroups,
2582 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2584 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2585 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2587 // create mesh if theMeshToAppendTo not provided
2588 SMESH::SMESH_Mesh_var newMesh;
2589 if ( CORBA::is_nil( theMeshToAppendTo ))
2590 newMesh = CreateEmptyMesh();
2592 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2593 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2594 if ( !newImpl ) return newMesh._retn();
2597 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2598 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2600 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2601 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2602 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2603 TGroupsMap groupsMap;
2604 TListOfNewGroups listOfNewGroups;
2606 if ( !CORBA::is_nil( theMeshToAppendTo ))
2608 // fill groupsMap with existing groups
2609 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2610 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2612 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2613 if ( !group->_is_nil() )
2615 CORBA::String_var name = group->GetName();
2616 SMESH::ElementType type = group->GetType();
2617 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2622 ::SMESH_MeshEditor newEditor( &locMesh );
2623 ::SMESH_MeshEditor::ElemFeatures elemType;
2625 // loop on sub-meshes
2626 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2628 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2629 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2630 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2631 if ( !initImpl ) continue;
2632 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2636 // assure that IDs increment by one during iteration
2637 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2638 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2639 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2640 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2642 initMeshDS->Modified();
2643 initMeshDS->CompactMesh();
2646 // remember nb of elements before filling in
2647 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2651 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2652 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2653 while ( elemIt->more() )
2655 SMESH_NodeXYZ node = elemIt->next();
2656 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2661 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2662 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2663 bool hasElems = (( srcElemTypes->length() > 1 ) ||
2664 ( srcElemTypes->length() == 1 && srcElemTypes[0] != SMESH::NODE ));
2667 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2668 while ( elemIt->more() )
2670 const SMDS_MeshElement* elem = elemIt->next();
2671 elemType.myNodes.resize( elem->NbNodes() );
2673 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2674 for ( int k = 0; itNodes->more(); k++)
2676 const SMDS_MeshNode* node = itNodes->next();
2677 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2680 // creates a corresponding element on existent nodes in new mesh
2681 newElems[ elem->GetID() ] =
2682 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2684 newEditor.ClearLastCreated(); // forget the history
2688 // create groups of just added elements
2689 SMESH::SMESH_Group_var newGroup;
2690 SMESH::ElementType groupType;
2691 if ( theCommonGroups )
2694 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2696 // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2697 static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2698 "Update names of ElementType's!!!" );
2700 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2702 for( groupType = SMESH::NODE;
2703 groupType < SMESH::NB_ELEMENT_TYPES;
2704 groupType = (SMESH::ElementType)( groupType + 1 ))
2706 if ( curState[ groupType ] <= prevState[ groupType ])
2707 continue; // no elements of groupType added from the i-th mesh
2709 // make a group name
2710 std::string groupName = "Gr";
2711 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2713 CORBA::String_var name = meshSO->GetName();
2717 groupName += typeNames[ groupType ];
2719 // make and fill a group
2720 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2721 std::vector< const SMDS_MeshElement* > & elemVec =
2722 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2723 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2725 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2727 for ( size_t j = 0; j < elemVec.size(); ++j )
2729 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2730 grpDS->Add( elemVec[j] );
2734 listOfNewGroups.clear();
2735 listOfNewGroups.push_back( newGroup );
2736 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2741 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2745 SMESH::SMESH_GroupBase_ptr group;
2746 CORBA::String_var groupName;
2747 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2749 // loop on groups of a source mesh
2750 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2751 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2753 group = listOfGroups[iG];
2754 groupType = group->GetType();
2755 groupName = group->GetName();
2756 std::string name = groupName.in();
2758 // convert a list of IDs
2759 newIDs->length( group->Size() );
2760 std::vector< const SMDS_MeshElement* > & elemVec =
2761 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2762 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2764 while ( itGrElems->more() )
2766 const SMDS_MeshElement* elem = itGrElems->next();
2767 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2769 newIDs[ nbElems++ ] = newElem->GetID();
2771 newIDs->length( nbElems );
2773 // check that a current group name and type don't have identical ones in final mesh
2774 listOfNewGroups.clear();
2775 TNameAndType nameAndType( name, groupType );
2776 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2777 if ( anIter == groupsMap.end() )
2779 // add a new group in the mesh
2780 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2781 newGroup->Add( newIDs );
2783 listOfNewGroups.push_back( newGroup );
2784 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2786 else if ( theUniteIdenticalGroups )
2788 // unite identical groups
2789 TListOfNewGroups& aNewGroups = anIter->second;
2790 aNewGroups.front()->Add( newIDs );
2794 // rename identical groups
2795 newGroup = newImpl->CreateGroup( groupType, groupName );
2796 newGroup->Add( newIDs );
2798 TListOfNewGroups& newGroups = anIter->second;
2799 std::string newGroupName;
2800 if ( newGroups.size() == 1 )
2802 newGroupName = name + "_1";
2803 newGroups.front()->SetName( newGroupName.c_str() );
2805 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2806 newGroup->SetName( newGroupName.c_str() );
2807 newGroups.push_back( newGroup );
2810 } // if an IDSource is a mesh
2813 if ( theMergeNodesAndElements ) // merge nodes
2815 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2816 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2817 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2818 /*SeparateCornersAndMedium=*/ false );
2819 newEditor.MergeNodes( groupsOfNodes );
2821 newEditor.MergeEqualElements();
2824 // Update Python script
2825 pythonDump << newMesh << " = " << this
2826 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2827 << theMeshesArray << ", "
2828 << theUniteIdenticalGroups << ", "
2829 << theMergeNodesAndElements << ", "
2830 << TVar( theMergeTolerance ) << ", "
2831 << theMeshToAppendTo << " )";
2833 pPythonDump.reset(); // enable python dump from GetGroups()
2835 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2836 if ( !newMesh->_is_nil() )
2838 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2841 // IPAL21468 Change icon of compound because it need not be computed.
2842 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2843 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2845 newMeshDS->Modified();
2847 return newMesh._retn();
2851 //================================================================================
2853 * \brief Create a mesh by copying a part of another mesh
2854 * \param mesh - TetraHedron mesh
2855 * \param meshName Name of the created mesh
2856 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2858 //================================================================================
2860 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateDualMesh(SMESH::SMESH_IDSource_ptr mesh,
2861 const char* meshName,
2862 CORBA::Boolean adapt_to_shape)
2864 Unexpect aCatch(SALOME_SalomeException);
2866 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2867 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2869 // 1. Get source mesh
2871 if ( CORBA::is_nil( mesh ))
2872 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2874 SMESH::SMESH_Mesh_var srcMesh = mesh->GetMesh();
2875 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2877 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2879 CORBA::String_var mesh_var=GetORB()->object_to_string(mesh);
2880 std::string mesh_ior = mesh_var.in();
2882 //temporary folder for the generation of the med file
2883 fs::path tmp_folder = fs::temp_directory_path() / fs::unique_path(fs::path("dual_mesh-%%%%"));
2884 fs::create_directories(tmp_folder);
2885 fs::path dual_mesh_file = tmp_folder / fs::path("tmp_dual_mesh.med");
2886 std::string mesh_name(meshName);
2887 MESSAGE("Working in folder" + tmp_folder.string());
2889 // Running Python script
2890 assert(Py_IsInitialized());
2891 PyGILState_STATE gstate;
2892 gstate = PyGILState_Ensure();
2901 std::string cmd="import salome.smesh.smesh_tools as smt\n";
2902 cmd +="smt.smesh_create_dual_mesh(\"" + mesh_ior + "\", r\"" +
2903 dual_mesh_file.string() + "\", mesh_name=\"" + mesh_name + "\", adapt_to_shape=" + ats + ")";
2906 PyObject *py_main = PyImport_AddModule("__main__");
2907 PyObject *py_dict = PyModule_GetDict(py_main);
2908 PyObject *local_dict = PyDict_New();
2910 PyRun_String(cmd.c_str(), Py_file_input, py_dict, local_dict);
2912 if (PyErr_Occurred()) {
2913 // Restrieving python error
2914 MESSAGE("Catching error");
2915 PyObject *errtype, *errvalue, *traceback;
2916 PyErr_Fetch(&errtype, &errvalue, &traceback);
2917 if(errvalue != NULL) {
2918 MESSAGE("Error has a value");
2919 PyObject *s = PyObject_Str(errvalue);
2921 std::string msg = PyUnicode_AsUTF8AndSize(s, &size);
2922 msg = "Issue with the execution of create_dual_mesh:\n"+msg;
2923 MESSAGE("throwing exception");
2924 // We need to deactivate the GIL before throwing the exception
2925 PyGILState_Release(gstate);
2926 THROW_SALOME_CORBA_EXCEPTION(msg.c_str(), SALOME::INTERNAL_ERROR );
2929 Py_XDECREF(errvalue);
2930 Py_XDECREF(errtype);
2931 Py_XDECREF(traceback);
2934 PyGILState_Release(gstate);
2936 MESSAGE("Mesh created in " + dual_mesh_file.string());
2938 // Import created MED
2939 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2940 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2942 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2943 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2944 if ( !meshSO->_is_nil() )
2946 SetName( meshSO, meshName, meshName );
2947 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2949 int ret = newMesh_i->ImportMEDFile(dual_mesh_file.string().c_str(), meshName);
2951 THROW_SALOME_CORBA_EXCEPTION( "Issue when importing mesh", SALOME::INTERNAL_ERROR );
2954 SMESH_Mesh& newMesh2 = newMesh_i->GetImpl();
2957 MESSAGE("Loading file: " << dual_mesh_file.string() << " with mesh " << meshName);
2958 int ret = newMesh2.MEDToMesh(dual_mesh_file.c_str(), meshName);
2961 newMesh_i->GetImpl().GetMeshDS()->Modified();
2963 *pyDump << newMesh << " = " << this
2964 << ".CreateDualMesh("
2966 << "'" << mesh_name << "', "
2969 pyDumpDeleter.reset(); // allow dump in GetGroups()
2971 if ( srcMesh_i->GetImpl().GetGroupIds().size() > 0 ) // dump created groups
2972 MESSAGE("Dump of groups");
2973 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2976 fs::remove_all(tmp_folder);
2979 return newMesh._retn();
2982 //================================================================================
2984 * \brief Create a mesh by copying a part of another mesh
2985 * \param meshPart - a part of mesh to copy
2986 * \param toCopyGroups - to create in the new mesh groups
2987 * the copied elements belongs to
2988 * \param toKeepIDs - to preserve IDs of the copied elements or not
2989 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2991 //================================================================================
2993 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2994 const char* meshName,
2995 CORBA::Boolean toCopyGroups,
2996 CORBA::Boolean toKeepIDs)
2998 Unexpect aCatch(SALOME_SalomeException);
3000 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
3001 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
3003 // 1. Get source mesh
3005 if ( CORBA::is_nil( meshPart ))
3006 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
3008 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
3009 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
3011 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
3013 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
3015 // 2. Make a new mesh
3017 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
3018 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
3020 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
3021 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
3022 if ( !meshSO->_is_nil() )
3024 SetName( meshSO, meshName, "Mesh" );
3025 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
3027 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3028 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3029 ::SMESH_MeshEditor::ElemFeatures elemType;
3031 // 3. Get elements to copy
3033 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
3034 TIDSortedElemSet srcElems;
3035 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
3036 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
3039 srcElemIt = srcMeshDS->elementsIterator();
3040 srcNodeIt = srcMeshDS->nodesIterator();
3044 SMESH::smIdType_array_var ids = meshPart->GetIDs();
3045 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
3047 for ( CORBA::ULong i=0; i < ids->length(); i++ )
3048 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
3049 srcElems.insert( elem );
3053 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
3054 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
3055 srcElems.insert( elem );
3057 if ( srcElems.empty() )
3058 return newMesh._retn();
3060 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
3061 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
3066 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
3067 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
3068 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
3070 const SMDS_MeshNode *nSrc, *nTgt;
3071 vector< const SMDS_MeshNode* > nodes;
3072 while ( srcElemIt->more() )
3074 const SMDS_MeshElement * elem = srcElemIt->next();
3076 nodes.resize( elem->NbNodes());
3077 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3079 for ( iN = 0; nIt->more(); ++iN )
3081 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3082 nTgt = newMeshDS->FindNode( nSrc->GetID());
3084 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3089 for ( iN = 0; nIt->more(); ++iN )
3091 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3092 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3094 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3095 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3099 if ( elem->GetType() != SMDSAbs_Node )
3101 elemType.Init( elem, /*basicOnly=*/false );
3102 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3104 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3105 if ( toCopyGroups && !toKeepIDs )
3106 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3108 } // while ( srcElemIt->more() )
3110 // 4(b). Copy free nodes
3112 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3114 while ( srcNodeIt->more() )
3116 nSrc = srcNodeIt->next();
3117 if ( nSrc->NbInverseElements() == 0 )
3120 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3122 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3129 int nbNewGroups = 0;
3132 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3133 while ( gIt->more() )
3135 SMESH_Group* group = gIt->next();
3136 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3138 // Check group type. We copy nodal groups containing nodes of copied element
3139 SMDSAbs_ElementType groupType = groupDS->GetType();
3140 if ( groupType != SMDSAbs_Node &&
3141 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3142 continue; // group type differs from types of meshPart
3144 // Find copied elements in the group
3145 vector< const SMDS_MeshElement* > groupElems;
3146 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3149 const SMDS_MeshElement* foundElem;
3150 if ( groupType == SMDSAbs_Node )
3152 while ( eIt->more() )
3153 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3154 groupElems.push_back( foundElem );
3158 while ( eIt->more() )
3159 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3160 groupElems.push_back( foundElem );
3165 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3166 if ( e2eMap.empty() ) continue;
3167 smIdType minID = e2eMap.begin()->first->GetID();
3168 smIdType maxID = e2eMap.rbegin()->first->GetID();
3169 TE2EMap::iterator e2e;
3170 while ( eIt->more() && groupElems.size() < e2eMap.size())
3172 const SMDS_MeshElement* e = eIt->next();
3173 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3174 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3175 groupElems.push_back( e2e->second );
3179 if ( !groupElems.empty() )
3181 SMESH::SMESH_Group_var newGroupObj =
3182 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3183 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3185 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3186 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3187 for ( unsigned i = 0; i < groupElems.size(); ++i )
3188 smdsGroup.Add( groupElems[i] );
3196 newMeshDS->Modified();
3198 *pyDump << newMesh << " = " << this
3199 << ".CopyMesh( " << meshPart << ", "
3200 << "'" << meshName << "', "
3201 << toCopyGroups << ", "
3202 << toKeepIDs << ")";
3204 pyDumpDeleter.reset(); // allow dump in GetGroups()
3206 if ( nbNewGroups > 0 ) // dump created groups
3207 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3209 return newMesh._retn();
3213 namespace // utils for CopyMeshWithGeom()
3215 typedef std::map< std::string, std::string > TStr2StrMap;
3216 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3217 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3218 typedef std::map< std::string, int > TName2IndexMap;
3220 //================================================================================
3222 * \brief Return a new sub-shape corresponding to an old one
3224 //================================================================================
3228 SMESH_Mesh_i* mySrcMesh_i;
3229 SMESH_Mesh_i* myNewMesh_i;
3230 SMESH_Gen_i* myGen_i;
3234 TStr2StrMap myOld2NewEntryMap; // map of study entries
3236 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3237 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3238 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3241 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3243 // not directly relating to shape search
3244 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3246 //================================================================================
3248 * \brief Constructor
3250 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3251 SMESH_Mesh_i* newMesh_i,
3252 SMESH_Gen_i* smeshGen_i )
3253 : mySrcMesh_i( srcMesh_i ),
3254 myNewMesh_i( newMesh_i ),
3255 myGen_i ( smeshGen_i ),
3256 myToPublish( smeshGen_i->IsEnablePublish() ),
3257 myGIPMapDone( false )
3259 // retrieve from the study shape mapping made thanks to
3260 // "Set presentation parameters and sub-shapes from arguments" option
3262 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3263 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3264 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3265 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3266 if ( newSO->_is_nil() )
3268 myToPublish = false;
3271 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3273 CORBA::String_var oldEntry = oldSO->GetID();
3274 CORBA::String_var newEntry = newSO->GetID();
3275 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3276 std::string( newEntry.in() )));
3277 std::string newMainEntry = newEntry.in();
3279 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3280 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3281 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3282 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3283 /*groupsOnly=*/false );
3284 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3286 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3287 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3288 bool refFound = false;
3289 for ( ; anIter->More(); anIter->Next() )
3291 SALOMEDS::SObject_wrap so = anIter->Value();
3292 if ( so->ReferencedObject( oldSO.inout() ))
3294 oldEntry = oldSO->GetID();
3295 newEntry = newSO->GetID();
3296 if (( refFound = ( newMainEntry != oldEntry.in() )))
3297 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3298 std::string( newEntry.in() )));
3303 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3304 if ( father->_is_equivalent( mainShapeNew ))
3306 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3307 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3308 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3309 CORBA::String_var name = newSO->GetName();
3311 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3317 //================================================================================
3319 * \brief Find a new sub-shape corresponding to an old one
3321 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3324 return GEOM::GEOM_Object::_duplicate( oldShape );
3326 GEOM::GEOM_Object_var newShape;
3328 if ( CORBA::is_nil( oldShape ))
3329 return newShape._retn();
3331 if ( !isChildOfOld( oldShape ))
3332 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3334 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3335 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3337 // try to find by entry or name
3340 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3341 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3342 if ( o2nID != myOld2NewEntryMap.end() )
3344 newShape = getShapeByEntry( o2nID->second );
3346 if ( newShape->_is_nil() )
3348 CORBA::String_var name = oldShape->GetName();
3349 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3350 if ( n2ind != myName2SubshapeIndex.end() )
3352 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3353 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3354 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3355 if ( oldIndices->length() == 0 ||
3356 newIndices->length() == 0 ||
3357 getShapeType( myNewMesh_i, newIndices[0] ) !=
3358 getShapeType( mySrcMesh_i, oldIndices[0] ))
3359 newShape = GEOM::GEOM_Object::_nil();
3364 if ( newShape->_is_nil() )
3366 // try to construct a new sub-shape using myGIPMap
3368 std::vector< int > newIndices;
3369 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3370 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3372 findNewIDs( oldIndices[i], newIndices );
3374 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3377 newShape = getInPlace( oldShape );
3379 if ( !newIndices.empty() && newShape->_is_nil() )
3381 // search for a sub-shape with same ids
3382 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3383 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3384 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3385 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3387 if ( newShape->_is_nil() )
3390 // create a new shape
3391 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3393 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3395 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3396 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3398 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3399 newIndicesList->length( newIndices.size() );
3400 for ( size_t i = 0; i < newIndices.size(); ++i )
3401 newIndicesList[ i ] = newIndices[ i ];
3402 grOp->UnionIDs( newShape, newIndicesList );
3406 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3407 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3416 if ( !newShape->_is_nil() && myToPublish )
3418 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3419 if ( !newEntry.in() || !newEntry.in()[0] )
3421 CORBA::String_var name = oldShape->GetName();
3422 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3423 newEntry = newShape->GetStudyEntry();
3424 oldEntry = oldShape->GetStudyEntry();
3425 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3426 std::string( newEntry.in() )));
3430 return newShape._retn();
3433 //================================================================================
3435 * \brief Return a study entry of a new shape by study entry of the old one
3437 std::string FindNew( const std::string & oldEntry )
3442 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3443 if ( o2nID != myOld2NewEntryMap.end() )
3444 return o2nID->second;
3446 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3447 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3450 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3451 if ( newShape->_is_nil() )
3452 return std::string();
3454 CORBA::String_var newEntry = newShape->GetStudyEntry();
3455 return newEntry.in();
3458 //================================================================================
3460 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3461 * Return zero if not found or there are more than one new ID
3463 int FindNew( int oldID )
3472 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3474 if ( myGIPMap[ oldID ].length() == 1 )
3476 newID = myGIPMap[ oldID ][ 0 ];
3478 else if ( myGIPMap[ oldID ].length() > 1 &&
3479 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3481 // select a meshed VERTEX
3482 SMESH_subMesh* newSM;
3483 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3484 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3485 ( !newSM->IsEmpty() ))
3486 newID = myGIPMap[ oldID ][ i ];
3492 //================================================================================
3494 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3495 * Return zero if the old shape is not kept as is in the new shape.
3497 int FindNewNotChanged( SMESH_subMesh* oldSM )
3500 return oldSM->GetId();
3502 int newID = FindNew( oldSM->GetId() );
3506 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3510 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3511 // one new sub-shape of the same type.
3513 if ( oldSM->DependsOn().size() !=
3514 newSM->DependsOn().size() )
3517 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3518 while ( srcSMIt->more() )
3520 oldSM = srcSMIt->next();
3521 int newSubID = FindNew( oldSM->GetId() );
3522 if ( getShapeType( myNewMesh_i, newSubID ) !=
3523 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3529 //================================================================================
3531 * \brief Return shape by study entry
3533 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3535 GEOM::GEOM_Object_var shape;
3536 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3537 if ( !so->_is_nil() )
3539 CORBA::Object_var obj = so->GetObject();
3540 shape = GEOM::GEOM_Object::_narrow( obj );
3542 return shape._retn();
3545 //================================================================================
3547 * \brief Fill myGIPMap by calling GetInPlaceMap()
3551 if ( !myGIPMapDone )
3553 myGIPMapDone = true;
3555 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3556 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3557 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3558 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3561 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3565 myGIPMap = new GEOM::ListOfListOfLong();
3570 //================================================================================
3572 * \brief Get new sub-shape by calling GetInPlace()
3574 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3576 GEOM::GEOM_Object_var newShape;
3578 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3579 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3580 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3583 newShape = op->GetInPlace( mainShapeNew, oldShape );
3588 return newShape._retn();
3591 //================================================================================
3593 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3594 * number of found IDs
3596 int findNewIDs( int oldID, std::vector< int >& newIDs )
3598 size_t prevNbIDs = newIDs.size();
3600 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3602 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3603 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3605 return newIDs.size() - prevNbIDs;
3608 //================================================================================
3610 * \brief Check if an object relates to the old shape
3612 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3614 if ( CORBA::is_nil( oldShape ))
3616 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3617 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3618 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3619 mainShapeOld1->_is_equivalent( oldShape ));
3622 //================================================================================
3624 * \brief Return shape type by shape ID
3626 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3628 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3629 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3630 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3633 //================================================================================
3635 * \brief Store a source sub-shape for which a counterpart not found and
3636 * a smesh object invalid due to that
3638 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3639 SALOMEDS::SObject_wrap smeshSO )
3641 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3642 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3644 CORBA::String_var smeshEntry = smeshSO->GetID();
3645 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3649 //================================================================================
3651 * \brief Store a source sub-shape for which a counterpart not found and
3652 * a smesh object invalid due to that
3654 void AddInvalid( std::string geomEntry,
3655 SALOMEDS::SObject_wrap smeshSO )
3657 if ( !geomEntry.empty() )
3659 CORBA::String_var smeshEntry = smeshSO->GetID();
3660 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3664 //================================================================================
3666 * \brief Store a source sub-shape for which a counterpart not found and
3667 * a smesh object invalid due to that
3669 void AddInvalid( int oldGeomID,
3670 SALOMEDS::SObject_wrap smeshSO )
3672 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3673 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3676 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3677 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3679 SMESH_Comment geomName( typeName[ shapeType ]);
3680 geomName << " #" << oldGeomID;
3682 CORBA::String_var smeshEntry = smeshSO->GetID();
3683 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3686 //================================================================================
3688 * \brief Return entries of a source sub-shape for which a counterpart not found and
3689 * of smesh objects invalid due to that
3691 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3692 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3695 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3696 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3698 nbSO += 1 + entry2entrySet->second.size();
3700 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3701 theInvalidEntries->length ( nbSO );
3702 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3704 entry2entrySet = myInvalidMap.begin();
3705 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3707 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3709 std::set< std::string > & entrySet = entry2entrySet->second;
3710 std::set< std::string >::iterator entry = entrySet.begin();
3711 for ( ; entry != entrySet.end(); ++entry )
3713 theInvalidEntries[ iEntry++ ] = entry->c_str();
3715 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3716 if ( !so->_is_nil() )
3717 theInvalidMeshSObjects[ iSO++ ] = so;
3722 }; // struct ShapeMapper
3724 //================================================================================
3726 * \brief Append an item to a CORBA sequence
3728 template < class CORBA_seq, class ITEM >
3729 void append( CORBA_seq& seq, ITEM item )
3731 if ( !CORBA::is_nil( item ))
3733 seq->length( 1 + seq->length() );
3734 seq[ seq->length() - 1 ] = item;
3737 } // namespace // utils for CopyMeshWithGeom()
3739 //================================================================================
3741 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3742 * \param [in] sourceMesh - a mesh to copy
3743 * \param [in] newGeometry - a new geometry
3744 * \param [in] toCopyGroups - to create groups in the new mesh
3745 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3746 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3747 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3748 * \param [out] newMesh - return a new mesh
3749 * \param [out] newGroups - return new groups
3750 * \param [out] newSubmeshes - return new sub-meshes
3751 * \param [out] newHypotheses - return new algorithms and hypotheses
3752 * \param [out] invalidEntries - return study entries of objects whose
3753 * counterparts are not found in the newGeometry, followed by entries
3754 * of mesh sub-objects that are invalid because they depend on a not found
3755 * preceding sub-shape
3756 * \return CORBA::Boolean - is a success
3758 //================================================================================
3760 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3761 GEOM::GEOM_Object_ptr theNewGeometry,
3762 const char* theMeshName,
3763 CORBA::Boolean theToCopyGroups,
3764 CORBA::Boolean theToReuseHypotheses,
3765 CORBA::Boolean theToCopyElements,
3766 SMESH::SMESH_Mesh_out theNewMesh,
3767 SMESH::ListOfGroups_out theNewGroups,
3768 SMESH::submesh_array_out theNewSubmeshes,
3769 SMESH::ListOfHypothesis_out theNewHypotheses,
3770 SMESH::string_array_out theInvalidEntries)
3772 if ( CORBA::is_nil( theSourceMesh ) ||
3773 CORBA::is_nil( theNewGeometry ))
3774 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3776 if ( !theSourceMesh->HasShapeToMesh() )
3777 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3782 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3784 theNewMesh = CreateMesh( theNewGeometry );
3785 theNewGroups = new SMESH::ListOfGroups();
3786 theNewSubmeshes = new SMESH::submesh_array();
3787 theNewHypotheses = new SMESH::ListOfHypothesis();
3788 theInvalidEntries = new SMESH::string_array();
3790 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3792 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3793 GEOM::GEOM_Object_var geom, newGeom;
3794 SALOMEDS::SObject_wrap so;
3796 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3797 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3800 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3802 // treat hypotheses of mesh and sub-meshes
3803 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3804 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3806 bool isSubMesh = ( iSM < smList->length() );
3809 // create a new sub-mesh
3810 SMESH::SMESH_subMesh_var newSM;
3811 geom = smList[iSM]->GetSubShape();
3812 so = ObjectToSObject( smList[iSM] );
3813 CORBA::String_var name;
3814 if ( !so->_is_nil() )
3815 name = so->GetName();
3816 newGeom = shapeMapper.FindNew( geom );
3817 if ( newGeom->_is_nil() )
3819 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3820 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3825 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3827 append( theNewSubmeshes, newSM );
3829 if ( newGeom->_is_nil() )
3830 continue; // don't assign hypotheses
3834 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3836 so = ObjectToSObject( theNewMesh );
3837 SetName( so, theMeshName, "Mesh" );
3840 // assign hypotheses
3841 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3842 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3844 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3845 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3847 // get geometry hyp depends on
3848 std::vector< std::string > entryArray;
3849 std::vector< int > subIDArray;
3850 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3852 if ( !theToReuseHypotheses || dependsOnGeom )
3854 // create a new hypothesis
3855 CORBA::String_var type = hyp->GetName();
3856 CORBA::String_var lib = hyp->GetLibName();
3857 CORBA::String_var data = hyp_i->SaveTo();
3860 hyp = CreateHypothesis( type, lib );
3861 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3862 hyp_i->LoadFrom( data.in() );
3863 append( theNewHypotheses, hyp );
3867 // update geometry hyp depends on
3868 if ( dependsOnGeom )
3870 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3872 if ( !entryArray[ iGeo ].empty() )
3874 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3875 if ( newEntry.empty() )
3878 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3879 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3881 entryArray[ iGeo ] = newEntry;
3884 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3886 if ( subIDArray[ iGeo ] > 0 )
3888 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3892 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3893 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3895 subIDArray[ iGeo ] = newID;
3898 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3902 CORBA::String_var errorText;
3903 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3904 if ( errorText.in()[0] )
3907 } // loop on hypotheses
3908 } // loop on sub-meshes and mesh
3911 // copy mesh elements, keeping IDs
3912 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3913 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3915 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3916 ::SMESH_MeshEditor::ElemFeatures elemData;
3918 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3919 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3920 /*vertexLast=*/false);
3921 while ( srcSMIt->more() )
3923 SMESH_subMesh* srcSM = srcSMIt->next();
3924 if ( srcSM->IsEmpty() )
3925 continue; // not yet computed
3926 int newID = shapeMapper.FindNewNotChanged( srcSM );
3930 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3931 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3932 while ( nIt->more() )
3934 SMESH_NodeXYZ node( nIt->next() );
3935 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3937 const SMDS_PositionPtr pos = node->GetPosition();
3938 const double* uv = pos->GetParameters();
3939 switch ( pos->GetTypeOfPosition() )
3941 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3942 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3943 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3944 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3948 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3949 while( eIt->more() )
3951 const SMDS_MeshElement* e = eIt->next();
3952 elemData.Init( e, /*basicOnly=*/false );
3953 elemData.SetID( e->GetID() );
3954 elemData.myNodes.resize( e->NbNodes() );
3955 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3957 for ( iN = 0; nnIt->more(); ++iN )
3959 const SMDS_MeshNode* srcNode = nnIt->next();
3960 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3961 if ( !elemData.myNodes[ iN ])
3964 if ( iN == elemData.myNodes.size() )
3965 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3966 newMeshDS->SetMeshElementOnShape( newElem, newID );
3968 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3969 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3972 newMeshDS->Modified();
3978 TStr2StrMap old2newGroupMap;
3980 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3982 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3983 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3984 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3986 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3987 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3988 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3990 CORBA::String_var name = groups[ i ]->GetName();
3991 SMESH::ElementType elemType = groups[ i ]->GetType();
3993 SMESH::SMESH_GroupBase_var newGroup;
3995 if ( !stdlGroup->_is_nil() )
3997 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3999 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
4000 const bool isElem = ( elemType != SMESH::NODE );
4001 CORBA::ULong iE = 0;
4002 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
4003 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
4005 if ( iE < elemIDs->length() )
4007 stdlGroup = theNewMesh->CreateGroup( elemType, name );
4008 stdlGroup->Add( elemIDs );
4009 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
4013 else if ( !geomGroup->_is_nil() )
4015 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
4016 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
4017 if ( newGeom->_is_nil() )
4019 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
4020 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
4025 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
4028 else if ( !fltrGroup->_is_nil() )
4030 // replace geometry in a filter
4031 SMESH::Filter_var filter = fltrGroup->GetFilter();
4032 SMESH::Filter::Criteria_var criteria;
4033 filter->GetCriteria( criteria.out() );
4035 bool isMissingGroup = false;
4036 std::vector< std::string > badEntries;
4038 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
4040 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
4041 switch ( criteria[ iCr ].Type )
4043 case SMESH::FT_BelongToMeshGroup:
4045 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
4046 btgg->SetGroupID( thresholdID );
4047 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
4048 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
4049 if ( refGroupSO->_is_nil() )
4051 CORBA::String_var refID = refGroupSO->GetID();
4052 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
4053 if ( o2nID == old2newGroupMap.end() )
4055 isMissingGroup = true; // corresponding new group not yet created
4058 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
4060 if ( o2nID->second.empty() ) // new referred group is invalid
4061 badEntries.push_back( refID.in() );
4064 case SMESH::FT_BelongToGeom:
4065 case SMESH::FT_BelongToPlane:
4066 case SMESH::FT_BelongToCylinder:
4067 case SMESH::FT_BelongToGenSurface:
4068 case SMESH::FT_LyingOnGeom:
4070 std::string newID = shapeMapper.FindNew( thresholdID );
4071 criteria[ iCr ].ThresholdID = newID.c_str();
4072 if ( newID.empty() )
4073 badEntries.push_back( thresholdID );
4076 case SMESH::FT_ConnectedElements:
4078 if ( thresholdID && thresholdID[0] )
4080 std::string newID = shapeMapper.FindNew( thresholdID );
4081 criteria[ iCr ].ThresholdID = newID.c_str();
4082 if ( newID.empty() )
4083 badEntries.push_back( thresholdID );
4089 } // loop on criteria
4091 if ( isMissingGroup && i < nbGroups )
4093 // to treat the group again
4094 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4098 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4099 newFilter->SetCriteria( criteria );
4101 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4102 newFilter->UnRegister();
4104 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4105 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4106 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4108 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4110 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4113 if ( !badEntries.empty() )
4116 } // treat a group on filter
4118 append( theNewGroups, newGroup );
4120 // fill old2newGroupMap
4121 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4122 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4123 if ( !srcSO->_is_nil() )
4125 CORBA::String_var srcID, newID("");
4126 srcID = srcSO->GetID();
4127 if ( !newSO->_is_nil() )
4128 newID = newSO->GetID();
4129 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4130 std::string( newID.in() )));
4133 if ( newGroup->_is_nil() )
4138 newMeshDS->CompactMesh();
4141 if ( !theMeshName || !theMeshName[0] )
4143 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4144 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4145 CORBA::String_var oldName = soOld->GetName();
4146 SetName( soNew, oldName.in(), "Mesh" );
4148 // mark invalid objects
4149 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4151 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4152 highLightInvalid( invalidSObjects[i].in(), true );
4155 << theNewMesh << ", "
4156 << theNewGroups << ", "
4157 << *theNewSubmeshes.ptr() << ", "
4158 << *theNewHypotheses.ptr() << ", "
4159 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4160 << theSourceMesh << ", "
4161 << theNewGeometry << ", "
4162 << "'" << theMeshName << "', "
4163 << theToCopyGroups << ", "
4164 << theToReuseHypotheses << ", "
4165 << theToCopyElements << " )";
4167 SMESH_CATCH( SMESH::throwCorbaException );
4172 //================================================================================
4174 * \brief Get version of MED format being used.
4176 //================================================================================
4178 char* SMESH_Gen_i::GetMEDFileVersion()
4180 MED::TInt majeur, mineur, release;
4181 majeur = mineur = release = 0;
4182 MED::GetVersionRelease(majeur, mineur, release);
4183 std::ostringstream version;
4184 version << majeur << "." << mineur << "." << release;
4185 return CORBA::string_dup( version.str().c_str() );
4188 //================================================================================
4190 * SMESH_Gen_i::GetMEDVersion
4192 * Get MED version of the file by its name
4194 //================================================================================
4196 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4198 std::string version = MED::GetMEDVersion( theFileName );
4199 return CORBA::string_dup( version.c_str() );
4202 //================================================================================
4204 * SMESH_Gen_i::CheckCompatibility
4206 * Check compatibility of file with MED format being used, read only.
4208 //================================================================================
4210 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4212 return MED::CheckCompatibility( theFileName );
4215 //================================================================================
4217 * SMESH_Gen_i::CheckWriteCompatibility
4219 * Check compatibility of file with MED format being used, for append on write.
4221 //================================================================================
4223 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4225 return MED::CheckCompatibility( theFileName, true );
4228 //================================================================================
4230 * SMESH_Gen_i::GetMeshNames
4232 * Get names of meshes defined in file with the specified name
4234 //================================================================================
4235 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4238 SMESH::string_array_var aResult = new SMESH::string_array();
4239 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4241 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4243 aResult->length( aNbMeshes );
4244 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4245 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4246 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4249 return aResult._retn();
4252 //=============================================================================
4256 * Save SMESH module's data
4258 //=============================================================================
4260 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4265 Kernel_Utils::Localizer loc;
4267 if (!myStudyContext)
4270 // Store study contents as a set of python commands
4273 SALOMEDS::Study_var aStudy = getStudyServant();
4275 // Declare a byte stream
4276 SALOMEDS::TMPFile_var aStreamFile;
4278 // Obtain a temporary dir
4279 TCollection_AsciiString tmpDir =
4280 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4282 // Create a sequence of files processed
4283 SALOMEDS_Tool::ListOfFiles aFileSeq;
4284 aFileSeq.reserve( NUM_TMP_FILES );
4286 TCollection_AsciiString aStudyName( "" );
4288 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4290 // Set names of temporary files
4291 TCollection_AsciiString filename =
4292 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4293 TCollection_AsciiString meshfile =
4294 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4295 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4296 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4297 filename = tmpDir + filename;
4298 meshfile = tmpDir + meshfile;
4301 HDFdataset* aDataset;
4302 HDFgroup* aTopGroup;
4304 HDFgroup* aSubGroup;
4305 HDFgroup* aSubSubGroup;
4306 hdf_size aSize[ 1 ];
4309 //Remove the files if they exist: BugID: 11225
4310 #ifndef WIN32 /* unix functionality */
4311 TCollection_AsciiString cmd("rm -f \"");
4313 TCollection_AsciiString cmd("del /F \"");
4323 system(cmd.ToCString());
4325 // MED writer to be used by storage process
4326 DriverMED_W_SMESHDS_Mesh writer;
4327 writer.SetFile( meshfile.ToCString() );
4328 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4331 // SetStoreName() to groups before storing hypotheses to let them refer to
4332 // groups using "store name", which is "Group <group_persistent_id>"
4334 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4335 for ( ; itBig->More(); itBig->Next() ) {
4336 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4337 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4338 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4339 if ( !CORBA::is_nil( anObject ) ) {
4340 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4341 if ( !myMesh->_is_nil() ) {
4342 myMesh->Load(); // load from study file if not yet done
4343 TPythonDump pd(this); // not to dump GetGroups()
4344 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4345 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4347 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4350 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4351 int anId = myStudyContext->findId( string( objStr.in() ) );
4353 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4354 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4355 aGrpBaseDS->SetStoreName( grpName );
4365 // ---> create HDF file
4366 aFile = new HDFfile( (char*) filename.ToCString() );
4367 aFile->CreateOnDisk();
4369 // --> iterator for top-level objects
4370 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4371 for ( ; itBig->More(); itBig->Next() ) {
4372 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4374 // --> hypotheses root branch (only one for the study)
4375 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4376 // create hypotheses root HDF group
4377 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4378 aTopGroup->CreateOnDisk();
4380 // iterator for all hypotheses
4381 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4382 for ( ; it->More(); it->Next() ) {
4383 SALOMEDS::SObject_wrap mySObject = it->Value();
4384 CORBA::Object_var anObject = SObjectToObject( mySObject );
4385 if ( !CORBA::is_nil( anObject ) ) {
4386 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4387 if ( !myHyp->_is_nil() ) {
4388 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4390 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4391 std::string hypname = hn.in();
4392 std::string libname = ln.in();
4394 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4395 // WIN32 and ".so" for X-system) must be deleted
4396 int libname_len = libname.length();
4398 if( libname_len > 4 )
4399 libname.resize( libname_len - 4 );
4401 // PAL17753 (Regression: missing hypothesis in restored study)
4402 // "lib" also should be removed from the beginning
4403 if( libname_len > 6 )
4404 libname = libname.substr( 3, libname_len - 3 - 3 );
4406 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4407 CORBA::String_var hypdata = myImpl->SaveTo();
4408 int id = myStudyContext->findId( string( objStr.in() ));
4410 // for each hypothesis create HDF group basing on its id
4411 char hypGrpName[30];
4412 sprintf( hypGrpName, "Hypothesis %d", id );
4413 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4414 aGroup->CreateOnDisk();
4415 // --> type name of hypothesis
4416 aSize[ 0 ] = hypname.length() + 1;
4417 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4418 aDataset->CreateOnDisk();
4419 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4420 aDataset->CloseOnDisk();
4421 // --> server plugin library name of hypothesis
4422 aSize[ 0 ] = libname.length() + 1;
4423 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4424 aDataset->CreateOnDisk();
4425 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4426 aDataset->CloseOnDisk();
4427 // --> persistent data of hypothesis
4428 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4429 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4430 aDataset->CreateOnDisk();
4431 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4432 aDataset->CloseOnDisk();
4433 // close hypothesis HDF group
4434 aGroup->CloseOnDisk();
4439 // close hypotheses root HDF group
4440 aTopGroup->CloseOnDisk();
4442 // --> algorithms root branch (only one for the study)
4443 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4444 // create algorithms root HDF group
4445 aTopGroup = new HDFgroup( "Algorithms", aFile );
4446 aTopGroup->CreateOnDisk();
4448 // iterator for all algorithms
4449 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4450 for ( ; it->More(); it->Next() ) {
4451 SALOMEDS::SObject_wrap mySObject = it->Value();
4452 CORBA::Object_var anObject = SObjectToObject( mySObject );
4453 if ( !CORBA::is_nil( anObject ) ) {
4454 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4455 if ( !myHyp->_is_nil() ) {
4456 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4458 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4459 std::string hypname = hn.in();
4460 std::string libname = ln.in();
4462 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4463 // WIN32 and ".so" for X-system) must be deleted
4464 int libname_len = libname.length();
4466 if( libname_len > 4 )
4467 libname.resize( libname_len - 4 );
4469 // PAL17753 (Regression: missing hypothesis in restored study)
4470 // "lib" also should be removed from the beginning
4471 if( libname_len > 6 )
4472 libname = libname.substr( 3, libname_len - 3 - 3 );
4474 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4475 CORBA::String_var hypdata = myImpl->SaveTo();
4476 int id = myStudyContext->findId( string( objStr.in() ) );
4478 // for each algorithm create HDF group basing on its id
4479 char hypGrpName[30];
4480 sprintf( hypGrpName, "Algorithm %d", id );
4481 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4482 aGroup->CreateOnDisk();
4483 // --> type name of algorithm
4484 aSize[0] = hypname.length() + 1;
4485 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4486 aDataset->CreateOnDisk();
4487 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4488 aDataset->CloseOnDisk();
4489 // --> server plugin library name of hypothesis
4490 aSize[0] = libname.length() + 1;
4491 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4492 aDataset->CreateOnDisk();
4493 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4494 aDataset->CloseOnDisk();
4495 // --> persistent data of algorithm
4496 aSize[0] = strlen( hypdata.in() ) + 1;
4497 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4498 aDataset->CreateOnDisk();
4499 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4500 aDataset->CloseOnDisk();
4501 // close algorithm HDF group
4502 aGroup->CloseOnDisk();
4507 // close algorithms root HDF group
4508 aTopGroup->CloseOnDisk();
4510 // --> mesh objects roots branches
4511 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4512 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4513 if ( !CORBA::is_nil( anObject ) ) {
4514 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4515 if ( !myMesh->_is_nil() ) {
4516 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4518 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4519 int id = myStudyContext->findId( string( objStr.in() ) );
4520 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4521 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4522 bool hasShape = myLocMesh.HasShapeToMesh();
4524 // for each mesh open the HDF group basing on its id
4525 char meshGrpName[ 30 ];
4526 sprintf( meshGrpName, "Mesh %d", id );
4527 aTopGroup = new HDFgroup( meshGrpName, aFile );
4528 aTopGroup->CreateOnDisk();
4530 // --> put dataset to hdf file which is a flag that mesh has data
4531 string strHasData = "0";
4532 // check if the mesh is not empty
4533 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4534 // write mesh data to med file
4535 writer.SetMesh( mySMESHDSMesh );
4536 writer.SetMeshId( id );
4539 aSize[ 0 ] = strHasData.length() + 1;
4540 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4541 aDataset->CreateOnDisk();
4542 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4543 aDataset->CloseOnDisk();
4546 // for each mesh open the HDF group basing on its auto color parameter
4547 char meshAutoColorName[ 30 ];
4548 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4550 anAutoColor[0] = myImpl->GetAutoColor();
4552 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4553 aDataset->CreateOnDisk();
4554 aDataset->WriteOnDisk( anAutoColor );
4555 aDataset->CloseOnDisk();
4557 // issue 0020693. Store _isModified flag
4558 int isModified = myLocMesh.GetIsModified();
4560 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4561 aDataset->CreateOnDisk();
4562 aDataset->WriteOnDisk( &isModified );
4563 aDataset->CloseOnDisk();
4565 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4566 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4568 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4569 aDataset->CreateOnDisk();
4570 aDataset->WriteOnDisk( &meshPersistentId );
4571 aDataset->CloseOnDisk();
4573 // Store SMESH_Mesh_i::_mainShapeTick
4574 int shapeTick = myImpl->MainShapeTick();
4576 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4577 aDataset->CreateOnDisk();
4578 aDataset->WriteOnDisk( &shapeTick );
4579 aDataset->CloseOnDisk();
4581 // write reference on a shape if exists
4582 SALOMEDS::SObject_wrap myRef;
4583 bool shapeRefFound = false;
4584 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4586 SALOMEDS::SObject_wrap myShape;
4587 bool ok = myRef->ReferencedObject( myShape.inout() );
4589 CORBA::Object_var shapeObj = myShape->GetObject();
4590 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4591 CORBA::String_var myRefOnObject = myShape->GetID();
4592 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4593 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4594 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4595 aDataset->CreateOnDisk();
4596 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4597 aDataset->CloseOnDisk();
4603 std::string info = myImpl->FileInfoToString();
4604 if ( !info.empty() )
4606 aSize[ 0 ] = info.size();
4607 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4608 aDataset->CreateOnDisk();
4609 aDataset->WriteOnDisk( (char*) info.data() );
4610 aDataset->CloseOnDisk();
4613 // write applied hypotheses if exist
4614 SALOMEDS::SObject_wrap myHypBranch;
4615 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4616 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4617 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4619 if ( found && (shapeRefFound || !hasShape) ) {
4620 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4621 aGroup->CreateOnDisk();
4623 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4625 for ( ; it->More(); it->Next() ) {
4626 SALOMEDS::SObject_wrap mySObject = it->Value();
4627 SALOMEDS::SObject_wrap myRefOnHyp;
4628 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4630 // san - it is impossible to recover applied hypotheses
4631 // using their entries within Load() method,
4632 // for there are no AttributeIORs in the study when Load() is working.
4633 // Hence, it is better to store persistent IDs of hypotheses as references to them
4635 //string myRefOnObject = myRefOnHyp->GetID();
4636 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4637 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4638 int id = myStudyContext->findId( string( objStr.in() ) );
4639 //if ( myRefOnObject.length() > 0 ) {
4640 //aSize[ 0 ] = myRefOnObject.length() + 1;
4641 char hypName[ 30 ], hypId[ 30 ];
4642 sprintf( hypName, "Hyp %d", ++hypNb );
4643 sprintf( hypId, "%d", id );
4644 aSize[ 0 ] = strlen( hypId ) + 1;
4645 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4646 aDataset->CreateOnDisk();
4647 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4648 aDataset->WriteOnDisk( hypId );
4649 aDataset->CloseOnDisk();
4653 aGroup->CloseOnDisk();
4656 // write applied algorithms if exist
4657 SALOMEDS::SObject_wrap myAlgoBranch;
4658 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4659 myAlgoBranch.inout() );
4660 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4661 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4663 if ( found && (shapeRefFound || !hasShape)) {
4664 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4665 aGroup->CreateOnDisk();
4667 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4669 for ( ; it->More(); it->Next() ) {
4670 SALOMEDS::SObject_wrap mySObject = it->Value();
4671 SALOMEDS::SObject_wrap myRefOnAlgo;
4672 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4674 // san - it is impossible to recover applied algorithms
4675 // using their entries within Load() method,
4676 // for there are no AttributeIORs in the study when Load() is working.
4677 // Hence, it is better to store persistent IDs of algorithms as references to them
4679 //string myRefOnObject = myRefOnAlgo->GetID();
4680 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4681 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4682 int id = myStudyContext->findId( string( objStr.in() ) );
4683 //if ( myRefOnObject.length() > 0 ) {
4684 //aSize[ 0 ] = myRefOnObject.length() + 1;
4685 char algoName[ 30 ], algoId[ 30 ];
4686 sprintf( algoName, "Algo %d", ++algoNb );
4687 sprintf( algoId, "%d", id );
4688 aSize[ 0 ] = strlen( algoId ) + 1;
4689 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4690 aDataset->CreateOnDisk();
4691 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4692 aDataset->WriteOnDisk( algoId );
4693 aDataset->CloseOnDisk();
4697 aGroup->CloseOnDisk();
4700 // --> submesh objects sub-branches
4702 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4703 SALOMEDS::SObject_wrap mySubmeshBranch;
4704 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4706 if ( found ) // check if there is shape reference in submeshes
4708 bool hasShapeRef = false;
4709 SALOMEDS::ChildIterator_wrap itSM =
4710 aStudy->NewChildIterator( mySubmeshBranch );
4711 for ( ; itSM->More(); itSM->Next() ) {
4712 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4713 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4714 mySubRef->ReferencedObject( myShape.inout() );
4715 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4718 { // remove one submesh
4719 if ( shapeRefFound )
4720 { // unassign hypothesis
4721 SMESH::SMESH_subMesh_var mySubMesh =
4722 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4723 if ( !mySubMesh->_is_nil() ) {
4724 int shapeID = mySubMesh->GetId();
4725 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4726 const list<const SMESHDS_Hypothesis*>& hypList =
4727 mySMESHDSMesh->GetHypothesis( S );
4728 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4729 while ( hyp != hypList.end() ) {
4730 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4731 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4735 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4737 } // loop on submeshes of a type
4738 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4739 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4742 } // end check if there is shape reference in submeshes
4744 char name_meshgroup[ 30 ];
4745 if ( i == GetSubMeshOnVertexTag() )
4746 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4747 else if ( i == GetSubMeshOnEdgeTag() )
4748 strcpy( name_meshgroup, "SubMeshes On Edge" );
4749 else if ( i == GetSubMeshOnWireTag() )
4750 strcpy( name_meshgroup, "SubMeshes On Wire" );
4751 else if ( i == GetSubMeshOnFaceTag() )
4752 strcpy( name_meshgroup, "SubMeshes On Face" );
4753 else if ( i == GetSubMeshOnShellTag() )
4754 strcpy( name_meshgroup, "SubMeshes On Shell" );
4755 else if ( i == GetSubMeshOnSolidTag() )
4756 strcpy( name_meshgroup, "SubMeshes On Solid" );
4757 else if ( i == GetSubMeshOnCompoundTag() )
4758 strcpy( name_meshgroup, "SubMeshes On Compound" );
4760 // for each type of submeshes create container HDF group
4761 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4762 aGroup->CreateOnDisk();
4764 // iterator for all submeshes of given type
4765 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4766 for ( ; itSM->More(); itSM->Next() ) {
4767 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4768 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4769 if ( !CORBA::is_nil( anSubObject ))
4771 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4772 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4773 int subid = myStudyContext->findId( string( objStr.in() ) );
4775 // for each mesh open the HDF group basing on its id
4776 char submeshGrpName[ 30 ];
4777 sprintf( submeshGrpName, "SubMesh %d", subid );
4778 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4779 aSubGroup->CreateOnDisk();
4781 // write reference on a shape, already checked if it exists
4782 SALOMEDS::SObject_wrap mySubRef, myShape;
4783 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4784 mySubRef->ReferencedObject( myShape.inout() );
4785 string myRefOnObject = myShape->GetID();
4786 if ( myRefOnObject.length() > 0 ) {
4787 aSize[ 0 ] = myRefOnObject.length() + 1;
4788 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4789 aDataset->CreateOnDisk();
4790 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4791 aDataset->CloseOnDisk();
4794 // write applied hypotheses if exist
4795 SALOMEDS::SObject_wrap mySubHypBranch;
4796 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4797 mySubHypBranch.inout() );
4799 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4800 aSubSubGroup->CreateOnDisk();
4802 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4804 for ( ; it->More(); it->Next() ) {
4805 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4806 SALOMEDS::SObject_wrap myRefOnHyp;
4807 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4809 //string myRefOnObject = myRefOnHyp->GetID();
4810 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4811 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4812 int id = myStudyContext->findId( string( objStr.in() ) );
4813 //if ( myRefOnObject.length() > 0 ) {
4814 //aSize[ 0 ] = myRefOnObject.length() + 1;
4815 char hypName[ 30 ], hypId[ 30 ];
4816 sprintf( hypName, "Hyp %d", ++hypNb );
4817 sprintf( hypId, "%d", id );
4818 aSize[ 0 ] = strlen( hypId ) + 1;
4819 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4820 aDataset->CreateOnDisk();
4821 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4822 aDataset->WriteOnDisk( hypId );
4823 aDataset->CloseOnDisk();
4827 aSubSubGroup->CloseOnDisk();
4830 // write applied algorithms if exist
4831 SALOMEDS::SObject_wrap mySubAlgoBranch;
4832 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4833 mySubAlgoBranch.inout() );
4835 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4836 aSubSubGroup->CreateOnDisk();
4838 SALOMEDS::ChildIterator_wrap it =
4839 aStudy->NewChildIterator( mySubAlgoBranch );
4841 for ( ; it->More(); it->Next() ) {
4842 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4843 SALOMEDS::SObject_wrap myRefOnAlgo;
4844 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4846 //string myRefOnObject = myRefOnAlgo->GetID();
4847 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4848 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4849 int id = myStudyContext->findId( string( objStr.in() ) );
4850 //if ( myRefOnObject.length() > 0 ) {
4851 //aSize[ 0 ] = myRefOnObject.length() + 1;
4852 char algoName[ 30 ], algoId[ 30 ];
4853 sprintf( algoName, "Algo %d", ++algoNb );
4854 sprintf( algoId, "%d", id );
4855 aSize[ 0 ] = strlen( algoId ) + 1;
4856 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4857 aDataset->CreateOnDisk();
4858 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4859 aDataset->WriteOnDisk( algoId );
4860 aDataset->CloseOnDisk();
4864 aSubSubGroup->CloseOnDisk();
4866 // close submesh HDF group
4867 aSubGroup->CloseOnDisk();
4870 // close container of submeshes by type HDF group
4871 aGroup->CloseOnDisk();
4875 // store submesh order if any
4876 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4877 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4878 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4879 char order_list[ 30 ];
4880 strcpy( order_list, "Mesh Order" );
4881 // count number of submesh ids
4883 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4884 for ( ; idIt != theOrderIds.end(); idIt++ )
4885 nbIDs += (*idIt).size();
4886 // number of values = number of IDs +
4887 // number of lists (for separators) - 1
4888 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4889 idIt = theOrderIds.begin();
4890 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4891 const TListOfInt& idList = *idIt;
4892 if (idIt != theOrderIds.begin()) // not first list
4893 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4894 // dump submesh ids from current list
4895 TListOfInt::const_iterator id_smId = idList.begin();
4896 for( ; id_smId != idList.end(); id_smId++ )
4897 smIDs[ i++ ] = *id_smId;
4900 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4902 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4903 aDataset->CreateOnDisk();
4904 aDataset->WriteOnDisk( smIDs );
4905 aDataset->CloseOnDisk();
4909 if ( !theOrderIds.empty() && isNewOrederVersion )
4911 // convert ids to entries
4912 std::list< std::list< std::string > > orderEntryLists;
4913 for ( const TListOfInt& idList : theOrderIds )
4915 orderEntryLists.emplace_back();
4916 std::list< std::string > & entryList = orderEntryLists.back();
4917 for ( const int& id : idList )
4919 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4920 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4921 SALOMEDS::SObject_var so = ObjectToSObject( go );
4922 if ( !so->_is_nil() )
4924 CORBA::String_var entry = so->GetID();
4925 entryList.emplace_back( entry.in() );
4929 // convert orderEntryLists to string
4930 std::ostringstream ostream;
4931 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4932 std::string orderEntryString = ostream.str();
4935 aSize[ 0 ] = orderEntryString.size() + 1;
4936 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4937 aDataset->CreateOnDisk();
4938 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4939 aDataset->CloseOnDisk();
4942 // groups root sub-branch
4943 SALOMEDS::SObject_wrap myGroupsBranch;
4944 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4945 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4947 char name_group[ 30 ];
4948 if ( i == GetNodeGroupsTag() )
4949 strcpy( name_group, "Groups of Nodes" );
4950 else if ( i == GetEdgeGroupsTag() )
4951 strcpy( name_group, "Groups of Edges" );
4952 else if ( i == GetFaceGroupsTag() )
4953 strcpy( name_group, "Groups of Faces" );
4954 else if ( i == GetVolumeGroupsTag() )
4955 strcpy( name_group, "Groups of Volumes" );
4956 else if ( i == Get0DElementsGroupsTag() )
4957 strcpy( name_group, "Groups of 0D Elements" );
4958 else if ( i == GetBallElementsGroupsTag() )
4959 strcpy( name_group, "Groups of Balls" );
4961 aGroup = new HDFgroup( name_group, aTopGroup );
4962 aGroup->CreateOnDisk();
4964 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4965 for ( ; it->More(); it->Next() ) {
4966 SALOMEDS::SObject_wrap mySObject = it->Value();
4967 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4968 if ( !CORBA::is_nil( aSubObject ) ) {
4969 SMESH_GroupBase_i* myGroupImpl =
4970 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4973 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4977 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4978 int anId = myStudyContext->findId( string( objStr.in() ) );
4980 // For each group, create a dataset named "Group <group_persistent_id>"
4981 // and store the group's user name into it
4982 const char* grpName = aGrpBaseDS->GetStoreName();
4983 CORBA::String_var aUserName = myGroupImpl->GetName();
4984 aSize[ 0 ] = strlen( aUserName ) + 1;
4986 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4987 aDataset->CreateOnDisk();
4988 aDataset->WriteOnDisk( aUserName );
4989 aDataset->CloseOnDisk();
4992 // For each group, create a dataset named "Group <group_persistent_id> Color"
4993 // and store the group's color into it
4994 char grpColorName[ 30 ];
4995 sprintf( grpColorName, "ColorGroup %d", anId );
4996 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4998 anRGB[ 0 ] = aColor.R;
4999 anRGB[ 1 ] = aColor.G;
5000 anRGB[ 2 ] = aColor.B;
5002 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
5003 aDataset->CreateOnDisk();
5004 aDataset->WriteOnDisk( anRGB );
5005 aDataset->CloseOnDisk();
5007 // Pass SMESHDS_Group to MED writer
5008 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
5010 writer.AddGroup( aGrpDS );
5012 // write reference on a shape if exists
5013 SMESHDS_GroupOnGeom* aGeomGrp =
5014 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
5016 SALOMEDS::SObject_wrap mySubRef, myShape;
5017 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
5018 mySubRef->ReferencedObject( myShape.inout() ) &&
5019 !CORBA::is_nil( myShape->GetObject() ))
5021 CORBA::String_var myRefOnObject = myShape->GetID();
5022 if ( myRefOnObject.in()[0] ) {
5023 char aRefName[ 30 ];
5024 sprintf( aRefName, "Ref on shape %d", anId);
5025 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
5026 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
5027 aDataset->CreateOnDisk();
5028 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
5029 aDataset->CloseOnDisk();
5032 else // shape ref is invalid:
5034 // save a group on geometry as ordinary group
5035 writer.AddGroup( aGeomGrp );
5038 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
5039 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
5041 std::string str = aFilterGrp_i->FilterToString();
5042 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
5043 aSize[ 0 ] = str.length() + 1;
5044 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
5045 aDataset->CreateOnDisk();
5046 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
5047 aDataset->CloseOnDisk();
5051 aGroup->CloseOnDisk();
5055 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
5057 // Flush current mesh information into MED file
5060 // save info on nb of elements
5061 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
5063 // maybe a shape was deleted in the study
5064 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
5065 TopoDS_Shape nullShape;
5066 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
5069 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
5074 aGroup = new HDFgroup( "Submeshes", aTopGroup );
5075 aGroup->CreateOnDisk();
5077 // each element belongs to one or none submesh,
5078 // so for each node/element, we store a submesh ID
5080 // Store submesh IDs
5081 for ( int isNode = 0; isNode < 2; ++isNode )
5083 SMDS_ElemIteratorPtr eIt =
5084 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
5085 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
5088 std::vector<int> smIDs; smIDs.reserve( nbElems );
5089 while ( eIt->more() )
5090 if ( const SMDS_MeshElement* e = eIt->next())
5091 smIDs.push_back( e->getshapeId() );
5093 aSize[ 0 ] = nbElems;
5094 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
5095 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5096 aDataset->CreateOnDisk();
5097 aDataset->WriteOnDisk( & smIDs[0] );
5098 aDataset->CloseOnDisk();
5101 aGroup->CloseOnDisk();
5103 // Store node positions on sub-shapes (SMDS_Position):
5104 // ----------------------------------------------------
5106 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5107 aGroup->CreateOnDisk();
5109 // in aGroup, create 5 datasets to contain:
5110 // "Nodes on Edges" - ID of node on edge
5111 // "Edge positions" - U parameter on node on edge
5112 // "Nodes on Faces" - ID of node on face
5113 // "Face U positions" - U parameter of node on face
5114 // "Face V positions" - V parameter of node on face
5116 // Find out nb of nodes on edges and faces
5117 // Collect corresponding sub-meshes
5118 int nbEdgeNodes = 0, nbFaceNodes = 0;
5119 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5120 // loop on SMESHDS_SubMesh'es
5121 while ( smIt->more() )
5123 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5124 if ( aSubMesh->IsComplexSubmesh() )
5125 continue; // submesh containing other submeshs
5126 smIdType nbNodes = aSubMesh->NbNodes();
5127 if ( nbNodes == 0 ) continue;
5129 int aShapeID = aSubMesh->GetID();
5130 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5132 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5133 // write only SMDS_FacePosition and SMDS_EdgePosition
5134 switch ( aShapeType ) {
5136 nbFaceNodes += nbNodes;
5137 aFaceSM.push_back( aSubMesh );
5140 nbEdgeNodes += nbNodes;
5141 aEdgeSM.push_back( aSubMesh );
5147 // Treat positions on edges or faces
5148 for ( int onFace = 0; onFace < 2; onFace++ )
5150 // Create arrays to store in datasets
5151 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5152 if (!nbNodes) continue;
5153 int* aNodeIDs = new int [ nbNodes ];
5154 double* aUPos = new double [ nbNodes ];
5155 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5158 // loop on sub-meshes
5159 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5160 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5161 for ( ; itSM != pListSM->end(); itSM++ )
5163 SMESHDS_SubMesh* aSubMesh = (*itSM);
5165 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5166 // loop on nodes in aSubMesh
5167 while ( itNode->more() )
5170 const SMDS_MeshNode* node = itNode->next();
5171 aNodeIDs [ iNode ] = node->GetID();
5174 const SMDS_PositionPtr pos = node->GetPosition();
5175 if ( onFace ) { // on FACE
5176 SMDS_FacePositionPtr fPos = pos;
5178 aUPos[ iNode ] = fPos->GetUParameter();
5179 aVPos[ iNode ] = fPos->GetVParameter();
5186 SMDS_EdgePositionPtr ePos = pos;
5188 aUPos[ iNode ] = ePos->GetUParameter();
5194 } // loop on nodes in aSubMesh
5195 } // loop on sub-meshes
5200 aSize[ 0 ] = nbNodes;
5202 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5203 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5204 aDataset->CreateOnDisk();
5205 aDataset->WriteOnDisk( aNodeIDs );
5206 aDataset->CloseOnDisk();
5209 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5210 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5211 aDataset->CreateOnDisk();
5212 aDataset->WriteOnDisk( aUPos );
5213 aDataset->CloseOnDisk();
5216 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5217 aDataset->CreateOnDisk();
5218 aDataset->WriteOnDisk( aVPos );
5219 aDataset->CloseOnDisk();
5224 if ( aVPos ) delete [] aVPos;
5226 } // treat positions on edges or faces
5228 // close "Node Positions" group
5229 aGroup->CloseOnDisk();
5231 } // if ( there are submeshes in SMESHDS_Mesh )
5234 // close mesh HDF group
5235 aTopGroup->CloseOnDisk();
5243 aFile->CloseOnDisk();
5246 // Convert temporary files to stream
5247 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5249 // Remove temporary files and directory
5251 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5253 return aStreamFile._retn();
5256 //=============================================================================
5258 * SMESH_Gen_i::SaveASCII
5260 * Save SMESH module's data in ASCII format
5262 //=============================================================================
5264 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5266 bool isMultiFile ) {
5267 MESSAGE( "SMESH_Gen_i::SaveASCII" );
5268 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5269 return aStreamFile._retn();
5271 //after usual saving needs to encipher binary to text string
5272 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5273 int size = aStreamFile.in().length();
5274 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5275 for ( int i = 0; i < size; i++ )
5276 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5278 buffer[size * 3] = '\0';
5280 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5282 return anAsciiStreamFile._retn();
5285 //=============================================================================
5289 * Load SMESH module's data
5291 //=============================================================================
5293 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5294 const SALOMEDS::TMPFile& theStream,
5298 UpdateStudy(); // load geom data
5299 Kernel_Utils::Localizer loc;
5301 SALOMEDS::Study_var aStudy = getStudyServant();
5303 // Get temporary files location
5304 TCollection_AsciiString tmpDir =
5305 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5307 // Convert the stream into sequence of files to process
5308 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5311 TCollection_AsciiString aStudyName( "" );
5312 if ( isMultiFile ) {
5313 CORBA::WString_var url = aStudy->URL();
5314 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5315 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5317 // Set names of temporary files
5318 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5319 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5323 HDFdataset* aDataset;
5324 HDFgroup* aTopGroup;
5326 HDFgroup* aSubGroup;
5327 HDFgroup* aSubSubGroup;
5330 // ---> open HDF file
5331 aFile = new HDFfile( (char*) filename.ToCString() );
5333 aFile->OpenOnDisk( HDF_RDONLY );
5335 catch ( HDFexception ) {
5336 INFOS( "Load(): " << filename << " not found!" );
5340 TPythonDump pd(this); // prevent dump during loading
5342 // For PAL13473 ("Repetitive mesh") implementation.
5343 // New dependencies between SMESH objects are established:
5344 // now hypotheses can refer to meshes, shapes and other hypotheses.
5345 // To keep data consistent, the following order of data restoration
5347 // 1. Create hypotheses
5348 // 2. Create all meshes
5349 // 3. Load hypotheses' data
5352 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5353 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5354 list< SMESH::Filter_var > filters;
5356 // get total number of top-level groups
5357 int aNbGroups = aFile->nInternalObjects();
5358 if ( aNbGroups > 0 ) {
5359 // --> in first turn we should read&create hypotheses
5360 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5361 // open hypotheses root HDF group
5362 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5363 aTopGroup->OpenOnDisk();
5365 // get number of hypotheses
5366 int aNbObjects = aTopGroup->nInternalObjects();
5367 for ( int j = 0; j < aNbObjects; j++ ) {
5368 // try to identify hypothesis
5369 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5370 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5372 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5373 // open hypothesis group
5374 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5375 aGroup->OpenOnDisk();
5377 // --> get hypothesis id
5378 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5383 // get number of datasets
5384 int aNbSubObjects = aGroup->nInternalObjects();
5385 for ( int k = 0; k < aNbSubObjects; k++ ) {
5387 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5388 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5389 // --> get hypothesis name
5390 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5391 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5392 aDataset->OpenOnDisk();
5393 size = aDataset->GetSize();
5394 char* hypname_str = new char[ size ];
5395 aDataset->ReadFromDisk( hypname_str );
5396 hypname = string( hypname_str );
5397 delete [] hypname_str;
5398 aDataset->CloseOnDisk();
5400 // --> get hypothesis plugin library name
5401 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5402 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5403 aDataset->OpenOnDisk();
5404 size = aDataset->GetSize();
5405 char* libname_str = new char[ size ];
5406 aDataset->ReadFromDisk( libname_str );
5407 SCRUTE( libname_str );
5408 libname = string( libname_str );
5409 delete [] libname_str;
5410 aDataset->CloseOnDisk();
5412 // --> get hypothesis data
5413 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5414 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5415 aDataset->OpenOnDisk();
5416 size = aDataset->GetSize();
5417 char* hypdata_str = new char[ size ];
5418 aDataset->ReadFromDisk( hypdata_str );
5419 hypdata = string( hypdata_str );
5420 delete [] hypdata_str;
5421 aDataset->CloseOnDisk();
5424 // close hypothesis HDF group
5425 aGroup->CloseOnDisk();
5427 // --> restore hypothesis from data
5428 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5429 MESSAGE("VSR - load hypothesis : id = " << id <<
5430 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5431 SMESH::SMESH_Hypothesis_var myHyp;
5433 try { // protect persistence mechanism against exceptions
5434 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5437 INFOS( "Exception during hypothesis creation" );
5440 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5442 // myImpl->LoadFrom( hypdata.c_str() );
5443 hypDataList.push_back( make_pair( myImpl, hypdata ));
5444 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5445 int newId = myStudyContext->findId( iorString.in() );
5446 myStudyContext->mapOldToNew( id, newId );
5449 MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5453 // close hypotheses root HDF group
5454 aTopGroup->CloseOnDisk();
5458 // --> then we should read&create algorithms
5459 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5460 // open algorithms root HDF group
5461 aTopGroup = new HDFgroup( "Algorithms", aFile );
5462 aTopGroup->OpenOnDisk();
5464 // get number of algorithms
5465 int aNbObjects = aTopGroup->nInternalObjects();
5466 for ( int j = 0; j < aNbObjects; j++ ) {
5467 // try to identify algorithm
5468 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5469 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5471 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5472 // open algorithm group
5473 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5474 aGroup->OpenOnDisk();
5476 // --> get algorithm id
5477 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5482 // get number of datasets
5483 int aNbSubObjects = aGroup->nInternalObjects();
5484 for ( int k = 0; k < aNbSubObjects; k++ ) {
5486 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5487 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5488 // --> get algorithm name
5489 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5490 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5491 aDataset->OpenOnDisk();
5492 size = aDataset->GetSize();
5493 char* hypname_str = new char[ size ];
5494 aDataset->ReadFromDisk( hypname_str );
5495 hypname = string( hypname_str );
5496 delete [] hypname_str;
5497 aDataset->CloseOnDisk();
5499 // --> get algorithm plugin library name
5500 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5501 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5502 aDataset->OpenOnDisk();
5503 size = aDataset->GetSize();
5504 char* libname_str = new char[ size ];
5505 aDataset->ReadFromDisk( libname_str );
5506 SCRUTE( libname_str );
5507 libname = string( libname_str );
5508 delete [] libname_str;
5509 aDataset->CloseOnDisk();
5511 // --> get algorithm data
5512 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5513 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5514 aDataset->OpenOnDisk();
5515 size = aDataset->GetSize();
5516 char* hypdata_str = new char[ size ];
5517 aDataset->ReadFromDisk( hypdata_str );
5518 SCRUTE( hypdata_str );
5519 hypdata = string( hypdata_str );
5520 delete [] hypdata_str;
5521 aDataset->CloseOnDisk();
5524 // close algorithm HDF group
5525 aGroup->CloseOnDisk();
5527 // --> restore algorithm from data
5528 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5529 MESSAGE("VSR - load algo : id = " << id <<
5530 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5531 SMESH::SMESH_Hypothesis_var myHyp;
5533 try { // protect persistence mechanism against exceptions
5534 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5536 catch( SALOME::SALOME_Exception& ex )
5538 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5541 INFOS( "Exception during hypothesis creation" );
5544 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5546 //myImpl->LoadFrom( hypdata.c_str() );
5547 hypDataList.push_back( make_pair( myImpl, hypdata ));
5548 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5549 int newId = myStudyContext->findId( iorString.in() );
5550 myStudyContext->mapOldToNew( id, newId );
5553 MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5557 // close algorithms root HDF group
5558 aTopGroup->CloseOnDisk();
5562 // --> the rest groups should be meshes
5563 for ( int i = 0; i < aNbGroups; i++ ) {
5564 // identify next group
5565 char meshName[ HDF_NAME_MAX_LEN+1 ];
5566 aFile->InternalObjectIndentify( i, meshName );
5568 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5570 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5574 // open mesh HDF group
5575 aTopGroup = new HDFgroup( meshName, aFile );
5576 aTopGroup->OpenOnDisk();
5578 // get number of child HDF objects
5579 int aNbObjects = aTopGroup->nInternalObjects();
5580 if ( aNbObjects > 0 ) {
5582 MESSAGE( "VSR - load mesh : id = " << id );
5583 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5584 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5585 if ( !myNewMeshImpl )
5587 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5589 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5590 int newId = myStudyContext->findId( iorString.in() );
5591 myStudyContext->mapOldToNew( id, newId );
5594 // try to read and set auto color flag
5595 char aMeshAutoColorName[ 30 ];
5596 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5597 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5599 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5600 aDataset->OpenOnDisk();
5601 size = aDataset->GetSize();
5602 int* anAutoColor = new int[ size ];
5603 aDataset->ReadFromDisk( anAutoColor );
5604 aDataset->CloseOnDisk();
5605 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5606 delete [] anAutoColor;
5609 // try to read and set reference to shape
5610 GEOM::GEOM_Object_var aShapeObject;
5611 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5612 // load mesh "Ref on shape" - it's an entry to SObject
5613 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5614 aDataset->OpenOnDisk();
5615 size = aDataset->GetSize();
5616 char* refFromFile = new char[ size ];
5617 aDataset->ReadFromDisk( refFromFile );
5618 aDataset->CloseOnDisk();
5619 if ( strlen( refFromFile ) > 0 ) {
5620 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5621 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5622 if ( !CORBA::is_nil( shapeObject ) ) {
5623 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5624 if ( !aShapeObject->_is_nil() )
5625 myNewMeshImpl->SetShape( aShapeObject );
5628 delete [] refFromFile;
5631 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5632 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5634 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5635 aDataset->OpenOnDisk();
5636 size = aDataset->GetSize();
5637 int* meshPersistentId = new int[ size ];
5638 aDataset->ReadFromDisk( meshPersistentId );
5639 aDataset->CloseOnDisk();
5640 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5641 delete [] meshPersistentId;
5644 // Restore SMESH_Mesh_i::_mainShapeTick
5645 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5647 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5648 aDataset->OpenOnDisk();
5649 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5650 aDataset->ReadFromDisk( shapeTick );
5651 aDataset->CloseOnDisk();
5654 // Restore file info
5655 if ( aTopGroup->ExistInternalObject( "file info" ))
5657 aDataset = new HDFdataset( "file info", aTopGroup );
5658 aDataset->OpenOnDisk();
5659 size = aDataset->GetSize();
5660 std::string info( size, ' ');
5661 aDataset->ReadFromDisk( (char*) info.data() );
5662 aDataset->CloseOnDisk();
5663 myNewMeshImpl->FileInfoFromString( info );
5669 // As all objects that can be referred by hypothesis are created,
5670 // we can restore hypothesis data
5672 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5673 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5675 SMESH_Hypothesis_i* hyp = hyp_data->first;
5676 string & data = hyp_data->second;
5677 hyp->LoadFrom( data.c_str() );
5680 // Restore the rest mesh data
5682 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5683 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5685 aTopGroup = meshi_group->second;
5686 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5688 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5689 bool hasData = false;
5692 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5693 int newId = myStudyContext->findId( iorString.in() );
5694 int meshOldId = myStudyContext->getOldId( newId );
5696 // try to find mesh data dataset
5697 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5698 // load mesh "has data" flag
5699 aDataset = new HDFdataset( "Has data", aTopGroup );
5700 aDataset->OpenOnDisk();
5701 size = aDataset->GetSize();
5702 char* strHasData = new char[ size ];
5703 aDataset->ReadFromDisk( strHasData );
5704 aDataset->CloseOnDisk();
5705 if ( strcmp( strHasData, "1") == 0 ) {
5708 delete [] strHasData;
5711 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5712 // nodes and elements are not yet put into sub-meshes)
5713 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5714 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5715 aGroup->OpenOnDisk();
5716 // get number of applied algorithms
5717 int aNbSubObjects = aGroup->nInternalObjects();
5718 MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5719 for ( int j = 0; j < aNbSubObjects; j++ ) {
5720 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5721 aGroup->InternalObjectIndentify( j, name_dataset );
5722 // check if it is an algorithm
5723 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5724 aDataset = new HDFdataset( name_dataset, aGroup );
5725 aDataset->OpenOnDisk();
5726 size = aDataset->GetSize();
5727 char* refFromFile = new char[ size ];
5728 aDataset->ReadFromDisk( refFromFile );
5729 aDataset->CloseOnDisk();
5730 // san - it is impossible to recover applied algorithms using their entries within Load() method
5731 int id = atoi( refFromFile );
5732 delete [] refFromFile;
5733 string anIOR = myStudyContext->getIORbyOldId( id );
5734 if ( !anIOR.empty() ) {
5735 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5736 if ( !CORBA::is_nil( hypObject ) ) {
5737 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5738 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5739 || !myNewMeshImpl->HasShapeToMesh()) )
5740 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5745 aGroup->CloseOnDisk();
5748 // try to get applied hypotheses
5749 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5750 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5751 aGroup->OpenOnDisk();
5752 // get number of applied hypotheses
5753 int aNbSubObjects = aGroup->nInternalObjects();
5754 for ( int j = 0; j < aNbSubObjects; j++ ) {
5755 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5756 aGroup->InternalObjectIndentify( j, name_dataset );
5757 // check if it is a hypothesis
5758 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5759 aDataset = new HDFdataset( name_dataset, aGroup );
5760 aDataset->OpenOnDisk();
5761 size = aDataset->GetSize();
5762 char* refFromFile = new char[ size ];
5763 aDataset->ReadFromDisk( refFromFile );
5764 aDataset->CloseOnDisk();
5765 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5766 int id = atoi( refFromFile );
5767 delete [] refFromFile;
5768 string anIOR = myStudyContext->getIORbyOldId( id );
5769 if ( !anIOR.empty() ) {
5770 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5771 if ( !CORBA::is_nil( hypObject ) ) {
5772 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5773 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5774 || !myNewMeshImpl->HasShapeToMesh()) )
5775 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5780 aGroup->CloseOnDisk();
5783 // --> try to find SUB-MESHES containers for each type of submesh
5784 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5785 const char* name_meshgroup = 0;
5786 if ( j == GetSubMeshOnVertexTag() )
5787 name_meshgroup = "SubMeshes On Vertex";
5788 else if ( j == GetSubMeshOnEdgeTag() )
5789 name_meshgroup = "SubMeshes On Edge";
5790 else if ( j == GetSubMeshOnWireTag() )
5791 name_meshgroup = "SubMeshes On Wire";
5792 else if ( j == GetSubMeshOnFaceTag() )
5793 name_meshgroup = "SubMeshes On Face";
5794 else if ( j == GetSubMeshOnShellTag() )
5795 name_meshgroup = "SubMeshes On Shell";
5796 else if ( j == GetSubMeshOnSolidTag() )
5797 name_meshgroup = "SubMeshes On Solid";
5798 else if ( j == GetSubMeshOnCompoundTag() )
5799 name_meshgroup = "SubMeshes On Compound";
5801 // try to get submeshes container HDF group
5802 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5803 // open submeshes containers HDF group
5804 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5805 aGroup->OpenOnDisk();
5807 // get number of submeshes
5808 int aNbSubMeshes = aGroup->nInternalObjects();
5809 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5811 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5812 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5813 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5814 // --> get submesh id
5815 int subid = atoi( name_submeshgroup + 7 );
5818 // open submesh HDF group
5819 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5820 aSubGroup->OpenOnDisk();
5822 // try to read and set reference to subshape
5823 GEOM::GEOM_Object_var aSubShapeObject;
5824 SMESH::SMESH_subMesh_var aSubMesh;
5826 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5827 // load submesh "Ref on shape" - it's an entry to SObject
5828 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5829 aDataset->OpenOnDisk();
5830 size = aDataset->GetSize();
5831 char* refFromFile = new char[ size ];
5832 aDataset->ReadFromDisk( refFromFile );
5833 aDataset->CloseOnDisk();
5834 if ( strlen( refFromFile ) > 0 ) {
5835 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5836 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5837 if ( !CORBA::is_nil( subShapeObject ) ) {
5838 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5839 if ( !aSubShapeObject->_is_nil() )
5840 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5841 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5842 if ( aSubMesh->_is_nil() )
5844 string iorSubString = GetORB()->object_to_string( aSubMesh );
5845 int newSubId = myStudyContext->findId( iorSubString );
5846 myStudyContext->mapOldToNew( subid, newSubId );
5849 delete [] refFromFile;
5852 if ( aSubMesh->_is_nil() )
5855 // try to get applied algorithms
5856 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5857 // open "applied algorithms" HDF group
5858 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5859 aSubSubGroup->OpenOnDisk();
5860 // get number of applied algorithms
5861 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5862 for ( int l = 0; l < aNbSubObjects; l++ ) {
5863 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5864 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5865 // check if it is an algorithm
5866 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5867 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5868 aDataset->OpenOnDisk();
5869 size = aDataset->GetSize();
5870 char* refFromFile = new char[ size ];
5871 aDataset->ReadFromDisk( refFromFile );
5872 aDataset->CloseOnDisk();
5874 int id = atoi( refFromFile );
5875 string anIOR = myStudyContext->getIORbyOldId( id );
5876 if ( !anIOR.empty() ) {
5877 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5878 if ( !CORBA::is_nil( hypObject ) ) {
5879 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5880 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5881 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5884 delete [] refFromFile;
5887 // close "applied algorithms" HDF group
5888 aSubSubGroup->CloseOnDisk();
5891 // try to get applied hypotheses
5892 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5893 // open "applied hypotheses" HDF group
5894 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5895 aSubSubGroup->OpenOnDisk();
5896 // get number of applied hypotheses
5897 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5898 for ( int l = 0; l < aNbSubObjects; l++ ) {
5899 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5900 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5901 // check if it is a hypothesis
5902 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5903 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5904 aDataset->OpenOnDisk();
5905 size = aDataset->GetSize();
5906 char* refFromFile = new char[ size ];
5907 aDataset->ReadFromDisk( refFromFile );
5908 aDataset->CloseOnDisk();
5910 int id = atoi( refFromFile );
5911 string anIOR = myStudyContext->getIORbyOldId( id );
5912 if ( !anIOR.empty() ) {
5913 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5914 if ( !CORBA::is_nil( hypObject ) ) {
5915 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5916 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5917 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5920 delete [] refFromFile;
5923 // close "APPLIED HYPOTHESES" hdf group
5924 aSubSubGroup->CloseOnDisk();
5927 // close SUB-MESH hdf group
5928 aSubGroup->CloseOnDisk();
5931 // close SUB-MESHES containers hdf group
5932 aGroup->CloseOnDisk();
5936 // try to get GROUPS
5937 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5938 char name_group[ 30 ];
5939 if ( ii == GetNodeGroupsTag() )
5940 strcpy( name_group, "Groups of Nodes" );
5941 else if ( ii == GetEdgeGroupsTag() )
5942 strcpy( name_group, "Groups of Edges" );
5943 else if ( ii == GetFaceGroupsTag() )
5944 strcpy( name_group, "Groups of Faces" );
5945 else if ( ii == GetVolumeGroupsTag() )
5946 strcpy( name_group, "Groups of Volumes" );
5947 else if ( ii == Get0DElementsGroupsTag() )
5948 strcpy( name_group, "Groups of 0D Elements" );
5949 else if ( ii == GetBallElementsGroupsTag() )
5950 strcpy( name_group, "Groups of Balls" );
5952 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5953 aGroup = new HDFgroup( name_group, aTopGroup );
5954 aGroup->OpenOnDisk();
5955 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5956 // within aGroup->ExistInternalObject( name )
5957 std::vector< std::string > subNames;
5958 TColStd_MapOfAsciiString mapOfNames;
5959 aGroup->GetAllObjects( subNames );
5960 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5961 mapOfNames.Add( subNames[ iN ].c_str() );
5963 for ( size_t j = 0; j < subNames.size(); j++ ) {
5964 const std::string& name_dataset = subNames[ j ];
5965 // check if it is a group
5966 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5969 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5972 int groupID = -1; // group local ID (also persistent)
5974 groupID = atoi( endptr + 1 );
5975 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5976 aDataset->OpenOnDisk();
5978 // Retrieve actual group name
5979 size = aDataset->GetSize();
5980 char* nameFromFile = new char[ size ];
5981 aDataset->ReadFromDisk( nameFromFile );
5982 aDataset->CloseOnDisk();
5984 // Try to find a shape reference
5985 TopoDS_Shape aShape;
5986 char aRefName[ 30 ];
5987 sprintf( aRefName, "Ref on shape %d", subid);
5988 if ( mapOfNames.Contains( aRefName ))
5990 // load mesh "Ref on shape" - it's an entry to SObject
5991 aDataset = new HDFdataset( aRefName, aGroup );
5992 aDataset->OpenOnDisk();
5993 size = aDataset->GetSize();
5994 char* refFromFile = new char[ size ];
5995 aDataset->ReadFromDisk( refFromFile );
5996 aDataset->CloseOnDisk();
5997 if ( strlen( refFromFile ) > 0 ) {
5998 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5999 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
6000 if ( !CORBA::is_nil( shapeObject ) ) {
6001 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
6002 if ( !aShapeObject->_is_nil() )
6003 aShape = GeomObjectToShape( aShapeObject );
6006 delete [] refFromFile;
6008 // Try to read a filter of SMESH_GroupOnFilter
6009 SMESH::Filter_var filter;
6010 SMESH_PredicatePtr predicate;
6011 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
6012 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
6014 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
6015 aDataset->OpenOnDisk();
6016 size = aDataset->GetSize();
6017 char* persistStr = new char[ size ];
6018 aDataset->ReadFromDisk( persistStr );
6019 aDataset->CloseOnDisk();
6020 if ( strlen( persistStr ) > 0 ) {
6021 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
6022 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
6023 filters.push_back( filter );
6025 delete [] persistStr;
6028 // Create group servant
6029 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
6030 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
6031 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
6032 delete [] nameFromFile;
6033 // Obtain a SMESHDS_Group object
6034 if ( aNewGroup->_is_nil() )
6037 CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
6038 string iorSubString(iorSubStringVar.in());
6039 int newSubId = myStudyContext->findId( iorSubString );
6040 myStudyContext->mapOldToNew( subid, newSubId );
6042 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
6046 if ( SMESH_GroupOnFilter_i* aFilterGroup =
6047 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
6049 aFilterGroup->SetFilter( filter );
6050 filter->UnRegister();
6052 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
6053 if ( !aGroupBaseDS )
6056 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
6059 // Read color of the group
6060 char aGroupColorName[ 30 ];
6061 sprintf( aGroupColorName, "ColorGroup %d", subid);
6062 if ( mapOfNames.Contains( aGroupColorName ))
6064 aDataset = new HDFdataset( aGroupColorName, aGroup );
6065 aDataset->OpenOnDisk();
6066 size = aDataset->GetSize();
6067 double* anRGB = new double[ size ];
6068 aDataset->ReadFromDisk( anRGB );
6069 aDataset->CloseOnDisk();
6070 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
6071 aGroupBaseDS->SetColor( aColor );
6076 aGroup->CloseOnDisk();
6080 // instead of reading mesh data, we read only brief information of all
6081 // objects: mesh, groups, sub-meshes (issue 0021208)
6084 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
6085 meshfile.ToCString(), filename.ToCString(),
6089 // read Sub-Mesh ORDER if any
6090 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
6091 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
6092 aDataset->OpenOnDisk();
6093 size = aDataset->GetSize();
6094 int* smIDs = new int[ size ];
6095 aDataset->ReadFromDisk( smIDs );
6096 aDataset->CloseOnDisk();
6097 TListOfListOfInt anOrderIds;
6098 anOrderIds.push_back( TListOfInt() );
6099 for ( int i = 0; i < size; i++ )
6100 if ( smIDs[ i ] < 0 ) // is separator
6101 anOrderIds.push_back( TListOfInt() );
6103 anOrderIds.back().push_back(smIDs[ i ]);
6105 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6108 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6110 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6111 aDataset->OpenOnDisk();
6112 size = aDataset->GetSize();
6113 std::string dataString; dataString.resize( size );
6114 aDataset->ReadFromDisk((char*) dataString.data() );
6115 aDataset->CloseOnDisk();
6117 std::list< std::list< std::string > > orderEntryLists;
6118 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6120 TListOfListOfInt anOrderIds;
6121 for ( const std::list< std::string >& entryList : orderEntryLists )
6123 anOrderIds.emplace_back();
6124 for ( const std::string & entry : entryList )
6126 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6127 TopoDS_Shape shape = GeomObjectToShape( go );
6128 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6129 anOrderIds.back().emplace_back( sm->GetId() );
6132 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6136 // update hyps needing full mesh data restored (issue 20918)
6137 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6139 SMESH_Hypothesis_i* hyp = hyp_data->first;
6140 hyp->UpdateAsMeshesRestored();
6143 // notify algos on completed restoration to set sub-mesh event listeners
6144 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6146 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6147 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6149 TopoDS_Shape myLocShape;
6150 if(myLocMesh.HasShapeToMesh())
6151 myLocShape = myLocMesh.GetShapeToMesh();
6153 myLocShape = SMESH_Mesh::PseudoShape();
6155 myLocMesh.GetSubMesh(myLocShape)->
6156 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6159 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6160 list< SMESH::Filter_var >::iterator f = filters.begin();
6161 for ( ; f != filters.end(); ++f )
6162 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6163 fi->FindBaseObjects();
6168 aTopGroup->CloseOnDisk();
6171 aFile->CloseOnDisk();
6174 // Remove temporary files created from the stream
6177 SMESH_File meshFile( meshfile.ToCString() );
6178 if ( !meshFile ) // no meshfile exists
6180 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6184 Engines::Container_var container = GetContainerRef();
6185 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6187 container_i->registerTemporaryFile( filename.ToCString() );
6188 container_i->registerTemporaryFile( meshfile.ToCString() );
6189 container_i->registerTemporaryFile( tmpDir.ToCString() );
6194 // creation of tree nodes for all data objects in the study
6195 // to support tree representation customization and drag-n-drop:
6196 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6197 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6198 useCaseBuilder->SetRootCurrent();
6199 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6200 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6201 for (it->InitEx(true); it->More(); it->Next()) {
6202 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6209 //=============================================================================
6211 * SMESH_Gen_i::LoadASCII
6213 * Load SMESH module's data in ASCII format
6215 //=============================================================================
6217 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6218 const SALOMEDS::TMPFile& theStream,
6220 bool isMultiFile ) {
6221 MESSAGE( "SMESH_Gen_i::LoadASCII" );
6222 return Load( theComponent, theStream, theURL, isMultiFile );
6224 //before call main ::Load method it's need for decipher text format to
6225 //binary ( "|xx" => x' )
6226 int size = theStream.length();
6227 if ( int((size / 3 )*3) != size ) //error size of buffer
6230 int real_size = int(size / 3);
6232 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6235 unsigned int c = -1;
6236 for ( int i = 0; i < real_size; i++ )
6238 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6239 sscanf( tmp, "%x", &c );
6240 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6243 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6245 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6248 //=============================================================================
6250 * SMESH_Gen_i::Close
6252 * Clears study-connected data when it is closed
6254 //=============================================================================
6256 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6258 MESSAGE( "SMESH_Gen_i::Close" );
6260 // Clear study contexts data
6261 myStudyContext->Clear();
6263 // remove the tmp files meshes are loaded from
6264 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6266 // Clean trace of API methods calls
6272 //=============================================================================
6274 * SMESH_Gen_i::ComponentDataType
6276 * Get component data type
6278 //=============================================================================
6280 char* SMESH_Gen_i::ComponentDataType()
6282 MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6283 return CORBA::string_dup( "SMESH" );
6287 //=============================================================================
6289 * SMESH_Gen_i::IORToLocalPersistentID
6291 * Transform data from transient form to persistent
6293 //=============================================================================
6295 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6296 const char* IORString,
6297 CORBA::Boolean /*isMultiFile*/,
6298 CORBA::Boolean /*isASCII*/ )
6300 MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6302 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6303 int anId = myStudyContext->findId( IORString );
6305 MESSAGE( "VSR " << anId );
6307 sprintf( strId, "%d", anId );
6308 return CORBA::string_dup( strId );
6311 return CORBA::string_dup( "" );
6314 //=============================================================================
6316 * SMESH_Gen_i::LocalPersistentIDToIOR
6318 * Transform data from persistent form to transient
6320 //=============================================================================
6322 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6323 const char* aLocalPersistentID,
6324 CORBA::Boolean /*isMultiFile*/,
6325 CORBA::Boolean /*isASCII*/ )
6327 MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6329 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6330 int anId = atoi( aLocalPersistentID );
6331 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6333 return CORBA::string_dup( "" );
6336 //=======================================================================
6337 //function : RegisterObject
6339 //=======================================================================
6341 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6343 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6344 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6345 return myStudyContext->addObject( string( iorString.in() ) );
6350 //================================================================================
6352 * \brief Return id of registered object
6353 * \param theObject - the Object
6354 * \retval int - Object id
6356 //================================================================================
6358 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6360 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6361 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6362 string iorStringCpp(iorString.in());
6363 return myStudyContext->findId( iorStringCpp );
6368 //=============================================================================
6370 * SMESH_Gen_i::SetName
6372 * Set a new object name
6374 //=============================================================================
6376 void SMESH_Gen_i::SetName(const char* theIOR,
6377 const char* theName)
6379 if ( theIOR && strcmp( theIOR, "" ) ) {
6380 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6381 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6382 if ( !aSO->_is_nil() ) {
6383 SetName( aSO, theName );
6388 // Version information
6389 char* SMESH_Gen_i::getVersion()
6391 #if SMESH_DEVELOPMENT
6392 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6394 return CORBA::string_dup(SMESH_VERSION_STR);
6398 //=================================================================================
6399 // function : Move()
6400 // purpose : Moves objects to the specified position.
6401 // Is used in the drag-n-drop functionality.
6402 //=================================================================================
6404 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6405 SALOMEDS::SObject_ptr where,
6408 if ( CORBA::is_nil( where ) ) return;
6410 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6411 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6412 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6413 std::string dataType = father->ComponentDataType();
6414 if ( dataType != "SMESH" ) return; // not a SMESH component
6416 SALOMEDS::SObject_var objAfter;
6417 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6418 // insert at given row -> find insertion position
6419 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6421 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6422 if ( i == row && useCaseIt->More() ) {
6423 objAfter = useCaseIt->Value();
6427 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6428 SALOMEDS::SObject_var sobj = what[i];
6429 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6430 // insert the object to the use case tree
6431 if ( !CORBA::is_nil( objAfter ) )
6432 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6434 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6438 //================================================================================
6440 * \brief Collect indices of elements, which are located inside the sphere
6442 //================================================================================
6444 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6445 SMESH::ElementType theElemType,
6451 SMESH::long_array_var aResult = new SMESH::long_array();
6452 if ( meshPart->_is_nil() )
6453 return aResult._retn();
6455 // 1. Create geometrical object
6456 gp_Pnt aP( theX, theY, theZ );
6457 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6459 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6461 if ( lst.size() > 0 ) {
6462 aResult->length( lst.size() );
6463 for ( size_t i = 0; i < lst.size(); i++ ) {
6464 aResult[i] = lst[i];
6467 return aResult._retn();
6470 //================================================================================
6472 * \brief Collect indices of elements, which are located inside the box
6474 //================================================================================
6476 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6477 SMESH::ElementType theElemType,
6478 CORBA::Double theX1,
6479 CORBA::Double theY1,
6480 CORBA::Double theZ1,
6481 CORBA::Double theX2,
6482 CORBA::Double theY2,
6483 CORBA::Double theZ2)
6485 SMESH::long_array_var aResult = new SMESH::long_array();
6486 if( meshPart->_is_nil() )
6487 return aResult._retn();
6489 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6490 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6492 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6494 if( lst.size() > 0 ) {
6495 aResult->length( lst.size() );
6496 for ( size_t i = 0; i < lst.size(); i++ ) {
6497 aResult[i] = lst[i];
6500 return aResult._retn();
6503 //================================================================================
6505 * \brief Collect indices of elements, which are located inside the cylinder
6507 //================================================================================
6509 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6510 SMESH::ElementType theElemType,
6514 CORBA::Double theDX,
6515 CORBA::Double theDY,
6516 CORBA::Double theDZ,
6518 CORBA::Double theR )
6520 SMESH::long_array_var aResult = new SMESH::long_array();
6521 if( meshPart->_is_nil() )
6522 return aResult._retn();
6524 gp_Pnt aP( theX, theY, theZ );
6525 gp_Vec aV( theDX, theDY, theDZ );
6526 gp_Ax2 anAxes (aP, aV);
6528 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6530 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6532 if( lst.size() > 0 ) {
6533 aResult->length( lst.size() );
6534 for ( size_t i = 0; i < lst.size(); i++ ) {
6535 aResult[i] = lst[i];
6538 return aResult._retn();
6541 //================================================================================
6543 * \brief Collect indices of elements, which are located inside the geom object
6545 //================================================================================
6547 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6548 SMESH::ElementType theElemType,
6549 GEOM::GEOM_Object_ptr theGeom,
6550 CORBA::Double theTolerance )
6552 SMESH::long_array_var aResult = new SMESH::long_array();
6553 if( meshPart->_is_nil() || theGeom->_is_nil() )
6554 return aResult._retn();
6556 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6558 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6560 if( lst.size() > 0 ) {
6561 aResult->length( lst.size() );
6562 for ( size_t i = 0; i < lst.size(); i++ ) {
6563 aResult[i] = lst[i];
6566 return aResult._retn();
6569 //================================================================================
6571 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6573 //================================================================================
6575 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6576 SMESH::ElementType theElemType,
6577 const TopoDS_Shape& theShape,
6578 double* theTolerance) {
6580 std::vector<long> res;
6581 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6583 if ( mesh->_is_nil() )
6586 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6590 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6595 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6596 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6597 anElementsOnShape->SetAllNodes( true );
6598 anElementsOnShape->SetMesh( meshDS );
6599 anElementsOnShape->SetShape( theShape, aType );
6602 anElementsOnShape->SetTolerance(*theTolerance);
6604 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6605 if ( !msource->_is_nil() ) { // Mesh case
6606 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6608 while ( elemIt->more() ) {
6609 const SMDS_MeshElement* anElem = elemIt->next();
6610 long anId = anElem->GetID();
6611 if ( anElementsOnShape->IsSatisfy( anId ) )
6612 res.push_back( anId );
6616 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6617 if ( !gsource->_is_nil() ) {
6618 if(theElemType == SMESH::NODE) {
6619 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6620 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6621 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6622 long anId = node->GetID();
6623 if ( anElementsOnShape->IsSatisfy( anId ) )
6624 res.push_back( anId );
6627 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6628 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6629 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6630 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6631 long anId = elem->GetID();
6632 if ( anElementsOnShape->IsSatisfy( anId ) )
6633 res.push_back( anId );
6638 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6639 if ( !smsource->_is_nil() ) {
6640 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6641 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6642 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6644 long anId = elem->GetID();
6645 if ( anElementsOnShape->IsSatisfy( anId ) )
6646 res.push_back( anId );
6653 //================================================================================
6655 * \brief Returns true if algorithm can be used to mesh a given geometry
6656 * \param [in] theAlgoType - the algorithm type
6657 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6658 * \param [in] theGeomObject - the geometry to mesh
6659 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6660 * else, returns \c True if at least one shape is meshable
6661 * \return CORBA::Boolean - can or can't
6663 //================================================================================
6665 #undef SMY_OWN_CATCH
6666 #define SMY_OWN_CATCH // prevent re-throwing SALOME::SALOME_Exception in IsApplicable()
6668 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6669 const char* theLibName,
6670 GEOM::GEOM_Object_ptr theGeomObject,
6671 CORBA::Boolean toCheckAll)
6675 std::string aPlatformLibName;
6676 GenericHypothesisCreator_i* aCreator =
6677 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6680 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6681 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6682 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6689 SMESH_CATCH( SMESH::doNothing );
6691 MESSAGE("SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : ""));