1 // Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
57 #include <libgen.h> // for basename function
61 #define LibHandle HMODULE
62 #define LoadLib( name ) LoadLibrary( name )
63 #define GetProc GetProcAddress
64 #define UnLoadLib( handle ) FreeLibrary( handle );
66 #define LibHandle void*
68 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
69 #else // DYNLOAD_LOCAL
70 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
71 #endif // DYNLOAD_LOCAL
73 #define UnLoadLib( handle ) dlclose( handle );
76 #include "SMESH_Gen_i.hxx"
77 #include "SMESH_version.h"
79 #include "DriverMED_W_SMESHDS_Mesh.h"
80 #include "DriverMED_R_SMESHDS_Mesh.h"
82 #include "DriverCGNS_Read.hxx"
84 #include "MED_Factory.hxx"
85 #include "SMDS_EdgePosition.hxx"
86 #include "SMDS_FacePosition.hxx"
87 #include "SMDS_SetIterator.hxx"
88 #include "SMDS_SpacePosition.hxx"
89 #include "SMDS_VertexPosition.hxx"
90 #include "SMESHDS_Document.hxx"
91 #include "SMESHDS_Group.hxx"
92 #include "SMESHDS_GroupOnGeom.hxx"
93 #include "SMESH_Algo_i.hxx"
94 #include "SMESH_File.hxx"
95 #include "SMESH_Group.hxx"
96 #include "SMESH_Group_i.hxx"
97 #include "SMESH_Hypothesis.hxx"
98 #include "SMESH_Hypothesis_i.hxx"
99 #include "SMESH_Mesh.hxx"
100 #include "SMESH_MeshEditor.hxx"
101 #include "SMESH_Mesh_i.hxx"
102 #include "SMESH_PreMeshInfo.hxx"
103 #include "SMESH_PythonDump.hxx"
104 #include "SMESH_ControlsDef.hxx"
106 // to pass CORBA exception through SMESH_TRY
107 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
108 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
110 #include CORBA_SERVER_HEADER(SMESH_Group)
111 #include CORBA_SERVER_HEADER(SMESH_Filter)
112 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
115 #include <GEOMImpl_Types.hxx>
116 #include <GEOM_Client.hxx>
118 #include <Basics_Utils.hxx>
119 #include <Basics_DirUtils.hxx>
121 #include <OpUtil.hxx>
122 #include <SALOMEDS_Tool.hxx>
123 #include <SALOME_Container_i.hxx>
124 #include <SALOME_LifeCycleCORBA.hxx>
125 #include <SALOME_NamingService.hxx>
126 #include <Utils_CorbaException.hxx>
127 #include <Utils_ExceptHandlers.hxx>
128 #include <Utils_SINGLETON.hxx>
129 #include <utilities.h>
131 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
132 #include CORBA_CLIENT_HEADER(SALOME_Session)
134 // helpers about SALOME::GenericObj
135 #include <SALOMEDS_wrap.hxx>
136 #include <SALOMEDS_Attributes_wrap.hxx>
137 #include <GEOM_wrap.hxx>
146 #include <boost/archive/text_oarchive.hpp>
147 #include <boost/archive/text_iarchive.hpp>
148 #include <boost/serialization/list.hpp>
149 #include <boost/serialization/string.hpp>
152 using SMESH::TPythonDump;
155 #define NUM_TMP_FILES 2
158 static int MYDEBUG = 0;
160 static int MYDEBUG = 0;
163 // Static variables definition
164 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
165 CORBA::ORB_var SMESH_Gen_i::myOrb;
166 PortableServer::POA_var SMESH_Gen_i::myPoa;
167 SALOME_NamingService_Abstract* SMESH_Gen_i::myNS = nullptr;
168 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = nullptr;
169 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = nullptr;
172 const int nbElemPerDiagonal = 10;
174 //=============================================================================
176 * GetServant [ static ]
178 * Get servant of the CORBA object
180 //=============================================================================
182 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
184 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
187 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
190 catch (PortableServer::POA::ObjectNotActive &ex)
192 INFOS("GetServant: ObjectNotActive");
195 catch (PortableServer::POA::WrongAdapter &ex)
197 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
200 catch (PortableServer::POA::WrongPolicy &ex)
202 INFOS("GetServant: WrongPolicy");
207 INFOS( "GetServant - Unknown exception was caught!!!" );
212 //=============================================================================
214 * SObjectToObject [ static ]
216 * Get CORBA object corresponding to the SALOMEDS::SObject
218 //=============================================================================
220 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
222 SALOMEDS::GenericAttribute_wrap anAttr;
223 CORBA::Object_var anObj;
224 if ( !theSObject->_is_nil() ) {
226 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
227 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
228 CORBA::String_var aValue = anIOR->Value();
229 if( strcmp( aValue, "" ) != 0 )
230 anObj = GetORB()->string_to_object( aValue );
234 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
240 //=============================================================================
244 * Get SALOME_NamingService object
246 //=============================================================================
248 SALOME_NamingService_Abstract* SMESH_Gen_i::GetNS()
250 if ( myNS == NULL ) {
251 myNS = SINGLETON_<SALOME_NamingService>::Instance();
252 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
253 myNS->init_orb( GetORB() );
258 //=============================================================================
262 * Get SALOME_LifeCycleCORBA object
264 //=============================================================================
266 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
268 if ( myLCC == NULL ) {
269 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
274 //=============================================================================
276 * GetGeomEngine [ static ]
278 * Get GEOM::GEOM_Gen reference
280 //=============================================================================
282 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
284 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
285 if ( !CORBA::is_nil( go ))
290 //=============================================================================
292 * SMESH_Gen_i::SMESH_Gen_i
294 * Default constructor: not for use
296 //=============================================================================
298 SMESH_Gen_i::SMESH_Gen_i()
302 //=============================================================================
304 * SMESH_Gen_i::SMESH_Gen_i
306 * Standard constructor, used with Container
308 //=============================================================================
310 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
311 PortableServer::POA_ptr poa,
312 PortableServer::ObjectId* contId,
313 const char* instanceName,
314 const char* interfaceName,
316 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
319 myOrb = CORBA::ORB::_duplicate(orb);
320 myPoa = PortableServer::POA::_duplicate(poa);
323 _id = myPoa->activate_object( _thisObj );
325 myStudyContext = new StudyContext;
327 myIsEmbeddedMode = false;
328 myIsEnablePublish = true;
329 myShapeReader = NULL; // shape reader
331 myIsHistoricalPythonDump = true;
332 myToForgetMeshDataOnHypModif = false;
334 // set it in standalone mode only
335 //OSD::SetSignal( true );
337 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
338 // find out mode (embedded or standalone) here else
339 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
340 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
343 if ( SALOME_NamingService_Abstract* ns = GetNS() )
345 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
346 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
347 if ( !session->_is_nil() )
349 CORBA::String_var str_host = session->getHostname();
350 CORBA::Long s_pid = session->getPID();
351 string my_host = Kernel_Utils::GetHostname();
353 long my_pid = (long)_getpid();
355 long my_pid = (long) getpid();
357 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
363 //=============================================================================
365 * SMESH_Gen_i::~SMESH_Gen_i
369 //=============================================================================
371 SMESH_Gen_i::~SMESH_Gen_i()
373 // delete hypothesis creators
374 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
375 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
377 // same creator can be mapped under different names
378 GenericHypothesisCreator_i* creator = (*itHyp).second;
382 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
383 if ( creator == (*itHyp2).second )
384 (*itHyp2).second = 0;
386 myHypCreatorMap.clear();
388 // Clear study contexts data
389 delete myStudyContext;
391 // delete shape reader
393 delete myShapeReader;
396 //=============================================================================
398 * SMESH_Gen_i::getHypothesisCreator
400 * Get hypothesis creator
402 //=============================================================================
404 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
405 const char* theLibName,
406 std::string& thePlatformLibName)
408 std::string aPlatformLibName;
409 /* It's Need to translate lib name for WIN32 or X platform */
410 if ( theLibName && theLibName[0] != '\0' )
412 int libNameLen = strlen(theLibName);
413 //check for old format "libXXXXXXX.so"
414 if (libNameLen > 7 &&
415 !strncmp( theLibName, "lib", 3 ) &&
416 !strcmp( theLibName+libNameLen-3, ".so" ))
420 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
421 #elif defined(__APPLE__)
422 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
424 aPlatformLibName = theLibName;
429 //try to use new format
431 aPlatformLibName = theLibName;
432 aPlatformLibName += ".dll";
433 #elif defined(__APPLE__)
434 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
436 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
440 thePlatformLibName = aPlatformLibName;
442 Unexpect aCatch(SALOME_SalomeException);
443 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
445 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
446 GenericHypothesisCreator_i* aCreator;
449 // check, if creator for this hypothesis type already exists
450 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
452 // load plugin library
453 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
456 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
458 const char* path = aPlatformLibName.c_str();
461 const char* path = aPlatformLibName.c_str();
463 LibHandle libHandle = LoadLib( path );
464 #if defined(WIN32) && defined(UNICODE)
469 // report any error, if occurred
471 const char* anError = dlerror();
472 throw(SALOME_Exception( anError ));
474 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
475 << aPlatformLibName));
479 // get method, returning hypothesis creator
480 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
481 GetHypothesisCreator procHandle =
482 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
485 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
486 << aPlatformLibName ));
487 UnLoadLib(libHandle);
490 // get hypothesis creator
491 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
492 aCreator = procHandle(theHypName);
495 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
496 << aPlatformLibName));
498 // map hypothesis creator to a hypothesis name
499 myHypCreatorMap[string(theHypName)] = aCreator;
504 return myHypCreatorMap[string(theHypName)];
507 catch (SALOME_Exception& S_ex)
509 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
514 //=============================================================================
516 * SMESH_Gen_i::createHypothesis
518 * Create hypothesis of given type
520 //=============================================================================
522 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
523 const char* theLibName)
525 SMESH_Hypothesis_i* myHypothesis_i = 0;
526 SMESH::SMESH_Hypothesis_var hypothesis_i;
527 std::string aPlatformLibName;
528 GenericHypothesisCreator_i* aCreator =
529 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
531 // create a new hypothesis object, store its ref. in studyContext
532 myHypothesis_i = aCreator->Create(myPoa, &myGen);
535 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
536 CORBA::String_var hypName = myHypothesis_i->GetName();
537 myHypCreatorMap[ hypName.in() ] = aCreator;
539 // activate the CORBA servant of hypothesis
540 hypothesis_i = myHypothesis_i->_this();
541 int nextId = RegisterObject( hypothesis_i );
542 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
543 else { (void)nextId; } // avoid "unused variable" warning in release mode
545 return hypothesis_i._retn();
548 //=============================================================================
550 * SMESH_Gen_i::createMesh
552 * Create empty mesh on shape
554 //=============================================================================
556 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
558 Unexpect aCatch(SALOME_SalomeException);
559 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
561 // Get or create the GEOM_Client instance
563 // create a new mesh object servant, store it in a map in study context
564 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
565 // create a new mesh object
566 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
567 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
569 // activate the CORBA servant of Mesh
570 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
571 int nextId = RegisterObject( mesh );
572 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
573 else { (void)nextId; } // avoid "unused variable" warning in release mode
576 catch (SALOME_Exception& S_ex) {
577 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
579 return SMESH::SMESH_Mesh::_nil();
582 //=============================================================================
584 * SMESH_Gen_i::GetShapeReader
588 //=============================================================================
590 GEOM_Client* SMESH_Gen_i::GetShapeReader()
592 // create shape reader if necessary
593 if ( !myShapeReader )
594 myShapeReader = new GEOM_Client(GetContainerRef());
595 ASSERT( myShapeReader );
596 return myShapeReader;
599 //=============================================================================
601 * SMESH_Gen_i::SetGeomEngine
603 * Set GEOM::GEOM_Gen reference
605 //=============================================================================
607 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
609 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
612 //=============================================================================
614 * SMESH_Gen_i::SetEmbeddedMode
618 //=============================================================================
620 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
622 myIsEmbeddedMode = theMode;
624 if ( !myIsEmbeddedMode ) {
625 //PAL10867: disable signals catching with "noexcepthandler" option
626 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
627 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
632 char* envDisableFPE = getenv("DISABLE_FPE");
633 if (envDisableFPE && atoi(envDisableFPE))
638 OSD::SetSignal( raiseFPE );
640 // else OSD::SetSignal() is called in GUI
644 //=============================================================================
646 * SMESH_Gen_i::IsEmbeddedMode
650 //=============================================================================
652 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
654 return myIsEmbeddedMode;
657 //=============================================================================
659 * SMESH_Gen_i::SetEnablePublish
661 * Set enable publishing in the study
663 //=============================================================================
665 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
667 myIsEnablePublish = theIsEnablePublish;
670 //=============================================================================
672 * SMESH_Gen_i::IsEnablePublish
674 * Check enable publishing
676 //=============================================================================
678 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
680 return myIsEnablePublish;
683 //=============================================================================
685 * SMESH_Gen_i::UpdateStudy
687 * Update study (needed at switching GEOM->SMESH)
689 //=============================================================================
691 void SMESH_Gen_i::UpdateStudy()
693 if ( !myStudyContext )
694 myStudyContext = new StudyContext;
696 SALOMEDS::Study_var aStudy = getStudyServant();
697 if ( !CORBA::is_nil( aStudy ) )
699 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
701 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
702 if( !GEOM_var->_is_nil() )
703 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
705 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
706 if( !GEOM_var->_is_nil() )
707 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
709 // NPAL16168, issue 0020210
710 // Let meshes update their data depending on GEOM groups that could change
711 CORBA::String_var compDataType = ComponentDataType();
712 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
713 if ( !me->_is_nil() ) {
714 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
715 for ( ; anIter->More(); anIter->Next() ) {
716 SALOMEDS::SObject_wrap so = anIter->Value();
717 CORBA::Object_var ior = SObjectToObject( so );
718 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
719 mesh->CheckGeomModif();
725 //================================================================================
727 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
729 //================================================================================
731 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
733 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
734 SALOMEDS::GenericAttribute_wrap attr;
735 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
737 SALOMEDS::AttributePixMap_wrap pm = attr;
738 CORBA::String_var ico = pm->GetPixMap();
739 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
744 //=================================================================================
745 // function : hasObjectInfo()
746 // purpose : shows if module provides information for its objects
747 //=================================================================================
749 bool SMESH_Gen_i::hasObjectInfo()
754 //=================================================================================
755 // function : getObjectInfo()
756 // purpose : returns an information for a given object by its entry
757 //=================================================================================
759 char* SMESH_Gen_i::getObjectInfo( const char* entry )
761 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
762 // for the rest, "module 'SMESH', ID=0:1:2:*"
766 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
767 CORBA::Object_var obj = SObjectToObject( so );
768 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
769 if ( isGeomModifIcon( mesh ))
771 txt << "The geometry was changed and the mesh needs to be recomputed";
776 CORBA::String_var compType = ComponentDataType();
777 txt << "module '" << compType << "', ID=" << entry;
779 return CORBA::string_dup( txt );
782 //=============================================================================
784 * SMESH_Gen_i::GetStudyContext
788 //=============================================================================
790 StudyContext* SMESH_Gen_i::GetStudyContext()
792 return myStudyContext;
795 //=============================================================================
797 * SMESH_Gen_i::CreateHypothesis
799 * Create hypothesis/algorithm of given type and publish it in the study
801 //=============================================================================
803 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
804 const char* theLibName )
806 Unexpect aCatch(SALOME_SalomeException);
807 // Create hypothesis/algorithm
808 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
810 // Publish hypothesis/algorithm in the study
811 if ( CanPublishInStudy( hyp ) ) {
812 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
813 if ( !aSO->_is_nil() ) {
814 // Update Python script
815 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
816 << theHypName << "', '" << theLibName << "')";
823 //================================================================================
825 * \brief Return a hypothesis initialized by given average length.
826 * \param theHypType - hypothesis type name
827 * \param theLibName - plugin library name
828 * \param theAverageLength - average length
829 * \param theQuadDominated - is quad-dominated flag
830 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
832 //================================================================================
834 SMESH::SMESH_Hypothesis_ptr
835 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
836 const char* theLibName,
837 CORBA::Double theAverageLength,
838 CORBA::Boolean theQuadDominated)
840 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
841 theAverageLength, theQuadDominated };
843 SMESH::SMESH_Hypothesis_var hyp =
844 GetHypothesisParameterValues( theHypType, theLibName,
845 SMESH::SMESH_Mesh::_nil(),
846 GEOM::GEOM_Object::_nil(),
848 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
850 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
851 << theHypType << "', '"
852 << theLibName << "', "
853 << theAverageLength << ", "
854 << theQuadDominated << " )";
859 //================================================================================
861 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
862 * existing on the given geometry or to size of the geometry.
863 * \param theHypType - hypothesis type name
864 * \param theLibName - plugin library name
865 * \param theMesh - The mesh of interest
866 * \param theGeom - The shape to get parameter values from
867 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
868 * in a study and used to compute the mesh, or a temporary one created just to pass
871 //================================================================================
873 SMESH::SMESH_Hypothesis_ptr
874 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
875 const char* theLibName,
876 SMESH::SMESH_Mesh_ptr theMesh,
877 GEOM::GEOM_Object_ptr theGeom,
878 const SMESH::HypInitParams& theParams)
880 Unexpect aCatch(SALOME_SalomeException);
882 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
883 if ( byMesh && CORBA::is_nil( theMesh ) )
884 return SMESH::SMESH_Hypothesis::_nil();
885 if ( byMesh && CORBA::is_nil( theGeom ) )
886 return SMESH::SMESH_Hypothesis::_nil();
888 // -----------------------------------------------
889 // find hypothesis used to mesh theGeom
890 // -----------------------------------------------
892 // get mesh and shape
893 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
894 TopoDS_Shape shape = GeomObjectToShape( theGeom );
895 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
896 return SMESH::SMESH_Hypothesis::_nil();
897 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
899 // create a temporary hypothesis to know its dimension
900 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
901 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
903 return SMESH::SMESH_Hypothesis::_nil();
904 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
907 // look for a hypothesis of theHypType used to mesh the shape
908 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
911 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
912 int nbLocalHyps = aHypList->length();
913 for ( int i = 0; i < nbLocalHyps; i++ ) {
914 CORBA::String_var hypName = aHypList[i]->GetName();
915 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
916 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
918 // check super shapes
919 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
920 while ( nbLocalHyps == 0 && itShape.More() ) {
921 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
922 if ( ! CORBA::is_nil( geomObj )) {
923 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
924 nbLocalHyps = aHypList->length();
925 for ( int i = 0; i < nbLocalHyps; i++ )
926 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
927 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
933 // let the temporary hypothesis find out somehow parameter values by mesh
934 if ( hyp->SetParametersByMesh( mesh, shape ))
935 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
939 ::SMESH_Hypothesis::TDefaults dflts;
940 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
941 dflts._nbSegments = myGen.GetDefaultNbSegments();
942 dflts._elemLength = theParams.averageLength;
943 dflts._quadDominated = theParams.quadDominated;
944 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
947 dflts._diagonal = mesh->GetShapeDiagonalSize();
949 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
950 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
951 dflts._shape = &shape;
954 // let the hypothesis initialize it's values
955 if ( hyp->SetParametersByDefaults( dflts, mesh ))
956 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
959 return SMESH::SMESH_Hypothesis::_nil();
962 //=============================================================================
964 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
965 * \param [in] theHyp - the hypothesis of interest
966 * \param [out] theMesh - the sole mesh using \a theHyp
967 * \param [out] theShape - the sole geometry \a theHyp is assigned to
968 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
970 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
971 * considered as SAME sub-mesh => result is \c true.
972 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
973 * a shape to which an hyp being edited is assigned.
975 //=============================================================================
977 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
978 SMESH::SMESH_Mesh_out theMesh,
979 GEOM::GEOM_Object_out theShape)
981 if ( CORBA::is_nil( theHyp ))
984 // get Mesh component SO
985 CORBA::String_var compDataType = ComponentDataType();
986 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
987 if ( CORBA::is_nil( comp ))
990 // look for child SO of meshes
991 SMESH::SMESH_Mesh_var foundMesh;
992 TopoDS_Shape foundShape;
994 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
995 for ( ; meshIter->More() && isSole; meshIter->Next() )
997 SALOMEDS::SObject_wrap curSO = meshIter->Value();
998 CORBA::Object_var obj = SObjectToObject( curSO );
999 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1003 // look for a sole shape where theHyp is assigned
1004 bool isHypFound = false;
1005 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1006 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1007 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1009 const THypList& hyps = s2hypsIt.Value();
1010 THypList::const_iterator h = hyps.begin();
1011 for ( ; h != hyps.end(); ++h )
1012 if ( (*h)->GetID() == theHyp->GetId() )
1014 if ( h != hyps.end()) // theHyp found
1017 if ( ! foundShape.IsNull() &&
1018 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1020 foundShape.Nullify();
1024 foundShape = s2hypsIt.Key();
1026 } // loop on assigned hyps
1028 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1030 if ( !foundMesh->_is_nil() ) // not a sole mesh
1032 if ( !foundMesh->HasShapeToMesh() ||
1033 !mesh_i ->HasShapeToMesh() )
1035 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1039 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1040 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1041 isSole = s1->IsSame( s2 );
1044 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1050 ! foundMesh->_is_nil() &&
1051 ! foundShape.IsNull() )
1053 theMesh = foundMesh._retn();
1054 theShape = ShapeToGeomObject( foundShape );
1055 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1060 //=============================================================================
1062 * Set number of segments per diagonal of boundary box of geometry by which
1063 * default segment length of appropriate 1D hypotheses is defined
1065 //=============================================================================
1067 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1069 if ( theNbSegments > 0 )
1070 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1072 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1075 //=============================================================================
1077 * \brief Set default number of segments per edge
1079 //=============================================================================
1081 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1083 if ( theNbSegments > 0 )
1084 myGen.SetDefaultNbSegments( int(theNbSegments) );
1086 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1089 //=============================================================================
1091 * Set an option value
1093 //=============================================================================
1095 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1097 if ( name && value && strlen( value ) > 0 )
1100 if ( strcmp(name, "historical_python_dump") == 0 )
1102 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1103 msgToGUI = "preferences/SMESH/historical_python_dump/";
1104 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1106 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1108 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1109 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1110 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1112 else if ( strcmp(name, "default_grp_color") == 0 )
1116 // color must be presented as a string of following form:
1117 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1118 str = str.substr(1);
1119 for ( size_t i = 0; i < str.length()/2; i++ )
1120 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1121 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1123 else if ( value ) { // rgb color ("255,170,0", for example)
1124 string tempValue( value );
1125 char* colorValue = strtok( &tempValue[0], "," );
1126 while ( colorValue != NULL ) {
1127 int c_value = atoi( colorValue );
1128 if ( c_value >= 0 && c_value <= 255 )
1129 color.push_back( c_value );
1130 colorValue = strtok( NULL, "," );
1133 if ( color.size() == 3 ) { // color must have three valid component
1134 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1135 myDefaultGroupColor = value;
1136 msgToGUI = "preferences/SMESH/default_grp_color/";
1141 // update preferences in case if SetOption() is invoked from python console
1142 if ( !msgToGUI.empty() )
1144 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1145 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1146 if ( !CORBA::is_nil( session ) )
1147 session->emitMessageOneWay(msgToGUI.c_str());
1152 //=============================================================================
1154 * Return an option value
1156 //=============================================================================
1158 char* SMESH_Gen_i::GetOption(const char* name)
1162 if ( strcmp(name, "historical_python_dump") == 0 )
1164 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1166 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1168 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1170 if ( strcmp(name, "default_grp_color") == 0 )
1172 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1175 return CORBA::string_dup( "" );
1178 //=============================================================================
1180 * SMESH_Gen_i::CreateMesh
1182 * Create empty mesh on a shape and publish it in the study
1184 //=============================================================================
1186 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1188 Unexpect aCatch(SALOME_SalomeException);
1189 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1191 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1193 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1194 ASSERT( meshServant );
1195 meshServant->SetShape( theShapeObject );
1197 // publish mesh in the study
1198 if ( CanPublishInStudy( mesh ) ) {
1199 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1200 aStudyBuilder->NewCommand(); // There is a transaction
1201 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1202 aStudyBuilder->CommitCommand();
1203 if ( !aSO->_is_nil() ) {
1204 // Update Python script
1205 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1209 return mesh._retn();
1212 //=============================================================================
1214 * SMESH_Gen_i::CreateEmptyMesh
1218 //=============================================================================
1220 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1222 Unexpect aCatch(SALOME_SalomeException);
1223 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1225 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1227 // publish mesh in the study
1228 if ( CanPublishInStudy( mesh ) ) {
1229 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1230 aStudyBuilder->NewCommand(); // There is a transaction
1231 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1232 aStudyBuilder->CommitCommand();
1233 if ( !aSO->_is_nil() ) {
1234 // Update Python script
1235 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1239 return mesh._retn();
1244 //================================================================================
1246 * \brief Throw an exception in case if the file can't be read
1248 //================================================================================
1250 void checkFileReadable( const char* theFileName )
1252 SMESH_File f ( theFileName );
1255 if ( !f.error().empty() )
1256 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1258 THROW_SALOME_CORBA_EXCEPTION
1259 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1260 SALOME::BAD_PARAM );
1265 //=============================================================================
1267 * SMESH_Gen_i::CreateMeshFromUNV
1269 * Create mesh and import data from UNV file
1271 //=============================================================================
1273 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1275 Unexpect aCatch(SALOME_SalomeException);
1277 checkFileReadable( theFileName );
1279 SMESH::SMESH_Mesh_var aMesh = createMesh();
1281 // publish mesh in the study
1282 if ( CanPublishInStudy( aMesh ) ) {
1283 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1284 aStudyBuilder->NewCommand(); // There is a transaction
1285 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1286 aStudyBuilder->CommitCommand();
1287 if ( !aSO->_is_nil() ) {
1288 // Update Python script
1289 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1293 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1295 aServant->ImportUNVFile( theFileName );
1297 // Dump creation of groups
1298 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1300 aServant->GetImpl().GetMeshDS()->Modified();
1301 return aMesh._retn();
1304 //=============================================================================
1306 * SMESH_Gen_i::CreateMeshFromMED
1308 * Create mesh and import data from MED file
1310 //=============================================================================
1312 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1313 SMESH::DriverMED_ReadStatus& theStatus,
1314 const char* theCommandNameForPython,
1315 const char* theFileNameForPython)
1318 char bname[ _MAX_FNAME ];
1319 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1320 string aFileName = bname;
1322 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1324 // Retrieve mesh names from the file
1325 DriverMED_R_SMESHDS_Mesh myReader;
1326 myReader.SetFile( theFileName );
1327 myReader.SetMeshId( -1 );
1328 Driver_Mesh::Status aStatus;
1329 list<string> aNames = myReader.GetMeshNames(aStatus);
1330 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1331 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1333 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1336 TPythonDump aPythonDump(this);
1337 aPythonDump << "([";
1339 if (theStatus == SMESH::DRS_OK) {
1340 SALOMEDS::StudyBuilder_var aStudyBuilder;
1341 aStudyBuilder = getStudyServant()->NewBuilder();
1342 aStudyBuilder->NewCommand(); // There is a transaction
1344 aResult->length( aNames.size() );
1347 // Iterate through all meshes and create mesh objects
1348 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1351 if (i > 0) aPythonDump << ", ";
1354 SMESH::SMESH_Mesh_var mesh = createMesh();
1356 // publish mesh in the study
1357 SALOMEDS::SObject_wrap aSO;
1358 if ( CanPublishInStudy( mesh ) )
1359 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1360 // - as names of meshes are stored in MED file, we use them for data publishing
1361 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1362 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1365 if ( !aSO->_is_nil() ) {
1368 aPythonDump << "mesh_" << i;
1371 // Read mesh data (groups are published automatically by ImportMEDFile())
1372 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1373 ASSERT( meshServant );
1374 SMESH::DriverMED_ReadStatus status1 =
1375 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1376 if (status1 > theStatus)
1377 theStatus = status1;
1379 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1380 meshServant->GetImpl().GetMeshDS()->Modified();
1382 if ( !aStudyBuilder->_is_nil() )
1383 aStudyBuilder->CommitCommand();
1386 // Update Python script
1387 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1389 // Dump creation of groups
1390 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1391 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1393 return aResult._retn();
1396 //================================================================================
1398 * \brief Create meshes by reading a MED file
1400 //================================================================================
1402 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1403 SMESH::DriverMED_ReadStatus& theStatus)
1405 Unexpect aCatch(SALOME_SalomeException);
1406 checkFileReadable( theFileName );
1408 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1409 "CreateMeshesFromMED", theFileName);
1413 //=============================================================================
1415 * SMESH_Gen_i::CreateMeshFromSAUV
1417 * Create mesh and import data from SAUV file
1419 //=============================================================================
1421 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1422 SMESH::DriverMED_ReadStatus& theStatus)
1424 Unexpect aCatch(SALOME_SalomeException);
1425 checkFileReadable( theFileName );
1427 std::string sauvfilename(theFileName);
1428 std::string medfilename(theFileName);
1429 medfilename += ".med";
1432 cmd = "%PYTHONBIN% ";
1437 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1439 system(cmd.c_str());
1440 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1442 "CreateMeshesFromSAUV",
1443 sauvfilename.c_str());
1445 cmd = "%PYTHONBIN% ";
1450 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1452 system(cmd.c_str());
1456 //=============================================================================
1458 * SMESH_Gen_i::CreateMeshFromSTL
1460 * Create mesh and import data from STL file
1462 //=============================================================================
1464 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1466 Unexpect aCatch(SALOME_SalomeException);
1467 checkFileReadable( theFileName );
1469 SMESH::SMESH_Mesh_var aMesh = createMesh();
1472 char bname[ _MAX_FNAME ];
1473 _splitpath( theFileName, NULL, NULL, bname, NULL );
1474 string aFileName = bname;
1476 string aFileName = basename( const_cast<char *>(theFileName) );
1478 // publish mesh in the study
1479 if ( CanPublishInStudy( aMesh ) ) {
1480 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1481 aStudyBuilder->NewCommand(); // There is a transaction
1482 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1483 aStudyBuilder->CommitCommand();
1484 if ( !aSO->_is_nil() ) {
1485 // Update Python script
1486 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1490 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1492 aServant->ImportSTLFile( theFileName );
1493 aServant->GetImpl().GetMeshDS()->Modified();
1494 return aMesh._retn();
1497 //================================================================================
1499 * \brief Create meshes and import data from the CGSN file
1501 //================================================================================
1503 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1504 SMESH::DriverMED_ReadStatus& theStatus)
1506 Unexpect aCatch(SALOME_SalomeException);
1507 checkFileReadable( theFileName );
1509 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1512 // Retrieve nb meshes from the file
1513 DriverCGNS_Read myReader;
1514 myReader.SetFile( theFileName );
1515 Driver_Mesh::Status aStatus;
1516 int nbMeshes = myReader.GetNbMeshes(aStatus);
1517 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1519 aResult->length( nbMeshes );
1521 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1524 TPythonDump aPythonDump(this);
1525 aPythonDump << "([";
1527 if (theStatus == SMESH::DRS_OK)
1529 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1530 aStudyBuilder->NewCommand(); // There is a transaction
1534 // Iterate through all meshes and create mesh objects
1535 for ( ; i < nbMeshes; ++i )
1538 if (i > 0) aPythonDump << ", ";
1541 SMESH::SMESH_Mesh_var mesh = createMesh();
1542 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1544 // Read mesh data (groups are published automatically by ImportMEDFile())
1545 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1546 ASSERT( meshServant );
1548 SMESH::DriverMED_ReadStatus status1 =
1549 meshServant->ImportCGNSFile( theFileName, i, meshName );
1550 if (status1 > theStatus)
1551 theStatus = status1;
1553 meshServant->GetImpl().GetMeshDS()->Modified();
1554 // publish mesh in the study
1555 SALOMEDS::SObject_wrap aSO;
1556 if ( CanPublishInStudy( mesh ) )
1557 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1560 if ( !aSO->_is_nil() ) {
1564 aPythonDump << "mesh_" << i;
1567 aStudyBuilder->CommitCommand();
1570 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1572 // Dump creation of groups
1573 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1574 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1576 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1579 return aResult._retn();
1582 //================================================================================
1584 * \brief Create a mesh and import data from a GMF file
1586 //================================================================================
1588 SMESH::SMESH_Mesh_ptr
1589 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1590 CORBA::Boolean theMakeRequiredGroups,
1591 SMESH::ComputeError_out theError)
1593 Unexpect aCatch(SALOME_SalomeException);
1594 checkFileReadable( theFileName );
1596 SMESH::SMESH_Mesh_var aMesh = createMesh();
1598 char bname[ _MAX_FNAME ];
1599 _splitpath( theFileName, NULL, NULL, bname, NULL );
1600 string aFileName = bname;
1602 string aFileName = basename( const_cast<char *>(theFileName) );
1604 // publish mesh in the study
1605 if ( CanPublishInStudy( aMesh ) ) {
1606 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1607 aStudyBuilder->NewCommand(); // There is a transaction
1608 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1609 aStudyBuilder->CommitCommand();
1610 if ( !aSO->_is_nil() ) {
1611 // Update Python script
1612 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1613 << theFileName << "', "
1614 << theMakeRequiredGroups << " )";
1617 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1619 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1620 aServant->GetImpl().GetMeshDS()->Modified();
1621 return aMesh._retn();
1625 //=============================================================================
1627 * SMESH_Gen_i::IsReadyToCompute
1629 * Return true if mesh contains enough data to be computed
1631 //=============================================================================
1633 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1634 GEOM::GEOM_Object_ptr theShapeObject )
1636 Unexpect aCatch(SALOME_SalomeException);
1637 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1639 if ( CORBA::is_nil( theShapeObject ) )
1640 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1641 SALOME::BAD_PARAM );
1642 if ( CORBA::is_nil( theMesh ) )
1643 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1644 SALOME::BAD_PARAM );
1647 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1648 ASSERT( meshServant );
1649 if ( meshServant ) {
1650 // get local TopoDS_Shape
1651 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1652 // call implementation
1653 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1654 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1657 catch ( SALOME_Exception& S_ex ) {
1658 INFOS( "catch exception "<< S_ex.what() );
1663 //================================================================================
1665 * \brief Find SObject for an algo
1667 //================================================================================
1669 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1672 SALOMEDS::Study_var aStudy = getStudyServant();
1673 if ( !aStudy->_is_nil() ) {
1674 // find algo in the study
1675 CORBA::String_var compDataType = ComponentDataType();
1676 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1677 if ( !father->_is_nil() ) {
1678 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1679 for ( ; itBig->More(); itBig->Next() ) {
1680 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1681 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1682 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1683 for ( ; algoIt->More(); algoIt->Next() ) {
1684 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1685 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1686 if ( !CORBA::is_nil( algoIOR )) {
1687 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1688 if ( impl && impl->GetImpl() == algo )
1689 return algoSO._retn();
1691 } // loop on algo SO's
1694 } // SMESH component iterator
1698 return SALOMEDS::SObject::_nil();
1701 //================================================================================
1703 * \brief Return errors of mesh computation
1705 //================================================================================
1707 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1708 GEOM::GEOM_Object_ptr theSubObject )
1710 Unexpect aCatch(SALOME_SalomeException);
1711 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1713 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1714 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1716 if ( CORBA::is_nil( theMesh ) )
1717 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1719 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1721 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1724 if(theMesh->HasShapeToMesh())
1725 shape = GeomObjectToShape( theSubObject );
1727 shape = SMESH_Mesh::PseudoShape();
1729 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1731 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1734 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1735 const bool includeSelf = true, complexShapeFirst = true;
1736 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1738 while ( smIt->more() )
1741 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1743 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1744 if ( error && !error->IsOK() )
1746 if ( !( error->myAlgo ) &&
1747 !( error->myAlgo = sm->GetAlgo() ))
1749 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1750 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1751 errStruct.comment = error->myComment.c_str();
1752 errStruct.subShapeID = sm->GetId();
1753 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1754 if ( !algoSO->_is_nil() ) {
1755 CORBA::String_var algoName = algoSO->GetName();
1756 errStruct.algoName = algoName;
1759 errStruct.algoName = error->myAlgo->GetName();
1761 errStruct.hasBadMesh = error->HasBadElems();
1764 error_array->length( nbErr );
1767 catch ( SALOME_Exception& S_ex ) {
1768 INFOS( "catch exception "<< S_ex.what() );
1771 return error_array._retn();
1774 //================================================================================
1776 * \brief Return mesh elements preventing computation of a subshape
1778 //================================================================================
1780 SMESH::MeshPreviewStruct*
1781 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1782 CORBA::Short theSubShapeID )
1784 Unexpect aCatch(SALOME_SalomeException);
1785 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1787 if ( CORBA::is_nil( theMesh ) )
1788 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1790 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1793 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1795 // mesh implementation
1796 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1797 // submesh by subshape id
1798 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1801 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1802 if ( error && error->HasBadElems() )
1804 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1805 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1807 // get nodes of elements and count elements
1808 TNode2LocalIDMap mapNode2LocalID;
1809 list< TNodeLocalID > connectivity;
1810 int i, nbElements = 0, nbConnNodes = 0;
1812 const list<const SMDS_MeshElement*>& badElems =
1813 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1814 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1815 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1816 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1818 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1819 while ( nIt->more() )
1820 connectivity.push_back
1821 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1823 // fill node coords and assign local ids to the nodes
1824 int nbNodes = mapNode2LocalID.size();
1825 result->nodesXYZ.length( nbNodes );
1826 TNodeLocalID node2ID = mapNode2LocalID.begin();
1827 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1828 node2ID->second = i;
1829 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1830 result->nodesXYZ[i].x = node->X();
1831 result->nodesXYZ[i].y = node->Y();
1832 result->nodesXYZ[i].z = node->Z();
1834 // fill connectivity
1835 result->elementConnectivities.length( nbConnNodes );
1836 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1837 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1838 result->elementConnectivities[i] = (*connIt)->second;
1840 // fill element types
1841 result->elementTypes.length( nbElements );
1842 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1844 const SMDS_MeshElement* elem = *elemIt;
1845 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1846 result->elementTypes[i].isPoly = elem->IsPoly();
1847 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1853 catch ( SALOME_Exception& S_ex ) {
1854 INFOS( "catch exception "<< S_ex.what() );
1857 return result._retn();
1860 //================================================================================
1862 * \brief Create a group of elements preventing computation of a sub-shape
1864 //================================================================================
1866 SMESH::ListOfGroups*
1867 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1868 CORBA::Short theSubShapeID,
1869 const char* theGroupName )
1871 Unexpect aCatch(SALOME_SalomeException);
1873 SMESH::ListOfGroups_var groups;
1875 if ( CORBA::is_nil( theMesh ) )
1876 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1879 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1881 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1882 TPythonDump(this) << groups << " = " << this
1883 << ".MakeGroupsOfBadInputElements( "
1884 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1887 catch ( SALOME_Exception& S_ex ) {
1888 INFOS( "catch exception "<< S_ex.what() );
1890 return groups._retn();
1893 //================================================================================
1895 * \brief Returns errors of hypotheses definition
1896 * \param theMesh - the mesh
1897 * \param theSubObject - the main or sub- shape
1898 * \retval SMESH::algo_error_array* - sequence of errors
1900 //================================================================================
1902 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1903 GEOM::GEOM_Object_ptr theSubObject )
1905 Unexpect aCatch(SALOME_SalomeException);
1906 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1908 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1909 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1911 if ( CORBA::is_nil( theMesh ) )
1912 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1914 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1916 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1917 ASSERT( meshServant );
1918 if ( meshServant ) {
1919 TopoDS_Shape myLocShape;
1920 if(theMesh->HasShapeToMesh())
1921 myLocShape = GeomObjectToShape( theSubObject );
1923 myLocShape = SMESH_Mesh::PseudoShape();
1925 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1926 list< ::SMESH_Gen::TAlgoStateError > error_list;
1927 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1928 // call ::SMESH_Gen::GetAlgoState()
1929 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1930 error_array->length( error_list.size() );
1932 for ( error = error_list.begin(); error != error_list.end(); ++error )
1934 // fill AlgoStateError structure
1935 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1936 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1937 errStruct.algoDim = error->_algoDim;
1938 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1939 errStruct.algoName = "";
1940 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1941 if ( !algoSO->_is_nil() ) {
1942 CORBA::String_var algoName = algoSO->GetName();
1943 errStruct.algoName = algoName.in();
1948 catch ( SALOME_Exception& S_ex ) {
1949 INFOS( "catch exception "<< S_ex.what() );
1951 return error_array._retn();
1954 //=============================================================================
1956 * SMESH_Gen_i::GetSubShapesId
1958 * Get sub-shapes unique ID's list
1960 //=============================================================================
1963 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1964 const SMESH::object_array& theListOfSubShapeObject )
1966 Unexpect aCatch(SALOME_SalomeException);
1967 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1969 SMESH::long_array_var shapesId = new SMESH::long_array;
1972 if ( CORBA::is_nil( theMainShapeObject ) )
1973 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1977 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1978 TopTools_IndexedMapOfShape myIndexToShape;
1979 TopExp::MapShapes(myMainShape,myIndexToShape);
1981 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1983 GEOM::GEOM_Object_var aShapeObject
1984 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1985 if ( CORBA::is_nil( aShapeObject ) )
1986 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1987 SALOME::BAD_PARAM );
1989 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1990 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1992 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1993 setId.insert(myIndexToShape.FindIndex(F));
1994 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1996 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1998 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1999 setId.insert(myIndexToShape.FindIndex(E));
2000 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2002 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2004 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2005 setId.insert(myIndexToShape.FindIndex(V));
2006 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2009 shapesId->length(setId.size());
2010 set<int>::iterator iind;
2012 for (iind = setId.begin(); iind != setId.end(); iind++)
2014 if(MYDEBUG) SCRUTE((*iind));
2015 shapesId[i] = (*iind);
2016 if(MYDEBUG) SCRUTE(shapesId[i]);
2020 catch (SALOME_Exception& S_ex)
2022 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2025 return shapesId._retn();
2028 //=============================================================================
2030 * SMESH_Gen_i::Compute
2032 * Compute mesh on a shape
2034 //=============================================================================
2036 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2037 GEOM::GEOM_Object_ptr theShapeObject )
2040 Unexpect aCatch(SALOME_SalomeException);
2041 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2043 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2044 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2045 SALOME::BAD_PARAM );
2047 if ( CORBA::is_nil( theMesh ) )
2048 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2049 SALOME::BAD_PARAM );
2051 // Update Python script
2052 TPythonDump(this) << "isDone = " << this << ".Compute( "
2053 << theMesh << ", " << theShapeObject << ")";
2057 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2058 ASSERT( meshServant );
2059 if ( meshServant ) {
2060 if ( isGeomModifIcon( theMesh ))
2061 meshServant->Clear();
2063 meshServant->Load();
2064 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2065 meshServant->CheckGeomModif();
2066 // get local TopoDS_Shape
2067 TopoDS_Shape myLocShape;
2068 if(theMesh->HasShapeToMesh())
2069 myLocShape = GeomObjectToShape( theShapeObject );
2071 myLocShape = SMESH_Mesh::PseudoShape();
2072 // call implementation compute
2073 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2074 myGen.PrepareCompute( myLocMesh, myLocShape );
2075 int how = ::SMESH_Gen::COMPACT_MESH;
2076 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2077 how |= ::SMESH_Gen::SHAPE_ONLY;
2078 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2079 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2080 myLocMesh.GetMeshDS()->Modified();
2081 UpdateIcons( theMesh );
2083 HighLightInvalid( theMesh, /*isInvalid=*/false );
2087 catch ( std::bad_alloc& ) {
2088 INFOS( "Compute(): lack of memory" );
2090 catch ( SALOME_Exception& S_ex ) {
2091 INFOS( "Compute(): catch exception "<< S_ex.what() );
2094 INFOS( "Compute(): unknown exception " );
2099 //=============================================================================
2101 * SMESH_Gen_i::CancelCompute
2103 * Cancel Compute mesh on a shape
2105 //=============================================================================
2107 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2108 GEOM::GEOM_Object_ptr theShapeObject )
2110 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2112 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2113 TopoDS_Shape myLocShape;
2114 if(theMesh->HasShapeToMesh())
2115 myLocShape = GeomObjectToShape( theShapeObject );
2117 myLocShape = SMESH_Mesh::PseudoShape();
2118 myGen.CancelCompute( myLocMesh, myLocShape);
2122 //=============================================================================
2124 * SMESH_Gen_i::Precompute
2126 * Compute mesh as preview till indicated dimension on shape
2128 //=============================================================================
2130 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2131 GEOM::GEOM_Object_ptr theShapeObject,
2132 SMESH::Dimension theDimension,
2133 SMESH::long_array& theShapesId)
2135 Unexpect aCatch(SALOME_SalomeException);
2136 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2138 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2139 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2140 SALOME::BAD_PARAM );
2142 if ( CORBA::is_nil( theMesh ) )
2143 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2144 SALOME::BAD_PARAM );
2146 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2149 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2150 meshServant->Load();
2151 ASSERT( meshServant );
2152 if ( meshServant ) {
2153 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2154 meshServant->CheckGeomModif();
2155 // get local TopoDS_Shape
2156 TopoDS_Shape myLocShape;
2157 if(theMesh->HasShapeToMesh())
2158 myLocShape = GeomObjectToShape( theShapeObject );
2160 return result._retn();
2162 // call implementation compute
2163 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2165 ::MeshDimension aDim = (MeshDimension)theDimension;
2166 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2168 int nbShapeId = shapeIds.size();
2169 theShapesId.length( nbShapeId );
2170 // iterates on shapes and collect mesh entities into mesh preview
2171 TSetOfInt::const_iterator idIt = shapeIds.begin();
2172 TSetOfInt::const_iterator idEnd = shapeIds.end();
2173 std::map< int, int > mapOfShIdNb;
2174 std::set< SMESH_TLink > setOfEdge;
2175 std::list< SMDSAbs_ElementType > listOfElemType;
2176 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2177 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2178 TNode2LocalIDMap mapNode2LocalID;
2179 list< TNodeLocalID > connectivity;
2180 int i, nbConnNodes = 0;
2181 std::set< const SMESH_subMesh* > setOfVSubMesh;
2182 // iterates on shapes
2183 for ( ; idIt != idEnd; idIt++ )
2185 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2187 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2188 if ( !sm || !sm->IsMeshComputed() )
2191 const TopoDS_Shape& aSh = sm->GetSubShape();
2192 const int shDim = myGen.GetShapeDim( aSh );
2193 if ( shDim < 1 || shDim > theDimension )
2196 mapOfShIdNb[ *idIt ] = 0;
2197 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2199 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2200 if ( !smDS ) continue;
2202 if ( theDimension == SMESH::DIM_2D )
2204 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2205 while ( faceIt->more() )
2207 const SMDS_MeshElement* face = faceIt->next();
2208 int aNbNode = face->NbNodes();
2210 aNbNode /= 2; // do not take into account additional middle nodes
2212 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2213 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2215 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2216 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2218 listOfElemType.push_back( SMDSAbs_Edge );
2219 connectivity.push_back
2220 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2221 connectivity.push_back
2222 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2228 else if ( theDimension == SMESH::DIM_1D )
2230 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2231 while ( nodeIt->more() )
2233 listOfElemType.push_back( SMDSAbs_Node );
2234 connectivity.push_back
2235 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2237 // add corner nodes by first vertex from edge
2238 SMESH_subMeshIteratorPtr edgeSmIt =
2239 sm->getDependsOnIterator(/*includeSelf*/false,
2240 /*complexShapeFirst*/false);
2241 while ( edgeSmIt->more() )
2243 SMESH_subMesh* vertexSM = edgeSmIt->next();
2244 // check that vertex is not already treated
2245 if ( !setOfVSubMesh.insert( vertexSM ).second )
2247 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2250 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2251 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2252 while ( nodeIt->more() )
2254 listOfElemType.push_back( SMDSAbs_Node );
2255 connectivity.push_back
2256 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2262 // fill node coords and assign local ids to the nodes
2263 int nbNodes = mapNode2LocalID.size();
2264 result->nodesXYZ.length( nbNodes );
2265 TNodeLocalID node2ID = mapNode2LocalID.begin();
2266 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2267 node2ID->second = i;
2268 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2269 result->nodesXYZ[i].x = node->X();
2270 result->nodesXYZ[i].y = node->Y();
2271 result->nodesXYZ[i].z = node->Z();
2273 // fill connectivity
2274 result->elementConnectivities.length( nbConnNodes );
2275 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2276 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2277 result->elementConnectivities[i] = (*connIt)->second;
2280 // fill element types
2281 result->elementTypes.length( listOfElemType.size() );
2282 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2283 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2284 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2286 SMDSAbs_ElementType elemType = *typeIt;
2287 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2288 result->elementTypes[i].isPoly = false;
2289 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2292 // correct number of shapes
2293 theShapesId.length( mapOfShIdNb.size() );
2297 catch ( std::bad_alloc& ) {
2298 INFOS( "Precompute(): lack of memory" );
2300 catch ( SALOME_Exception& S_ex ) {
2301 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2304 INFOS( "Precompute(): unknown exception " );
2306 return result._retn();
2310 //=============================================================================
2312 * SMESH_Gen_i::Evaluate
2314 * Evaluate mesh on a shape
2316 //=============================================================================
2318 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2319 GEOM::GEOM_Object_ptr theShapeObject)
2321 Unexpect aCatch(SALOME_SalomeException);
2322 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2324 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2325 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2327 if ( CORBA::is_nil( theMesh ) )
2328 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2330 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2331 nbels->length(SMESH::Entity_Last);
2332 int i = SMESH::Entity_Node;
2333 for (; i < SMESH::Entity_Last; i++)
2336 // Update Python script
2337 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2338 << theMesh << ", " << theShapeObject << ")";
2342 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2343 ASSERT( meshServant );
2344 if ( meshServant ) {
2345 meshServant->Load();
2346 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2347 meshServant->CheckGeomModif();
2348 // get local TopoDS_Shape
2349 TopoDS_Shape myLocShape;
2350 if(theMesh->HasShapeToMesh())
2351 myLocShape = GeomObjectToShape( theShapeObject );
2353 myLocShape = SMESH_Mesh::PseudoShape();
2354 // call implementation compute
2355 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2356 MapShapeNbElems aResMap;
2357 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2358 MapShapeNbElemsItr anIt = aResMap.begin();
2359 for(; anIt!=aResMap.end(); anIt++) {
2360 const vector<smIdType>& aVec = (*anIt).second;
2361 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2362 smIdType nbElem = aVec[i];
2363 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2365 SMESH_subMesh* sm = anIt->first;
2366 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2367 const SMESH_Algo* algo = sm->GetAlgo();
2368 if ( (algo && !error.get()) || error->IsOK() )
2369 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2373 nbels[i] += aVec[i];
2377 return nbels._retn();
2380 catch ( std::bad_alloc& ) {
2381 INFOS( "Evaluate(): lack of memory" );
2383 catch ( SALOME_Exception& S_ex ) {
2384 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2387 INFOS( "Evaluate(): unknown exception " );
2390 return nbels._retn();
2393 //================================================================================
2395 * \brief Return geometrical object the given element is built on
2396 * \param theMesh - the mesh the element is in
2397 * \param theElementID - the element ID
2398 * \param theGeomName - the name of the result geom object if it is not yet published
2399 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2401 //================================================================================
2403 GEOM::GEOM_Object_ptr
2404 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2405 SMESH::smIdType theElementID,
2406 const char* theGeomName)
2408 Unexpect aCatch(SALOME_SalomeException);
2410 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2411 if ( !geom->_is_nil() ) {
2412 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2413 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2415 // try to find the corresponding SObject
2416 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2417 if ( SObj->_is_nil() ) // submesh can be not found even if published
2419 // try to find published submesh
2420 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2421 if ( !geom->IsMainShape() && list->length() == 1 ) {
2422 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2423 SALOMEDS::ChildIterator_wrap it;
2424 if ( !mainSO->_is_nil() ) {
2425 it = getStudyServant()->NewChildIterator( mainSO );
2427 if ( !it->_is_nil() ) {
2428 for ( it->InitEx(true); it->More(); it->Next() ) {
2429 SALOMEDS::SObject_wrap so = it->Value();
2430 CORBA::Object_var obj = SObjectToObject( so );
2431 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2432 if ( !subGeom->_is_nil() ) {
2433 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2434 if ( subList->length() == 1 && list[0] == subList[0] ) {
2444 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2445 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2447 // return only published geometry
2448 if ( !SObj->_is_nil() ) {
2449 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2450 CORBA::Object_var obj = SObjectToObject( SObj );
2451 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2455 return GEOM::GEOM_Object::_nil();
2458 //================================================================================
2460 * \brief Return geometrical object the given element is built on.
2461 * \param theMesh - the mesh the element is in
2462 * \param theElementID - the element ID
2463 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2465 //================================================================================
2467 GEOM::GEOM_Object_ptr
2468 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2469 SMESH::smIdType theElementID)
2471 Unexpect aCatch(SALOME_SalomeException);
2472 if ( CORBA::is_nil( theMesh ) )
2473 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2475 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2476 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2478 // get a core mesh DS
2479 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2480 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2482 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2483 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2484 // find the element in mesh
2485 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2486 // find a shape id by the element
2487 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2488 // get a geom object by the shape id
2489 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2490 if ( geom->_is_nil() ) {
2491 // try to find a published sub-shape
2492 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2493 SALOMEDS::ChildIterator_wrap it;
2494 if ( !mainSO->_is_nil() ) {
2495 it = getStudyServant()->NewChildIterator( mainSO );
2497 if ( !it->_is_nil() ) {
2498 for ( it->InitEx(true); it->More(); it->Next() ) {
2499 SALOMEDS::SObject_wrap so = it->Value();
2500 CORBA::Object_var obj = SObjectToObject( so );
2501 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2502 if ( !subGeom->_is_nil() ) {
2503 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2504 if ( subList->length() == 1 && shapeID == subList[0] ) {
2512 if ( geom->_is_nil() ) {
2514 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2515 if ( !op->_is_nil() )
2516 geom = op->GetSubShape( mainShape, shapeID );
2521 if ( !geom->_is_nil() ) {
2522 GeomObjectToShape( geom ); // let geom client remember the found shape
2523 return geom._retn();
2528 return GEOM::GEOM_Object::_nil();
2531 //================================================================================
2533 * SMESH_Gen_i::Concatenate
2535 * Concatenate the given meshes into one mesh
2537 //================================================================================
2539 SMESH::SMESH_Mesh_ptr
2540 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2541 CORBA::Boolean theUniteIdenticalGroups,
2542 CORBA::Boolean theMergeNodesAndElements,
2543 CORBA::Double theMergeTolerance,
2544 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2546 return ConcatenateCommon(theMeshesArray,
2547 theUniteIdenticalGroups,
2548 theMergeNodesAndElements,
2554 //================================================================================
2556 * SMESH_Gen_i::ConcatenateWithGroups
2558 * Concatenate the given meshes into one mesh
2559 * Create the groups of all elements from initial meshes
2561 //================================================================================
2563 SMESH::SMESH_Mesh_ptr
2564 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2565 CORBA::Boolean theUniteIdenticalGroups,
2566 CORBA::Boolean theMergeNodesAndElements,
2567 CORBA::Double theMergeTolerance,
2568 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2570 return ConcatenateCommon(theMeshesArray,
2571 theUniteIdenticalGroups,
2572 theMergeNodesAndElements,
2578 //================================================================================
2580 * SMESH_Gen_i::ConcatenateCommon
2582 * Concatenate the given meshes into one mesh
2584 //================================================================================
2586 SMESH::SMESH_Mesh_ptr
2587 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2588 CORBA::Boolean theUniteIdenticalGroups,
2589 CORBA::Boolean theMergeNodesAndElements,
2590 CORBA::Double theMergeTolerance,
2591 CORBA::Boolean theCommonGroups,
2592 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2594 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2595 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2597 // create mesh if theMeshToAppendTo not provided
2598 SMESH::SMESH_Mesh_var newMesh;
2599 if ( CORBA::is_nil( theMeshToAppendTo ))
2600 newMesh = CreateEmptyMesh();
2602 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2603 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2604 if ( !newImpl ) return newMesh._retn();
2607 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2608 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2610 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2611 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2612 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2613 TGroupsMap groupsMap;
2614 TListOfNewGroups listOfNewGroups;
2616 if ( !CORBA::is_nil( theMeshToAppendTo ))
2618 // fill groupsMap with existing groups
2619 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2620 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2622 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2623 if ( !group->_is_nil() )
2625 CORBA::String_var name = group->GetName();
2626 SMESH::ElementType type = group->GetType();
2627 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2632 ::SMESH_MeshEditor newEditor( &locMesh );
2633 ::SMESH_MeshEditor::ElemFeatures elemType;
2635 // loop on sub-meshes
2636 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2638 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2639 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2640 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2641 if ( !initImpl ) continue;
2642 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2646 // assure that IDs increment by one during iteration
2647 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2648 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2649 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2650 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2652 initMeshDS->Modified();
2653 initMeshDS->CompactMesh();
2656 // remember nb of elements before filling in
2657 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2661 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2662 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2663 while ( elemIt->more() )
2665 SMESH_NodeXYZ node = elemIt->next();
2666 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2671 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2672 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2674 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2675 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2676 while ( elemIt->more() )
2678 const SMDS_MeshElement* elem = elemIt->next();
2679 elemType.myNodes.resize( elem->NbNodes() );
2681 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2682 for ( int k = 0; itNodes->more(); k++)
2684 const SMDS_MeshNode* node = itNodes->next();
2685 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2688 // creates a corresponding element on existent nodes in new mesh
2689 newElems[ elem->GetID() ] =
2690 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2692 newEditor.ClearLastCreated(); // forget the history
2695 // create groups of just added elements
2696 SMESH::SMESH_Group_var newGroup;
2697 SMESH::ElementType groupType;
2698 if ( theCommonGroups )
2701 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2702 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2703 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2704 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2707 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2709 for( groupType = SMESH::NODE;
2710 groupType < SMESH::NB_ELEMENT_TYPES;
2711 groupType = (SMESH::ElementType)( groupType + 1 ))
2713 if ( curState[ groupType ] <= prevState[ groupType ])
2714 continue; // no elements of groupType added from the i-th mesh
2716 // make a group name
2717 std::string groupName = "Gr";
2718 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2720 CORBA::String_var name = meshSO->GetName();
2724 groupName += typeNames[ groupType ];
2726 // make and fill a group
2727 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2728 std::vector< const SMDS_MeshElement* > & elemVec =
2729 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2730 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2732 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2734 for ( size_t j = 0; j < elemVec.size(); ++j )
2736 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2737 grpDS->Add( elemVec[j] );
2741 listOfNewGroups.clear();
2742 listOfNewGroups.push_back( newGroup );
2743 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2748 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2752 SMESH::SMESH_GroupBase_ptr group;
2753 CORBA::String_var groupName;
2754 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2756 // loop on groups of a source mesh
2757 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2758 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2760 group = listOfGroups[iG];
2761 groupType = group->GetType();
2762 groupName = group->GetName();
2763 std::string name = groupName.in();
2765 // convert a list of IDs
2766 newIDs->length( group->Size() );
2767 std::vector< const SMDS_MeshElement* > & elemVec =
2768 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2769 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2771 while ( itGrElems->more() )
2773 const SMDS_MeshElement* elem = itGrElems->next();
2774 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2776 newIDs[ nbElems++ ] = newElem->GetID();
2778 newIDs->length( nbElems );
2780 // check that a current group name and type don't have identical ones in final mesh
2781 listOfNewGroups.clear();
2782 TNameAndType nameAndType( name, groupType );
2783 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2784 if ( anIter == groupsMap.end() )
2786 // add a new group in the mesh
2787 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2788 newGroup->Add( newIDs );
2790 listOfNewGroups.push_back( newGroup );
2791 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2793 else if ( theUniteIdenticalGroups )
2795 // unite identical groups
2796 TListOfNewGroups& aNewGroups = anIter->second;
2797 aNewGroups.front()->Add( newIDs );
2801 // rename identical groups
2802 newGroup = newImpl->CreateGroup( groupType, groupName );
2803 newGroup->Add( newIDs );
2805 TListOfNewGroups& newGroups = anIter->second;
2806 std::string newGroupName;
2807 if ( newGroups.size() == 1 )
2809 newGroupName = name + "_1";
2810 newGroups.front()->SetName( newGroupName.c_str() );
2812 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2813 newGroup->SetName( newGroupName.c_str() );
2814 newGroups.push_back( newGroup );
2817 } // if an IDSource is a mesh
2820 if ( theMergeNodesAndElements ) // merge nodes
2822 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2823 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2824 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2825 /*SeparateCornersAndMedium=*/ false );
2826 newEditor.MergeNodes( groupsOfNodes );
2828 newEditor.MergeEqualElements();
2831 // Update Python script
2832 pythonDump << newMesh << " = " << this
2833 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2834 << theMeshesArray << ", "
2835 << theUniteIdenticalGroups << ", "
2836 << theMergeNodesAndElements << ", "
2837 << TVar( theMergeTolerance ) << ", "
2838 << theMeshToAppendTo << " )";
2840 pPythonDump.reset(); // enable python dump from GetGroups()
2842 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2843 if ( !newMesh->_is_nil() )
2845 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2848 // IPAL21468 Change icon of compound because it need not be computed.
2849 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2850 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2852 newMeshDS->Modified();
2854 return newMesh._retn();
2857 //================================================================================
2859 * \brief Create a mesh by copying a part of another mesh
2860 * \param meshPart - a part of mesh to copy
2861 * \param toCopyGroups - to create in the new mesh groups
2862 * the copied elements belongs to
2863 * \param toKeepIDs - to preserve IDs of the copied elements or not
2864 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2866 //================================================================================
2868 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2869 const char* meshName,
2870 CORBA::Boolean toCopyGroups,
2871 CORBA::Boolean toKeepIDs)
2873 Unexpect aCatch(SALOME_SalomeException);
2875 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2876 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2878 // 1. Get source mesh
2880 if ( CORBA::is_nil( meshPart ))
2881 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2883 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2884 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2886 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2888 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2890 // 2. Make a new mesh
2892 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2893 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2895 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2896 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2897 if ( !meshSO->_is_nil() )
2899 SetName( meshSO, meshName, "Mesh" );
2900 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2902 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2903 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2904 ::SMESH_MeshEditor::ElemFeatures elemType;
2906 // 3. Get elements to copy
2908 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2909 TIDSortedElemSet srcElems;
2910 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2911 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2914 srcElemIt = srcMeshDS->elementsIterator();
2915 srcNodeIt = srcMeshDS->nodesIterator();
2919 SMESH::smIdType_array_var ids = meshPart->GetIDs();
2920 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2922 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2923 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2924 srcElems.insert( elem );
2928 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2929 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2930 srcElems.insert( elem );
2932 if ( srcElems.empty() )
2933 return newMesh._retn();
2935 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2936 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2941 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2942 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2943 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2945 const SMDS_MeshNode *nSrc, *nTgt;
2946 vector< const SMDS_MeshNode* > nodes;
2947 while ( srcElemIt->more() )
2949 const SMDS_MeshElement * elem = srcElemIt->next();
2951 nodes.resize( elem->NbNodes());
2952 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2954 for ( iN = 0; nIt->more(); ++iN )
2956 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2957 nTgt = newMeshDS->FindNode( nSrc->GetID());
2959 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2964 for ( iN = 0; nIt->more(); ++iN )
2966 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2967 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2969 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2970 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2974 if ( elem->GetType() != SMDSAbs_Node )
2976 elemType.Init( elem, /*basicOnly=*/false );
2977 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2979 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2980 if ( toCopyGroups && !toKeepIDs )
2981 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2983 } // while ( srcElemIt->more() )
2985 // 4(b). Copy free nodes
2987 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2989 while ( srcNodeIt->more() )
2991 nSrc = srcNodeIt->next();
2992 if ( nSrc->NbInverseElements() == 0 )
2995 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2997 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3004 int nbNewGroups = 0;
3007 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3008 while ( gIt->more() )
3010 SMESH_Group* group = gIt->next();
3011 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3013 // Check group type. We copy nodal groups containing nodes of copied element
3014 SMDSAbs_ElementType groupType = groupDS->GetType();
3015 if ( groupType != SMDSAbs_Node &&
3016 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3017 continue; // group type differs from types of meshPart
3019 // Find copied elements in the group
3020 vector< const SMDS_MeshElement* > groupElems;
3021 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3024 const SMDS_MeshElement* foundElem;
3025 if ( groupType == SMDSAbs_Node )
3027 while ( eIt->more() )
3028 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3029 groupElems.push_back( foundElem );
3033 while ( eIt->more() )
3034 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3035 groupElems.push_back( foundElem );
3040 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3041 if ( e2eMap.empty() ) continue;
3042 smIdType minID = e2eMap.begin()->first->GetID();
3043 smIdType maxID = e2eMap.rbegin()->first->GetID();
3044 TE2EMap::iterator e2e;
3045 while ( eIt->more() && groupElems.size() < e2eMap.size())
3047 const SMDS_MeshElement* e = eIt->next();
3048 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3049 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3050 groupElems.push_back( e2e->second );
3054 if ( !groupElems.empty() )
3056 SMESH::SMESH_Group_var newGroupObj =
3057 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3058 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3060 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3061 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3062 for ( unsigned i = 0; i < groupElems.size(); ++i )
3063 smdsGroup.Add( groupElems[i] );
3071 newMeshDS->Modified();
3073 *pyDump << newMesh << " = " << this
3074 << ".CopyMesh( " << meshPart << ", "
3075 << "'" << meshName << "', "
3076 << toCopyGroups << ", "
3077 << toKeepIDs << ")";
3079 pyDumpDeleter.reset(); // allow dump in GetGroups()
3081 if ( nbNewGroups > 0 ) // dump created groups
3082 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3084 return newMesh._retn();
3088 namespace // utils for CopyMeshWithGeom()
3090 typedef std::map< std::string, std::string > TStr2StrMap;
3091 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3092 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3093 typedef std::map< std::string, int > TName2IndexMap;
3095 //================================================================================
3097 * \brief Return a new sub-shape corresponding to an old one
3099 //================================================================================
3103 SMESH_Mesh_i* mySrcMesh_i;
3104 SMESH_Mesh_i* myNewMesh_i;
3105 SMESH_Gen_i* myGen_i;
3109 TStr2StrMap myOld2NewEntryMap; // map of study entries
3111 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3112 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3113 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3116 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3118 // not directly relating to shape search
3119 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3121 //================================================================================
3123 * \brief Constructor
3125 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3126 SMESH_Mesh_i* newMesh_i,
3127 SMESH_Gen_i* smeshGen_i )
3128 : mySrcMesh_i( srcMesh_i ),
3129 myNewMesh_i( newMesh_i ),
3130 myGen_i ( smeshGen_i ),
3131 myToPublish( smeshGen_i->IsEnablePublish() ),
3132 myGIPMapDone( false )
3134 // retrieve from the study shape mapping made thanks to
3135 // "Set presentation parameters and sub-shapes from arguments" option
3137 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3138 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3139 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3140 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3141 if ( newSO->_is_nil() )
3143 myToPublish = false;
3146 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3148 CORBA::String_var oldEntry = oldSO->GetID();
3149 CORBA::String_var newEntry = newSO->GetID();
3150 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3151 std::string( newEntry.in() )));
3152 std::string newMainEntry = newEntry.in();
3154 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3155 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3156 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3157 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3158 /*groupsOnly=*/false );
3159 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3161 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3162 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3163 bool refFound = false;
3164 for ( ; anIter->More(); anIter->Next() )
3166 SALOMEDS::SObject_wrap so = anIter->Value();
3167 if ( so->ReferencedObject( oldSO.inout() ))
3169 oldEntry = oldSO->GetID();
3170 newEntry = newSO->GetID();
3171 if (( refFound = ( newMainEntry != oldEntry.in() )))
3172 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3173 std::string( newEntry.in() )));
3178 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3179 if ( father->_is_equivalent( mainShapeNew ))
3181 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3182 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3183 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3184 CORBA::String_var name = newSO->GetName();
3186 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3192 //================================================================================
3194 * \brief Find a new sub-shape corresponding to an old one
3196 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3199 return GEOM::GEOM_Object::_duplicate( oldShape );
3201 GEOM::GEOM_Object_var newShape;
3203 if ( CORBA::is_nil( oldShape ))
3204 return newShape._retn();
3206 if ( !isChildOfOld( oldShape ))
3207 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3209 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3210 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3212 // try to find by entry or name
3215 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3216 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3217 if ( o2nID != myOld2NewEntryMap.end() )
3219 newShape = getShapeByEntry( o2nID->second );
3221 if ( newShape->_is_nil() )
3223 CORBA::String_var name = oldShape->GetName();
3224 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3225 if ( n2ind != myName2SubshapeIndex.end() )
3227 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3228 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3229 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3230 if ( oldIndices->length() == 0 ||
3231 newIndices->length() == 0 ||
3232 getShapeType( myNewMesh_i, newIndices[0] ) !=
3233 getShapeType( mySrcMesh_i, oldIndices[0] ))
3234 newShape = GEOM::GEOM_Object::_nil();
3239 if ( newShape->_is_nil() )
3241 // try to construct a new sub-shape using myGIPMap
3243 std::vector< int > newIndices;
3244 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3245 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3247 findNewIDs( oldIndices[i], newIndices );
3249 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3252 newShape = getInPlace( oldShape );
3254 if ( !newIndices.empty() && newShape->_is_nil() )
3256 // search for a sub-shape with same ids
3257 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3258 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3259 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3260 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3262 if ( newShape->_is_nil() )
3265 // create a new shape
3266 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3268 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3270 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3271 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3273 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3274 newIndicesList->length( newIndices.size() );
3275 for ( size_t i = 0; i < newIndices.size(); ++i )
3276 newIndicesList[ i ] = newIndices[ i ];
3277 grOp->UnionIDs( newShape, newIndicesList );
3281 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3282 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3291 if ( !newShape->_is_nil() && myToPublish )
3293 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3294 if ( !newEntry.in() || !newEntry.in()[0] )
3296 CORBA::String_var name = oldShape->GetName();
3297 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3298 newEntry = newShape->GetStudyEntry();
3299 oldEntry = oldShape->GetStudyEntry();
3300 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3301 std::string( newEntry.in() )));
3305 return newShape._retn();
3308 //================================================================================
3310 * \brief Return a study entry of a new shape by study entry of the old one
3312 std::string FindNew( const std::string & oldEntry )
3317 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3318 if ( o2nID != myOld2NewEntryMap.end() )
3319 return o2nID->second;
3321 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3322 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3325 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3326 if ( newShape->_is_nil() )
3327 return std::string();
3329 CORBA::String_var newEntry = newShape->GetStudyEntry();
3330 return newEntry.in();
3333 //================================================================================
3335 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3336 * Return zero if not found or there are more than one new ID
3338 int FindNew( int oldID )
3347 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3349 if ( myGIPMap[ oldID ].length() == 1 )
3351 newID = myGIPMap[ oldID ][ 0 ];
3353 else if ( myGIPMap[ oldID ].length() > 1 &&
3354 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3356 // select a meshed VERTEX
3357 SMESH_subMesh* newSM;
3358 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3359 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3360 ( !newSM->IsEmpty() ))
3361 newID = myGIPMap[ oldID ][ i ];
3367 //================================================================================
3369 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3370 * Return zero if the old shape is not kept as is in the new shape.
3372 int FindNewNotChanged( SMESH_subMesh* oldSM )
3375 return oldSM->GetId();
3377 int newID = FindNew( oldSM->GetId() );
3381 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3385 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3386 // one new sub-shape of the same type.
3388 if ( oldSM->DependsOn().size() !=
3389 newSM->DependsOn().size() )
3392 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3393 while ( srcSMIt->more() )
3395 oldSM = srcSMIt->next();
3396 int newSubID = FindNew( oldSM->GetId() );
3397 if ( getShapeType( myNewMesh_i, newSubID ) !=
3398 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3404 //================================================================================
3406 * \brief Return shape by study entry
3408 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3410 GEOM::GEOM_Object_var shape;
3411 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3412 if ( !so->_is_nil() )
3414 CORBA::Object_var obj = so->GetObject();
3415 shape = GEOM::GEOM_Object::_narrow( obj );
3417 return shape._retn();
3420 //================================================================================
3422 * \brief Fill myGIPMap by calling GetInPlaceMap()
3426 if ( !myGIPMapDone )
3428 myGIPMapDone = true;
3430 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3431 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3432 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3433 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3436 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3440 myGIPMap = new GEOM::ListOfListOfLong();
3445 //================================================================================
3447 * \brief Get new sub-shape by calling GetInPlace()
3449 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3451 GEOM::GEOM_Object_var newShape;
3453 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3454 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3455 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3458 newShape = op->GetInPlace( mainShapeNew, oldShape );
3463 return newShape._retn();
3466 //================================================================================
3468 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3469 * number of found IDs
3471 int findNewIDs( int oldID, std::vector< int >& newIDs )
3473 size_t prevNbIDs = newIDs.size();
3475 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3477 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3478 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3480 return newIDs.size() - prevNbIDs;
3483 //================================================================================
3485 * \brief Check if an object relates to the old shape
3487 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3489 if ( CORBA::is_nil( oldShape ))
3491 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3492 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3493 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3494 mainShapeOld1->_is_equivalent( oldShape ));
3497 //================================================================================
3499 * \brief Return shape type by shape ID
3501 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3503 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3504 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3505 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3508 //================================================================================
3510 * \brief Store a source sub-shape for which a counterpart not found and
3511 * a smesh object invalid due to that
3513 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3514 SALOMEDS::SObject_wrap smeshSO )
3516 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3517 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3519 CORBA::String_var smeshEntry = smeshSO->GetID();
3520 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3524 //================================================================================
3526 * \brief Store a source sub-shape for which a counterpart not found and
3527 * a smesh object invalid due to that
3529 void AddInvalid( std::string geomEntry,
3530 SALOMEDS::SObject_wrap smeshSO )
3532 if ( !geomEntry.empty() )
3534 CORBA::String_var smeshEntry = smeshSO->GetID();
3535 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3539 //================================================================================
3541 * \brief Store a source sub-shape for which a counterpart not found and
3542 * a smesh object invalid due to that
3544 void AddInvalid( int oldGeomID,
3545 SALOMEDS::SObject_wrap smeshSO )
3547 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3548 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3551 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3552 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3554 SMESH_Comment geomName( typeName[ shapeType ]);
3555 geomName << " #" << oldGeomID;
3557 CORBA::String_var smeshEntry = smeshSO->GetID();
3558 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3561 //================================================================================
3563 * \brief Return entries of a source sub-shape for which a counterpart not found and
3564 * of smesh objects invalid due to that
3566 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3567 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3570 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3571 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3573 nbSO += 1 + entry2entrySet->second.size();
3575 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3576 theInvalidEntries->length ( nbSO );
3577 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3579 entry2entrySet = myInvalidMap.begin();
3580 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3582 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3584 std::set< std::string > & entrySet = entry2entrySet->second;
3585 std::set< std::string >::iterator entry = entrySet.begin();
3586 for ( ; entry != entrySet.end(); ++entry )
3588 theInvalidEntries[ iEntry++ ] = entry->c_str();
3590 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3591 if ( !so->_is_nil() )
3592 theInvalidMeshSObjects[ iSO++ ] = so;
3597 }; // struct ShapeMapper
3599 //================================================================================
3601 * \brief Append an item to a CORBA sequence
3603 template < class CORBA_seq, class ITEM >
3604 void append( CORBA_seq& seq, ITEM item )
3606 if ( !CORBA::is_nil( item ))
3608 seq->length( 1 + seq->length() );
3609 seq[ seq->length() - 1 ] = item;
3612 } // namespace // utils for CopyMeshWithGeom()
3614 //================================================================================
3616 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3617 * \param [in] sourceMesh - a mesh to copy
3618 * \param [in] newGeometry - a new geometry
3619 * \param [in] toCopyGroups - to create groups in the new mesh
3620 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3621 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3622 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3623 * \param [out] newMesh - return a new mesh
3624 * \param [out] newGroups - return new groups
3625 * \param [out] newSubmeshes - return new sub-meshes
3626 * \param [out] newHypotheses - return new algorithms and hypotheses
3627 * \param [out] invalidEntries - return study entries of objects whose
3628 * counterparts are not found in the newGeometry, followed by entries
3629 * of mesh sub-objects that are invalid because they depend on a not found
3630 * preceding sub-shape
3631 * \return CORBA::Boolean - is a success
3633 //================================================================================
3635 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3636 GEOM::GEOM_Object_ptr theNewGeometry,
3637 const char* theMeshName,
3638 CORBA::Boolean theToCopyGroups,
3639 CORBA::Boolean theToReuseHypotheses,
3640 CORBA::Boolean theToCopyElements,
3641 SMESH::SMESH_Mesh_out theNewMesh,
3642 SMESH::ListOfGroups_out theNewGroups,
3643 SMESH::submesh_array_out theNewSubmeshes,
3644 SMESH::ListOfHypothesis_out theNewHypotheses,
3645 SMESH::string_array_out theInvalidEntries)
3647 if ( CORBA::is_nil( theSourceMesh ) ||
3648 CORBA::is_nil( theNewGeometry ))
3649 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3651 if ( !theSourceMesh->HasShapeToMesh() )
3652 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3657 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3659 theNewMesh = CreateMesh( theNewGeometry );
3660 theNewGroups = new SMESH::ListOfGroups();
3661 theNewSubmeshes = new SMESH::submesh_array();
3662 theNewHypotheses = new SMESH::ListOfHypothesis();
3663 theInvalidEntries = new SMESH::string_array();
3665 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3667 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3668 GEOM::GEOM_Object_var geom, newGeom;
3669 SALOMEDS::SObject_wrap so;
3671 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3672 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3675 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3677 // treat hypotheses of mesh and sub-meshes
3678 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3679 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3681 bool isSubMesh = ( iSM < smList->length() );
3684 // create a new sub-mesh
3685 SMESH::SMESH_subMesh_var newSM;
3686 geom = smList[iSM]->GetSubShape();
3687 so = ObjectToSObject( smList[iSM] );
3688 CORBA::String_var name;
3689 if ( !so->_is_nil() )
3690 name = so->GetName();
3691 newGeom = shapeMapper.FindNew( geom );
3692 if ( newGeom->_is_nil() )
3694 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3695 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3700 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3702 append( theNewSubmeshes, newSM );
3704 if ( newGeom->_is_nil() )
3705 continue; // don't assign hypotheses
3709 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3711 so = ObjectToSObject( theNewMesh );
3712 SetName( so, theMeshName, "Mesh" );
3715 // assign hypotheses
3716 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3717 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3719 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3720 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3722 // get geometry hyp depends on
3723 std::vector< std::string > entryArray;
3724 std::vector< int > subIDArray;
3725 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3727 if ( !theToReuseHypotheses || dependsOnGeom )
3729 // create a new hypothesis
3730 CORBA::String_var type = hyp->GetName();
3731 CORBA::String_var lib = hyp->GetLibName();
3732 CORBA::String_var data = hyp_i->SaveTo();
3735 hyp = CreateHypothesis( type, lib );
3736 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3737 hyp_i->LoadFrom( data.in() );
3738 append( theNewHypotheses, hyp );
3742 // update geometry hyp depends on
3743 if ( dependsOnGeom )
3745 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3747 if ( !entryArray[ iGeo ].empty() )
3749 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3750 if ( newEntry.empty() )
3753 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3754 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3756 entryArray[ iGeo ] = newEntry;
3759 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3761 if ( subIDArray[ iGeo ] > 0 )
3763 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3767 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3768 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3770 subIDArray[ iGeo ] = newID;
3773 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3777 CORBA::String_var errorText;
3778 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3779 if ( errorText.in()[0] )
3782 } // loop on hypotheses
3783 } // loop on sub-meshes and mesh
3786 // copy mesh elements, keeping IDs
3787 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3788 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3790 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3791 ::SMESH_MeshEditor::ElemFeatures elemData;
3793 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3794 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3795 /*vertexLast=*/false);
3796 while ( srcSMIt->more() )
3798 SMESH_subMesh* srcSM = srcSMIt->next();
3799 if ( srcSM->IsEmpty() )
3800 continue; // not yet computed
3801 int newID = shapeMapper.FindNewNotChanged( srcSM );
3805 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3806 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3807 while ( nIt->more() )
3809 SMESH_NodeXYZ node( nIt->next() );
3810 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3812 const SMDS_PositionPtr pos = node->GetPosition();
3813 const double* uv = pos->GetParameters();
3814 switch ( pos->GetTypeOfPosition() )
3816 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3817 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3818 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3819 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3823 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3824 while( eIt->more() )
3826 const SMDS_MeshElement* e = eIt->next();
3827 elemData.Init( e, /*basicOnly=*/false );
3828 elemData.SetID( e->GetID() );
3829 elemData.myNodes.resize( e->NbNodes() );
3830 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3832 for ( iN = 0; nnIt->more(); ++iN )
3834 const SMDS_MeshNode* srcNode = nnIt->next();
3835 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3836 if ( !elemData.myNodes[ iN ])
3839 if ( iN == elemData.myNodes.size() )
3840 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3841 newMeshDS->SetMeshElementOnShape( newElem, newID );
3843 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3844 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3847 newMeshDS->Modified();
3853 TStr2StrMap old2newGroupMap;
3855 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3857 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3858 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3859 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3861 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3862 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3863 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3865 CORBA::String_var name = groups[ i ]->GetName();
3866 SMESH::ElementType elemType = groups[ i ]->GetType();
3868 SMESH::SMESH_GroupBase_var newGroup;
3870 if ( !stdlGroup->_is_nil() )
3872 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3874 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3875 const bool isElem = ( elemType != SMESH::NODE );
3876 CORBA::ULong iE = 0;
3877 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3878 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3880 if ( iE < elemIDs->length() )
3882 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3883 stdlGroup->Add( elemIDs );
3884 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3888 else if ( !geomGroup->_is_nil() )
3890 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3891 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3892 if ( newGeom->_is_nil() )
3894 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3895 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3900 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3903 else if ( !fltrGroup->_is_nil() )
3905 // replace geometry in a filter
3906 SMESH::Filter_var filter = fltrGroup->GetFilter();
3907 SMESH::Filter::Criteria_var criteria;
3908 filter->GetCriteria( criteria.out() );
3910 bool isMissingGroup = false;
3911 std::vector< std::string > badEntries;
3913 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3915 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3916 switch ( criteria[ iCr ].Type )
3918 case SMESH::FT_BelongToMeshGroup:
3920 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3921 btgg->SetGroupID( thresholdID );
3922 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3923 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3924 if ( refGroupSO->_is_nil() )
3926 CORBA::String_var refID = refGroupSO->GetID();
3927 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3928 if ( o2nID == old2newGroupMap.end() )
3930 isMissingGroup = true; // corresponding new group not yet created
3933 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3935 if ( o2nID->second.empty() ) // new referred group is invalid
3936 badEntries.push_back( refID.in() );
3939 case SMESH::FT_BelongToGeom:
3940 case SMESH::FT_BelongToPlane:
3941 case SMESH::FT_BelongToCylinder:
3942 case SMESH::FT_BelongToGenSurface:
3943 case SMESH::FT_LyingOnGeom:
3945 std::string newID = shapeMapper.FindNew( thresholdID );
3946 criteria[ iCr ].ThresholdID = newID.c_str();
3947 if ( newID.empty() )
3948 badEntries.push_back( thresholdID );
3951 case SMESH::FT_ConnectedElements:
3953 if ( thresholdID && thresholdID[0] )
3955 std::string newID = shapeMapper.FindNew( thresholdID );
3956 criteria[ iCr ].ThresholdID = newID.c_str();
3957 if ( newID.empty() )
3958 badEntries.push_back( thresholdID );
3964 } // loop on criteria
3966 if ( isMissingGroup && i < nbGroups )
3968 // to treat the group again
3969 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3973 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3974 newFilter->SetCriteria( criteria );
3976 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3977 newFilter->UnRegister();
3979 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3980 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3981 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3983 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3985 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3988 if ( !badEntries.empty() )
3991 } // treat a group on filter
3993 append( theNewGroups, newGroup );
3995 // fill old2newGroupMap
3996 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3997 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3998 if ( !srcSO->_is_nil() )
4000 CORBA::String_var srcID, newID("");
4001 srcID = srcSO->GetID();
4002 if ( !newSO->_is_nil() )
4003 newID = newSO->GetID();
4004 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4005 std::string( newID.in() )));
4008 if ( newGroup->_is_nil() )
4013 newMeshDS->CompactMesh();
4016 if ( !theMeshName || !theMeshName[0] )
4018 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4019 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4020 CORBA::String_var oldName = soOld->GetName();
4021 SetName( soNew, oldName.in(), "Mesh" );
4023 // mark invalid objects
4024 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4026 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4027 highLightInvalid( invalidSObjects[i].in(), true );
4030 << theNewMesh << ", "
4031 << theNewGroups << ", "
4032 << *theNewSubmeshes.ptr() << ", "
4033 << *theNewHypotheses.ptr() << ", "
4034 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4035 << theSourceMesh << ", "
4036 << theNewGeometry << ", "
4037 << "'" << theMeshName << "', "
4038 << theToCopyGroups << ", "
4039 << theToReuseHypotheses << ", "
4040 << theToCopyElements << " )";
4042 SMESH_CATCH( SMESH::throwCorbaException );
4047 //================================================================================
4049 * \brief Get version of MED format being used.
4051 //================================================================================
4053 char* SMESH_Gen_i::GetMEDFileVersion()
4055 MED::TInt majeur, mineur, release;
4056 majeur = mineur = release = 0;
4057 MED::GetVersionRelease(majeur, mineur, release);
4058 std::ostringstream version;
4059 version << majeur << "." << mineur << "." << release;
4060 return CORBA::string_dup( version.str().c_str() );
4063 //================================================================================
4065 * SMESH_Gen_i::GetMEDVersion
4067 * Get MED version of the file by its name
4069 //================================================================================
4071 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4073 std::string version = MED::GetMEDVersion( theFileName );
4074 return CORBA::string_dup( version.c_str() );
4077 //================================================================================
4079 * SMESH_Gen_i::CheckCompatibility
4081 * Check compatibility of file with MED format being used, read only.
4083 //================================================================================
4085 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4087 return MED::CheckCompatibility( theFileName );
4090 //================================================================================
4092 * SMESH_Gen_i::CheckWriteCompatibility
4094 * Check compatibility of file with MED format being used, for append on write.
4096 //================================================================================
4098 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4100 return MED::CheckCompatibility( theFileName, true );
4103 //================================================================================
4105 * SMESH_Gen_i::GetMeshNames
4107 * Get names of meshes defined in file with the specified name
4109 //================================================================================
4110 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4113 SMESH::string_array_var aResult = new SMESH::string_array();
4114 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4116 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4118 aResult->length( aNbMeshes );
4119 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4120 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4121 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4124 return aResult._retn();
4127 //=============================================================================
4131 * Save SMESH module's data
4133 //=============================================================================
4135 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4140 Kernel_Utils::Localizer loc;
4142 if (!myStudyContext)
4145 // Store study contents as a set of python commands
4148 SALOMEDS::Study_var aStudy = getStudyServant();
4150 // Declare a byte stream
4151 SALOMEDS::TMPFile_var aStreamFile;
4153 // Obtain a temporary dir
4154 TCollection_AsciiString tmpDir =
4155 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4157 // Create a sequence of files processed
4158 SALOMEDS_Tool::ListOfFiles aFileSeq;
4159 aFileSeq.reserve( NUM_TMP_FILES );
4161 TCollection_AsciiString aStudyName( "" );
4163 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4165 // Set names of temporary files
4166 TCollection_AsciiString filename =
4167 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4168 TCollection_AsciiString meshfile =
4169 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4170 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4171 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4172 filename = tmpDir + filename;
4173 meshfile = tmpDir + meshfile;
4176 HDFdataset* aDataset;
4177 HDFgroup* aTopGroup;
4179 HDFgroup* aSubGroup;
4180 HDFgroup* aSubSubGroup;
4181 hdf_size aSize[ 1 ];
4184 //Remove the files if they exist: BugID: 11225
4185 #ifndef WIN32 /* unix functionality */
4186 TCollection_AsciiString cmd("rm -f \"");
4188 TCollection_AsciiString cmd("del /F \"");
4198 system(cmd.ToCString());
4200 // MED writer to be used by storage process
4201 DriverMED_W_SMESHDS_Mesh myWriter;
4202 myWriter.SetFile( meshfile.ToCString() );
4205 // SetStoreName() to groups before storing hypotheses to let them refer to
4206 // groups using "store name", which is "Group <group_persistent_id>"
4208 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4209 for ( ; itBig->More(); itBig->Next() ) {
4210 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4211 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4212 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4213 if ( !CORBA::is_nil( anObject ) ) {
4214 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4215 if ( !myMesh->_is_nil() ) {
4216 myMesh->Load(); // load from study file if not yet done
4217 TPythonDump pd(this); // not to dump GetGroups()
4218 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4219 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4221 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4224 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4225 int anId = myStudyContext->findId( string( objStr.in() ) );
4227 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4228 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4229 aGrpBaseDS->SetStoreName( grpName );
4239 // ---> create HDF file
4240 aFile = new HDFfile( (char*) filename.ToCString() );
4241 aFile->CreateOnDisk();
4243 // --> iterator for top-level objects
4244 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4245 for ( ; itBig->More(); itBig->Next() ) {
4246 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4248 // --> hypotheses root branch (only one for the study)
4249 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4250 // create hypotheses root HDF group
4251 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4252 aTopGroup->CreateOnDisk();
4254 // iterator for all hypotheses
4255 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4256 for ( ; it->More(); it->Next() ) {
4257 SALOMEDS::SObject_wrap mySObject = it->Value();
4258 CORBA::Object_var anObject = SObjectToObject( mySObject );
4259 if ( !CORBA::is_nil( anObject ) ) {
4260 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4261 if ( !myHyp->_is_nil() ) {
4262 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4264 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4265 std::string hypname = hn.in();
4266 std::string libname = ln.in();
4268 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4269 // WIN32 and ".so" for X-system) must be deleted
4270 int libname_len = libname.length();
4272 if( libname_len > 4 )
4273 libname.resize( libname_len - 4 );
4275 // PAL17753 (Regression: missing hypothesis in restored study)
4276 // "lib" also should be removed from the beginning
4277 if( libname_len > 6 )
4278 libname = libname.substr( 3, libname_len - 3 - 3 );
4280 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4281 CORBA::String_var hypdata = myImpl->SaveTo();
4282 int id = myStudyContext->findId( string( objStr.in() ));
4284 // for each hypothesis create HDF group basing on its id
4285 char hypGrpName[30];
4286 sprintf( hypGrpName, "Hypothesis %d", id );
4287 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4288 aGroup->CreateOnDisk();
4289 // --> type name of hypothesis
4290 aSize[ 0 ] = hypname.length() + 1;
4291 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4292 aDataset->CreateOnDisk();
4293 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4294 aDataset->CloseOnDisk();
4295 // --> server plugin library name of hypothesis
4296 aSize[ 0 ] = libname.length() + 1;
4297 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4298 aDataset->CreateOnDisk();
4299 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4300 aDataset->CloseOnDisk();
4301 // --> persistent data of hypothesis
4302 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4303 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4304 aDataset->CreateOnDisk();
4305 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4306 aDataset->CloseOnDisk();
4307 // close hypothesis HDF group
4308 aGroup->CloseOnDisk();
4313 // close hypotheses root HDF group
4314 aTopGroup->CloseOnDisk();
4316 // --> algorithms root branch (only one for the study)
4317 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4318 // create algorithms root HDF group
4319 aTopGroup = new HDFgroup( "Algorithms", aFile );
4320 aTopGroup->CreateOnDisk();
4322 // iterator for all algorithms
4323 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4324 for ( ; it->More(); it->Next() ) {
4325 SALOMEDS::SObject_wrap mySObject = it->Value();
4326 CORBA::Object_var anObject = SObjectToObject( mySObject );
4327 if ( !CORBA::is_nil( anObject ) ) {
4328 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4329 if ( !myHyp->_is_nil() ) {
4330 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4332 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4333 std::string hypname = hn.in();
4334 std::string libname = ln.in();
4336 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4337 // WIN32 and ".so" for X-system) must be deleted
4338 int libname_len = libname.length();
4340 if( libname_len > 4 )
4341 libname.resize( libname_len - 4 );
4343 // PAL17753 (Regression: missing hypothesis in restored study)
4344 // "lib" also should be removed from the beginning
4345 if( libname_len > 6 )
4346 libname = libname.substr( 3, libname_len - 3 - 3 );
4348 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4349 CORBA::String_var hypdata = myImpl->SaveTo();
4350 int id = myStudyContext->findId( string( objStr.in() ) );
4352 // for each algorithm create HDF group basing on its id
4353 char hypGrpName[30];
4354 sprintf( hypGrpName, "Algorithm %d", id );
4355 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4356 aGroup->CreateOnDisk();
4357 // --> type name of algorithm
4358 aSize[0] = hypname.length() + 1;
4359 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4360 aDataset->CreateOnDisk();
4361 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4362 aDataset->CloseOnDisk();
4363 // --> server plugin library name of hypothesis
4364 aSize[0] = libname.length() + 1;
4365 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4366 aDataset->CreateOnDisk();
4367 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4368 aDataset->CloseOnDisk();
4369 // --> persistent data of algorithm
4370 aSize[0] = strlen( hypdata.in() ) + 1;
4371 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4372 aDataset->CreateOnDisk();
4373 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4374 aDataset->CloseOnDisk();
4375 // close algorithm HDF group
4376 aGroup->CloseOnDisk();
4381 // close algorithms root HDF group
4382 aTopGroup->CloseOnDisk();
4384 // --> mesh objects roots branches
4385 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4386 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4387 if ( !CORBA::is_nil( anObject ) ) {
4388 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4389 if ( !myMesh->_is_nil() ) {
4390 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4392 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4393 int id = myStudyContext->findId( string( objStr.in() ) );
4394 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4395 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4396 bool hasShape = myLocMesh.HasShapeToMesh();
4398 // for each mesh open the HDF group basing on its id
4399 char meshGrpName[ 30 ];
4400 sprintf( meshGrpName, "Mesh %d", id );
4401 aTopGroup = new HDFgroup( meshGrpName, aFile );
4402 aTopGroup->CreateOnDisk();
4404 // --> put dataset to hdf file which is a flag that mesh has data
4405 string strHasData = "0";
4406 // check if the mesh is not empty
4407 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4408 // write mesh data to med file
4409 myWriter.SetMesh( mySMESHDSMesh );
4410 myWriter.SetMeshId( id );
4413 aSize[ 0 ] = strHasData.length() + 1;
4414 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4415 aDataset->CreateOnDisk();
4416 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4417 aDataset->CloseOnDisk();
4420 // for each mesh open the HDF group basing on its auto color parameter
4421 char meshAutoColorName[ 30 ];
4422 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4424 anAutoColor[0] = myImpl->GetAutoColor();
4426 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4427 aDataset->CreateOnDisk();
4428 aDataset->WriteOnDisk( anAutoColor );
4429 aDataset->CloseOnDisk();
4431 // issue 0020693. Store _isModified flag
4432 int isModified = myLocMesh.GetIsModified();
4434 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4435 aDataset->CreateOnDisk();
4436 aDataset->WriteOnDisk( &isModified );
4437 aDataset->CloseOnDisk();
4439 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4440 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4442 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4443 aDataset->CreateOnDisk();
4444 aDataset->WriteOnDisk( &meshPersistentId );
4445 aDataset->CloseOnDisk();
4447 // Store SMESH_Mesh_i::_mainShapeTick
4448 int shapeTick = myImpl->MainShapeTick();
4450 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4451 aDataset->CreateOnDisk();
4452 aDataset->WriteOnDisk( &shapeTick );
4453 aDataset->CloseOnDisk();
4455 // write reference on a shape if exists
4456 SALOMEDS::SObject_wrap myRef;
4457 bool shapeRefFound = false;
4458 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4460 SALOMEDS::SObject_wrap myShape;
4461 bool ok = myRef->ReferencedObject( myShape.inout() );
4463 CORBA::Object_var shapeObj = myShape->GetObject();
4464 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4465 CORBA::String_var myRefOnObject = myShape->GetID();
4466 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4467 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4468 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4469 aDataset->CreateOnDisk();
4470 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4471 aDataset->CloseOnDisk();
4477 std::string info = myImpl->FileInfoToString();
4478 if ( !info.empty() )
4480 aSize[ 0 ] = info.size();
4481 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4482 aDataset->CreateOnDisk();
4483 aDataset->WriteOnDisk( (char*) info.data() );
4484 aDataset->CloseOnDisk();
4487 // write applied hypotheses if exist
4488 SALOMEDS::SObject_wrap myHypBranch;
4489 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4490 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4491 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4493 if ( found && (shapeRefFound || !hasShape) ) {
4494 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4495 aGroup->CreateOnDisk();
4497 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4499 for ( ; it->More(); it->Next() ) {
4500 SALOMEDS::SObject_wrap mySObject = it->Value();
4501 SALOMEDS::SObject_wrap myRefOnHyp;
4502 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4504 // san - it is impossible to recover applied hypotheses
4505 // using their entries within Load() method,
4506 // for there are no AttributeIORs in the study when Load() is working.
4507 // Hence, it is better to store persistent IDs of hypotheses as references to them
4509 //string myRefOnObject = myRefOnHyp->GetID();
4510 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4511 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4512 int id = myStudyContext->findId( string( objStr.in() ) );
4513 //if ( myRefOnObject.length() > 0 ) {
4514 //aSize[ 0 ] = myRefOnObject.length() + 1;
4515 char hypName[ 30 ], hypId[ 30 ];
4516 sprintf( hypName, "Hyp %d", ++hypNb );
4517 sprintf( hypId, "%d", id );
4518 aSize[ 0 ] = strlen( hypId ) + 1;
4519 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4520 aDataset->CreateOnDisk();
4521 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4522 aDataset->WriteOnDisk( hypId );
4523 aDataset->CloseOnDisk();
4527 aGroup->CloseOnDisk();
4530 // write applied algorithms if exist
4531 SALOMEDS::SObject_wrap myAlgoBranch;
4532 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4533 myAlgoBranch.inout() );
4534 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4535 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4537 if ( found && (shapeRefFound || !hasShape)) {
4538 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4539 aGroup->CreateOnDisk();
4541 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4543 for ( ; it->More(); it->Next() ) {
4544 SALOMEDS::SObject_wrap mySObject = it->Value();
4545 SALOMEDS::SObject_wrap myRefOnAlgo;
4546 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4548 // san - it is impossible to recover applied algorithms
4549 // using their entries within Load() method,
4550 // for there are no AttributeIORs in the study when Load() is working.
4551 // Hence, it is better to store persistent IDs of algorithms as references to them
4553 //string myRefOnObject = myRefOnAlgo->GetID();
4554 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4555 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4556 int id = myStudyContext->findId( string( objStr.in() ) );
4557 //if ( myRefOnObject.length() > 0 ) {
4558 //aSize[ 0 ] = myRefOnObject.length() + 1;
4559 char algoName[ 30 ], algoId[ 30 ];
4560 sprintf( algoName, "Algo %d", ++algoNb );
4561 sprintf( algoId, "%d", id );
4562 aSize[ 0 ] = strlen( algoId ) + 1;
4563 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4564 aDataset->CreateOnDisk();
4565 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4566 aDataset->WriteOnDisk( algoId );
4567 aDataset->CloseOnDisk();
4571 aGroup->CloseOnDisk();
4574 // --> submesh objects sub-branches
4576 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4577 SALOMEDS::SObject_wrap mySubmeshBranch;
4578 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4580 if ( found ) // check if there is shape reference in submeshes
4582 bool hasShapeRef = false;
4583 SALOMEDS::ChildIterator_wrap itSM =
4584 aStudy->NewChildIterator( mySubmeshBranch );
4585 for ( ; itSM->More(); itSM->Next() ) {
4586 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4587 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4588 mySubRef->ReferencedObject( myShape.inout() );
4589 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4592 { // remove one submesh
4593 if ( shapeRefFound )
4594 { // unassign hypothesis
4595 SMESH::SMESH_subMesh_var mySubMesh =
4596 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4597 if ( !mySubMesh->_is_nil() ) {
4598 int shapeID = mySubMesh->GetId();
4599 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4600 const list<const SMESHDS_Hypothesis*>& hypList =
4601 mySMESHDSMesh->GetHypothesis( S );
4602 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4603 while ( hyp != hypList.end() ) {
4604 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4605 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4609 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4611 } // loop on submeshes of a type
4612 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4613 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4616 } // end check if there is shape reference in submeshes
4618 char name_meshgroup[ 30 ];
4619 if ( i == GetSubMeshOnVertexTag() )
4620 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4621 else if ( i == GetSubMeshOnEdgeTag() )
4622 strcpy( name_meshgroup, "SubMeshes On Edge" );
4623 else if ( i == GetSubMeshOnWireTag() )
4624 strcpy( name_meshgroup, "SubMeshes On Wire" );
4625 else if ( i == GetSubMeshOnFaceTag() )
4626 strcpy( name_meshgroup, "SubMeshes On Face" );
4627 else if ( i == GetSubMeshOnShellTag() )
4628 strcpy( name_meshgroup, "SubMeshes On Shell" );
4629 else if ( i == GetSubMeshOnSolidTag() )
4630 strcpy( name_meshgroup, "SubMeshes On Solid" );
4631 else if ( i == GetSubMeshOnCompoundTag() )
4632 strcpy( name_meshgroup, "SubMeshes On Compound" );
4634 // for each type of submeshes create container HDF group
4635 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4636 aGroup->CreateOnDisk();
4638 // iterator for all submeshes of given type
4639 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4640 for ( ; itSM->More(); itSM->Next() ) {
4641 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4642 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4643 if ( !CORBA::is_nil( anSubObject ))
4645 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4646 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4647 int subid = myStudyContext->findId( string( objStr.in() ) );
4649 // for each mesh open the HDF group basing on its id
4650 char submeshGrpName[ 30 ];
4651 sprintf( submeshGrpName, "SubMesh %d", subid );
4652 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4653 aSubGroup->CreateOnDisk();
4655 // write reference on a shape, already checked if it exists
4656 SALOMEDS::SObject_wrap mySubRef, myShape;
4657 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4658 mySubRef->ReferencedObject( myShape.inout() );
4659 string myRefOnObject = myShape->GetID();
4660 if ( myRefOnObject.length() > 0 ) {
4661 aSize[ 0 ] = myRefOnObject.length() + 1;
4662 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4663 aDataset->CreateOnDisk();
4664 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4665 aDataset->CloseOnDisk();
4668 // write applied hypotheses if exist
4669 SALOMEDS::SObject_wrap mySubHypBranch;
4670 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4671 mySubHypBranch.inout() );
4673 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4674 aSubSubGroup->CreateOnDisk();
4676 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4678 for ( ; it->More(); it->Next() ) {
4679 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4680 SALOMEDS::SObject_wrap myRefOnHyp;
4681 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4683 //string myRefOnObject = myRefOnHyp->GetID();
4684 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4685 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4686 int id = myStudyContext->findId( string( objStr.in() ) );
4687 //if ( myRefOnObject.length() > 0 ) {
4688 //aSize[ 0 ] = myRefOnObject.length() + 1;
4689 char hypName[ 30 ], hypId[ 30 ];
4690 sprintf( hypName, "Hyp %d", ++hypNb );
4691 sprintf( hypId, "%d", id );
4692 aSize[ 0 ] = strlen( hypId ) + 1;
4693 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4694 aDataset->CreateOnDisk();
4695 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4696 aDataset->WriteOnDisk( hypId );
4697 aDataset->CloseOnDisk();
4701 aSubSubGroup->CloseOnDisk();
4704 // write applied algorithms if exist
4705 SALOMEDS::SObject_wrap mySubAlgoBranch;
4706 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4707 mySubAlgoBranch.inout() );
4709 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4710 aSubSubGroup->CreateOnDisk();
4712 SALOMEDS::ChildIterator_wrap it =
4713 aStudy->NewChildIterator( mySubAlgoBranch );
4715 for ( ; it->More(); it->Next() ) {
4716 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4717 SALOMEDS::SObject_wrap myRefOnAlgo;
4718 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4720 //string myRefOnObject = myRefOnAlgo->GetID();
4721 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4722 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4723 int id = myStudyContext->findId( string( objStr.in() ) );
4724 //if ( myRefOnObject.length() > 0 ) {
4725 //aSize[ 0 ] = myRefOnObject.length() + 1;
4726 char algoName[ 30 ], algoId[ 30 ];
4727 sprintf( algoName, "Algo %d", ++algoNb );
4728 sprintf( algoId, "%d", id );
4729 aSize[ 0 ] = strlen( algoId ) + 1;
4730 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4731 aDataset->CreateOnDisk();
4732 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4733 aDataset->WriteOnDisk( algoId );
4734 aDataset->CloseOnDisk();
4738 aSubSubGroup->CloseOnDisk();
4740 // close submesh HDF group
4741 aSubGroup->CloseOnDisk();
4744 // close container of submeshes by type HDF group
4745 aGroup->CloseOnDisk();
4749 // store submesh order if any
4750 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4751 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4752 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4753 char order_list[ 30 ];
4754 strcpy( order_list, "Mesh Order" );
4755 // count number of submesh ids
4757 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4758 for ( ; idIt != theOrderIds.end(); idIt++ )
4759 nbIDs += (*idIt).size();
4760 // number of values = number of IDs +
4761 // number of lists (for separators) - 1
4762 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4763 idIt = theOrderIds.begin();
4764 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4765 const TListOfInt& idList = *idIt;
4766 if (idIt != theOrderIds.begin()) // not first list
4767 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4768 // dump submesh ids from current list
4769 TListOfInt::const_iterator id_smId = idList.begin();
4770 for( ; id_smId != idList.end(); id_smId++ )
4771 smIDs[ i++ ] = *id_smId;
4774 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4776 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4777 aDataset->CreateOnDisk();
4778 aDataset->WriteOnDisk( smIDs );
4779 aDataset->CloseOnDisk();
4783 if ( !theOrderIds.empty() && isNewOrederVersion )
4785 // convert ids to entries
4786 std::list< std::list< std::string > > orderEntryLists;
4787 for ( const TListOfInt& idList : theOrderIds )
4789 orderEntryLists.emplace_back();
4790 std::list< std::string > & entryList = orderEntryLists.back();
4791 for ( const int& id : idList )
4793 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4794 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4795 SALOMEDS::SObject_var so = ObjectToSObject( go );
4796 if ( !so->_is_nil() )
4798 CORBA::String_var entry = so->GetID();
4799 entryList.emplace_back( entry.in() );
4803 // convert orderEntryLists to string
4804 std::ostringstream ostream;
4805 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4806 std::string orderEntryString = ostream.str();
4809 aSize[ 0 ] = orderEntryString.size() + 1;
4810 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4811 aDataset->CreateOnDisk();
4812 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4813 aDataset->CloseOnDisk();
4816 // groups root sub-branch
4817 SALOMEDS::SObject_wrap myGroupsBranch;
4818 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4819 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4821 char name_group[ 30 ];
4822 if ( i == GetNodeGroupsTag() )
4823 strcpy( name_group, "Groups of Nodes" );
4824 else if ( i == GetEdgeGroupsTag() )
4825 strcpy( name_group, "Groups of Edges" );
4826 else if ( i == GetFaceGroupsTag() )
4827 strcpy( name_group, "Groups of Faces" );
4828 else if ( i == GetVolumeGroupsTag() )
4829 strcpy( name_group, "Groups of Volumes" );
4830 else if ( i == Get0DElementsGroupsTag() )
4831 strcpy( name_group, "Groups of 0D Elements" );
4832 else if ( i == GetBallElementsGroupsTag() )
4833 strcpy( name_group, "Groups of Balls" );
4835 aGroup = new HDFgroup( name_group, aTopGroup );
4836 aGroup->CreateOnDisk();
4838 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4839 for ( ; it->More(); it->Next() ) {
4840 SALOMEDS::SObject_wrap mySObject = it->Value();
4841 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4842 if ( !CORBA::is_nil( aSubObject ) ) {
4843 SMESH_GroupBase_i* myGroupImpl =
4844 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4847 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4851 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4852 int anId = myStudyContext->findId( string( objStr.in() ) );
4854 // For each group, create a dataset named "Group <group_persistent_id>"
4855 // and store the group's user name into it
4856 const char* grpName = aGrpBaseDS->GetStoreName();
4857 CORBA::String_var aUserName = myGroupImpl->GetName();
4858 aSize[ 0 ] = strlen( aUserName ) + 1;
4860 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4861 aDataset->CreateOnDisk();
4862 aDataset->WriteOnDisk( aUserName );
4863 aDataset->CloseOnDisk();
4866 // For each group, create a dataset named "Group <group_persistent_id> Color"
4867 // and store the group's color into it
4868 char grpColorName[ 30 ];
4869 sprintf( grpColorName, "ColorGroup %d", anId );
4870 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4872 anRGB[ 0 ] = aColor.R;
4873 anRGB[ 1 ] = aColor.G;
4874 anRGB[ 2 ] = aColor.B;
4876 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4877 aDataset->CreateOnDisk();
4878 aDataset->WriteOnDisk( anRGB );
4879 aDataset->CloseOnDisk();
4881 // Pass SMESHDS_Group to MED writer
4882 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4884 myWriter.AddGroup( aGrpDS );
4886 // write reference on a shape if exists
4887 SMESHDS_GroupOnGeom* aGeomGrp =
4888 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4890 SALOMEDS::SObject_wrap mySubRef, myShape;
4891 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4892 mySubRef->ReferencedObject( myShape.inout() ) &&
4893 !CORBA::is_nil( myShape->GetObject() ))
4895 CORBA::String_var myRefOnObject = myShape->GetID();
4896 if ( myRefOnObject.in()[0] ) {
4897 char aRefName[ 30 ];
4898 sprintf( aRefName, "Ref on shape %d", anId);
4899 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4900 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4901 aDataset->CreateOnDisk();
4902 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4903 aDataset->CloseOnDisk();
4906 else // shape ref is invalid:
4908 // save a group on geometry as ordinary group
4909 myWriter.AddGroup( aGeomGrp );
4912 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4913 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4915 std::string str = aFilterGrp_i->FilterToString();
4916 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4917 aSize[ 0 ] = str.length() + 1;
4918 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4919 aDataset->CreateOnDisk();
4920 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4921 aDataset->CloseOnDisk();
4925 aGroup->CloseOnDisk();
4929 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4931 // Flush current mesh information into MED file
4934 // save info on nb of elements
4935 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4937 // maybe a shape was deleted in the study
4938 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4939 TopoDS_Shape nullShape;
4940 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4943 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4948 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4949 aGroup->CreateOnDisk();
4951 // each element belongs to one or none submesh,
4952 // so for each node/element, we store a submesh ID
4954 // Store submesh IDs
4955 for ( int isNode = 0; isNode < 2; ++isNode )
4957 SMDS_ElemIteratorPtr eIt =
4958 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4959 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4962 std::vector<int> smIDs; smIDs.reserve( nbElems );
4963 while ( eIt->more() )
4964 if ( const SMDS_MeshElement* e = eIt->next())
4965 smIDs.push_back( e->getshapeId() );
4967 aSize[ 0 ] = nbElems;
4968 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4969 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4970 aDataset->CreateOnDisk();
4971 aDataset->WriteOnDisk( & smIDs[0] );
4972 aDataset->CloseOnDisk();
4975 aGroup->CloseOnDisk();
4977 // Store node positions on sub-shapes (SMDS_Position):
4978 // ----------------------------------------------------
4980 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4981 aGroup->CreateOnDisk();
4983 // in aGroup, create 5 datasets to contain:
4984 // "Nodes on Edges" - ID of node on edge
4985 // "Edge positions" - U parameter on node on edge
4986 // "Nodes on Faces" - ID of node on face
4987 // "Face U positions" - U parameter of node on face
4988 // "Face V positions" - V parameter of node on face
4990 // Find out nb of nodes on edges and faces
4991 // Collect corresponding sub-meshes
4992 int nbEdgeNodes = 0, nbFaceNodes = 0;
4993 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4994 // loop on SMESHDS_SubMesh'es
4995 while ( smIt->more() )
4997 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4998 if ( aSubMesh->IsComplexSubmesh() )
4999 continue; // submesh containing other submeshs
5000 smIdType nbNodes = aSubMesh->NbNodes();
5001 if ( nbNodes == 0 ) continue;
5003 int aShapeID = aSubMesh->GetID();
5004 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5006 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5007 // write only SMDS_FacePosition and SMDS_EdgePosition
5008 switch ( aShapeType ) {
5010 nbFaceNodes += nbNodes;
5011 aFaceSM.push_back( aSubMesh );
5014 nbEdgeNodes += nbNodes;
5015 aEdgeSM.push_back( aSubMesh );
5021 // Treat positions on edges or faces
5022 for ( int onFace = 0; onFace < 2; onFace++ )
5024 // Create arrays to store in datasets
5025 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5026 if (!nbNodes) continue;
5027 int* aNodeIDs = new int [ nbNodes ];
5028 double* aUPos = new double [ nbNodes ];
5029 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5032 // loop on sub-meshes
5033 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5034 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5035 for ( ; itSM != pListSM->end(); itSM++ )
5037 SMESHDS_SubMesh* aSubMesh = (*itSM);
5039 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5040 // loop on nodes in aSubMesh
5041 while ( itNode->more() )
5044 const SMDS_MeshNode* node = itNode->next();
5045 aNodeIDs [ iNode ] = node->GetID();
5048 const SMDS_PositionPtr pos = node->GetPosition();
5049 if ( onFace ) { // on FACE
5050 SMDS_FacePositionPtr fPos = pos;
5052 aUPos[ iNode ] = fPos->GetUParameter();
5053 aVPos[ iNode ] = fPos->GetVParameter();
5060 SMDS_EdgePositionPtr ePos = pos;
5062 aUPos[ iNode ] = ePos->GetUParameter();
5068 } // loop on nodes in aSubMesh
5069 } // loop on sub-meshes
5074 aSize[ 0 ] = nbNodes;
5076 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5077 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5078 aDataset->CreateOnDisk();
5079 aDataset->WriteOnDisk( aNodeIDs );
5080 aDataset->CloseOnDisk();
5083 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5084 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5085 aDataset->CreateOnDisk();
5086 aDataset->WriteOnDisk( aUPos );
5087 aDataset->CloseOnDisk();
5090 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5091 aDataset->CreateOnDisk();
5092 aDataset->WriteOnDisk( aVPos );
5093 aDataset->CloseOnDisk();
5098 if ( aVPos ) delete [] aVPos;
5100 } // treat positions on edges or faces
5102 // close "Node Positions" group
5103 aGroup->CloseOnDisk();
5105 } // if ( there are submeshes in SMESHDS_Mesh )
5108 // close mesh HDF group
5109 aTopGroup->CloseOnDisk();
5117 aFile->CloseOnDisk();
5120 // Convert temporary files to stream
5121 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5123 // Remove temporary files and directory
5125 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5127 return aStreamFile._retn();
5130 //=============================================================================
5132 * SMESH_Gen_i::SaveASCII
5134 * Save SMESH module's data in ASCII format
5136 //=============================================================================
5138 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5140 bool isMultiFile ) {
5141 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5142 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5143 return aStreamFile._retn();
5145 //after usual saving needs to encipher binary to text string
5146 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5147 int size = aStreamFile.in().length();
5148 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5149 for ( int i = 0; i < size; i++ )
5150 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5152 buffer[size * 3] = '\0';
5154 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5156 return anAsciiStreamFile._retn();
5159 //=============================================================================
5163 * Load SMESH module's data
5165 //=============================================================================
5167 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5168 const SALOMEDS::TMPFile& theStream,
5172 UpdateStudy(); // load geom data
5173 Kernel_Utils::Localizer loc;
5175 SALOMEDS::Study_var aStudy = getStudyServant();
5177 // Get temporary files location
5178 TCollection_AsciiString tmpDir =
5179 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5181 // Convert the stream into sequence of files to process
5182 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5185 TCollection_AsciiString aStudyName( "" );
5186 if ( isMultiFile ) {
5187 CORBA::WString_var url = aStudy->URL();
5188 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5190 // Set names of temporary files
5191 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5192 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5196 HDFdataset* aDataset;
5197 HDFgroup* aTopGroup;
5199 HDFgroup* aSubGroup;
5200 HDFgroup* aSubSubGroup;
5203 // ---> open HDF file
5204 aFile = new HDFfile( (char*) filename.ToCString() );
5206 aFile->OpenOnDisk( HDF_RDONLY );
5208 catch ( HDFexception ) {
5209 INFOS( "Load(): " << filename << " not found!" );
5213 TPythonDump pd(this); // prevent dump during loading
5215 // For PAL13473 ("Repetitive mesh") implementation.
5216 // New dependencies between SMESH objects are established:
5217 // now hypotheses can refer to meshes, shapes and other hypotheses.
5218 // To keep data consistent, the following order of data restoration
5220 // 1. Create hypotheses
5221 // 2. Create all meshes
5222 // 3. Load hypotheses' data
5225 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5226 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5227 list< SMESH::Filter_var > filters;
5229 // get total number of top-level groups
5230 int aNbGroups = aFile->nInternalObjects();
5231 if ( aNbGroups > 0 ) {
5232 // --> in first turn we should read&create hypotheses
5233 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5234 // open hypotheses root HDF group
5235 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5236 aTopGroup->OpenOnDisk();
5238 // get number of hypotheses
5239 int aNbObjects = aTopGroup->nInternalObjects();
5240 for ( int j = 0; j < aNbObjects; j++ ) {
5241 // try to identify hypothesis
5242 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5243 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5245 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5246 // open hypothesis group
5247 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5248 aGroup->OpenOnDisk();
5250 // --> get hypothesis id
5251 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5256 // get number of datasets
5257 int aNbSubObjects = aGroup->nInternalObjects();
5258 for ( int k = 0; k < aNbSubObjects; k++ ) {
5260 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5261 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5262 // --> get hypothesis name
5263 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5264 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5265 aDataset->OpenOnDisk();
5266 size = aDataset->GetSize();
5267 char* hypname_str = new char[ size ];
5268 aDataset->ReadFromDisk( hypname_str );
5269 hypname = string( hypname_str );
5270 delete [] hypname_str;
5271 aDataset->CloseOnDisk();
5273 // --> get hypothesis plugin library name
5274 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5275 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5276 aDataset->OpenOnDisk();
5277 size = aDataset->GetSize();
5278 char* libname_str = new char[ size ];
5279 aDataset->ReadFromDisk( libname_str );
5280 if(MYDEBUG) SCRUTE( libname_str );
5281 libname = string( libname_str );
5282 delete [] libname_str;
5283 aDataset->CloseOnDisk();
5285 // --> get hypothesis data
5286 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5287 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5288 aDataset->OpenOnDisk();
5289 size = aDataset->GetSize();
5290 char* hypdata_str = new char[ size ];
5291 aDataset->ReadFromDisk( hypdata_str );
5292 hypdata = string( hypdata_str );
5293 delete [] hypdata_str;
5294 aDataset->CloseOnDisk();
5297 // close hypothesis HDF group
5298 aGroup->CloseOnDisk();
5300 // --> restore hypothesis from data
5301 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5302 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5303 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5304 SMESH::SMESH_Hypothesis_var myHyp;
5306 try { // protect persistence mechanism against exceptions
5307 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5310 INFOS( "Exception during hypothesis creation" );
5313 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5315 // myImpl->LoadFrom( hypdata.c_str() );
5316 hypDataList.push_back( make_pair( myImpl, hypdata ));
5317 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5318 int newId = myStudyContext->findId( iorString.in() );
5319 myStudyContext->mapOldToNew( id, newId );
5322 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5326 // close hypotheses root HDF group
5327 aTopGroup->CloseOnDisk();
5331 // --> then we should read&create algorithms
5332 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5333 // open algorithms root HDF group
5334 aTopGroup = new HDFgroup( "Algorithms", aFile );
5335 aTopGroup->OpenOnDisk();
5337 // get number of algorithms
5338 int aNbObjects = aTopGroup->nInternalObjects();
5339 for ( int j = 0; j < aNbObjects; j++ ) {
5340 // try to identify algorithm
5341 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5342 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5344 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5345 // open algorithm group
5346 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5347 aGroup->OpenOnDisk();
5349 // --> get algorithm id
5350 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5355 // get number of datasets
5356 int aNbSubObjects = aGroup->nInternalObjects();
5357 for ( int k = 0; k < aNbSubObjects; k++ ) {
5359 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5360 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5361 // --> get algorithm name
5362 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5363 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5364 aDataset->OpenOnDisk();
5365 size = aDataset->GetSize();
5366 char* hypname_str = new char[ size ];
5367 aDataset->ReadFromDisk( hypname_str );
5368 hypname = string( hypname_str );
5369 delete [] hypname_str;
5370 aDataset->CloseOnDisk();
5372 // --> get algorithm plugin library name
5373 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5374 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5375 aDataset->OpenOnDisk();
5376 size = aDataset->GetSize();
5377 char* libname_str = new char[ size ];
5378 aDataset->ReadFromDisk( libname_str );
5379 if(MYDEBUG) SCRUTE( libname_str );
5380 libname = string( libname_str );
5381 delete [] libname_str;
5382 aDataset->CloseOnDisk();
5384 // --> get algorithm data
5385 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5386 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5387 aDataset->OpenOnDisk();
5388 size = aDataset->GetSize();
5389 char* hypdata_str = new char[ size ];
5390 aDataset->ReadFromDisk( hypdata_str );
5391 if(MYDEBUG) SCRUTE( hypdata_str );
5392 hypdata = string( hypdata_str );
5393 delete [] hypdata_str;
5394 aDataset->CloseOnDisk();
5397 // close algorithm HDF group
5398 aGroup->CloseOnDisk();
5400 // --> restore algorithm from data
5401 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5402 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5403 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5404 SMESH::SMESH_Hypothesis_var myHyp;
5406 try { // protect persistence mechanism against exceptions
5407 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5409 catch( SALOME::SALOME_Exception& ex )
5411 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5414 INFOS( "Exception during hypothesis creation" );
5417 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5419 //myImpl->LoadFrom( hypdata.c_str() );
5420 hypDataList.push_back( make_pair( myImpl, hypdata ));
5421 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5422 int newId = myStudyContext->findId( iorString.in() );
5423 myStudyContext->mapOldToNew( id, newId );
5426 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5430 // close algorithms root HDF group
5431 aTopGroup->CloseOnDisk();
5435 // --> the rest groups should be meshes
5436 for ( int i = 0; i < aNbGroups; i++ ) {
5437 // identify next group
5438 char meshName[ HDF_NAME_MAX_LEN+1 ];
5439 aFile->InternalObjectIndentify( i, meshName );
5441 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5443 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5447 // open mesh HDF group
5448 aTopGroup = new HDFgroup( meshName, aFile );
5449 aTopGroup->OpenOnDisk();
5451 // get number of child HDF objects
5452 int aNbObjects = aTopGroup->nInternalObjects();
5453 if ( aNbObjects > 0 ) {
5455 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5456 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5457 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5458 if ( !myNewMeshImpl )
5460 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5462 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5463 int newId = myStudyContext->findId( iorString.in() );
5464 myStudyContext->mapOldToNew( id, newId );
5467 // try to read and set auto color flag
5468 char aMeshAutoColorName[ 30 ];
5469 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5470 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5472 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5473 aDataset->OpenOnDisk();
5474 size = aDataset->GetSize();
5475 int* anAutoColor = new int[ size ];
5476 aDataset->ReadFromDisk( anAutoColor );
5477 aDataset->CloseOnDisk();
5478 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5479 delete [] anAutoColor;
5482 // try to read and set reference to shape
5483 GEOM::GEOM_Object_var aShapeObject;
5484 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5485 // load mesh "Ref on shape" - it's an entry to SObject
5486 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5487 aDataset->OpenOnDisk();
5488 size = aDataset->GetSize();
5489 char* refFromFile = new char[ size ];
5490 aDataset->ReadFromDisk( refFromFile );
5491 aDataset->CloseOnDisk();
5492 if ( strlen( refFromFile ) > 0 ) {
5493 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5494 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5495 if ( !CORBA::is_nil( shapeObject ) ) {
5496 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5497 if ( !aShapeObject->_is_nil() )
5498 myNewMeshImpl->SetShape( aShapeObject );
5501 delete [] refFromFile;
5504 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5505 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5507 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5508 aDataset->OpenOnDisk();
5509 size = aDataset->GetSize();
5510 int* meshPersistentId = new int[ size ];
5511 aDataset->ReadFromDisk( meshPersistentId );
5512 aDataset->CloseOnDisk();
5513 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5514 delete [] meshPersistentId;
5517 // Restore SMESH_Mesh_i::_mainShapeTick
5518 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5520 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5521 aDataset->OpenOnDisk();
5522 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5523 aDataset->ReadFromDisk( shapeTick );
5524 aDataset->CloseOnDisk();
5527 // Restore file info
5528 if ( aTopGroup->ExistInternalObject( "file info" ))
5530 aDataset = new HDFdataset( "file info", aTopGroup );
5531 aDataset->OpenOnDisk();
5532 size = aDataset->GetSize();
5533 std::string info( size, ' ');
5534 aDataset->ReadFromDisk( (char*) info.data() );
5535 aDataset->CloseOnDisk();
5536 myNewMeshImpl->FileInfoFromString( info );
5542 // As all object that can be referred by hypothesis are created,
5543 // we can restore hypothesis data
5545 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5546 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5548 SMESH_Hypothesis_i* hyp = hyp_data->first;
5549 string & data = hyp_data->second;
5550 hyp->LoadFrom( data.c_str() );
5553 // Restore the rest mesh data
5555 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5556 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5558 aTopGroup = meshi_group->second;
5559 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5561 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5562 bool hasData = false;
5565 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5566 int newId = myStudyContext->findId( iorString.in() );
5567 int meshOldId = myStudyContext->getOldId( newId );
5569 // try to find mesh data dataset
5570 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5571 // load mesh "has data" flag
5572 aDataset = new HDFdataset( "Has data", aTopGroup );
5573 aDataset->OpenOnDisk();
5574 size = aDataset->GetSize();
5575 char* strHasData = new char[ size ];
5576 aDataset->ReadFromDisk( strHasData );
5577 aDataset->CloseOnDisk();
5578 if ( strcmp( strHasData, "1") == 0 ) {
5581 delete [] strHasData;
5584 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5585 // nodes and elements are not yet put into sub-meshes)
5586 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5587 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5588 aGroup->OpenOnDisk();
5589 // get number of applied algorithms
5590 int aNbSubObjects = aGroup->nInternalObjects();
5591 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5592 for ( int j = 0; j < aNbSubObjects; j++ ) {
5593 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5594 aGroup->InternalObjectIndentify( j, name_dataset );
5595 // check if it is an algorithm
5596 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5597 aDataset = new HDFdataset( name_dataset, aGroup );
5598 aDataset->OpenOnDisk();
5599 size = aDataset->GetSize();
5600 char* refFromFile = new char[ size ];
5601 aDataset->ReadFromDisk( refFromFile );
5602 aDataset->CloseOnDisk();
5603 // san - it is impossible to recover applied algorithms using their entries within Load() method
5604 int id = atoi( refFromFile );
5605 delete [] refFromFile;
5606 string anIOR = myStudyContext->getIORbyOldId( id );
5607 if ( !anIOR.empty() ) {
5608 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5609 if ( !CORBA::is_nil( hypObject ) ) {
5610 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5611 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5612 || !myNewMeshImpl->HasShapeToMesh()) )
5613 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5618 aGroup->CloseOnDisk();
5621 // try to get applied hypotheses
5622 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5623 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5624 aGroup->OpenOnDisk();
5625 // get number of applied hypotheses
5626 int aNbSubObjects = aGroup->nInternalObjects();
5627 for ( int j = 0; j < aNbSubObjects; j++ ) {
5628 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5629 aGroup->InternalObjectIndentify( j, name_dataset );
5630 // check if it is a hypothesis
5631 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5632 aDataset = new HDFdataset( name_dataset, aGroup );
5633 aDataset->OpenOnDisk();
5634 size = aDataset->GetSize();
5635 char* refFromFile = new char[ size ];
5636 aDataset->ReadFromDisk( refFromFile );
5637 aDataset->CloseOnDisk();
5638 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5639 int id = atoi( refFromFile );
5640 delete [] refFromFile;
5641 string anIOR = myStudyContext->getIORbyOldId( id );
5642 if ( !anIOR.empty() ) {
5643 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5644 if ( !CORBA::is_nil( hypObject ) ) {
5645 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5646 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5647 || !myNewMeshImpl->HasShapeToMesh()) )
5648 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5653 aGroup->CloseOnDisk();
5656 // --> try to find SUB-MESHES containers for each type of submesh
5657 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5658 const char* name_meshgroup = 0;
5659 if ( j == GetSubMeshOnVertexTag() )
5660 name_meshgroup = "SubMeshes On Vertex";
5661 else if ( j == GetSubMeshOnEdgeTag() )
5662 name_meshgroup = "SubMeshes On Edge";
5663 else if ( j == GetSubMeshOnWireTag() )
5664 name_meshgroup = "SubMeshes On Wire";
5665 else if ( j == GetSubMeshOnFaceTag() )
5666 name_meshgroup = "SubMeshes On Face";
5667 else if ( j == GetSubMeshOnShellTag() )
5668 name_meshgroup = "SubMeshes On Shell";
5669 else if ( j == GetSubMeshOnSolidTag() )
5670 name_meshgroup = "SubMeshes On Solid";
5671 else if ( j == GetSubMeshOnCompoundTag() )
5672 name_meshgroup = "SubMeshes On Compound";
5674 // try to get submeshes container HDF group
5675 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5676 // open submeshes containers HDF group
5677 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5678 aGroup->OpenOnDisk();
5680 // get number of submeshes
5681 int aNbSubMeshes = aGroup->nInternalObjects();
5682 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5684 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5685 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5686 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5687 // --> get submesh id
5688 int subid = atoi( name_submeshgroup + 7 );
5691 // open submesh HDF group
5692 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5693 aSubGroup->OpenOnDisk();
5695 // try to read and set reference to subshape
5696 GEOM::GEOM_Object_var aSubShapeObject;
5697 SMESH::SMESH_subMesh_var aSubMesh;
5699 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5700 // load submesh "Ref on shape" - it's an entry to SObject
5701 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5702 aDataset->OpenOnDisk();
5703 size = aDataset->GetSize();
5704 char* refFromFile = new char[ size ];
5705 aDataset->ReadFromDisk( refFromFile );
5706 aDataset->CloseOnDisk();
5707 if ( strlen( refFromFile ) > 0 ) {
5708 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5709 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5710 if ( !CORBA::is_nil( subShapeObject ) ) {
5711 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5712 if ( !aSubShapeObject->_is_nil() )
5713 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5714 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5715 if ( aSubMesh->_is_nil() )
5717 string iorSubString = GetORB()->object_to_string( aSubMesh );
5718 int newSubId = myStudyContext->findId( iorSubString );
5719 myStudyContext->mapOldToNew( subid, newSubId );
5722 delete [] refFromFile;
5725 if ( aSubMesh->_is_nil() )
5728 // try to get applied algorithms
5729 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5730 // open "applied algorithms" HDF group
5731 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5732 aSubSubGroup->OpenOnDisk();
5733 // get number of applied algorithms
5734 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5735 for ( int l = 0; l < aNbSubObjects; l++ ) {
5736 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5737 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5738 // check if it is an algorithm
5739 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5740 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5741 aDataset->OpenOnDisk();
5742 size = aDataset->GetSize();
5743 char* refFromFile = new char[ size ];
5744 aDataset->ReadFromDisk( refFromFile );
5745 aDataset->CloseOnDisk();
5747 int id = atoi( refFromFile );
5748 string anIOR = myStudyContext->getIORbyOldId( id );
5749 if ( !anIOR.empty() ) {
5750 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5751 if ( !CORBA::is_nil( hypObject ) ) {
5752 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5753 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5754 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5757 delete [] refFromFile;
5760 // close "applied algorithms" HDF group
5761 aSubSubGroup->CloseOnDisk();
5764 // try to get applied hypotheses
5765 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5766 // open "applied hypotheses" HDF group
5767 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5768 aSubSubGroup->OpenOnDisk();
5769 // get number of applied hypotheses
5770 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5771 for ( int l = 0; l < aNbSubObjects; l++ ) {
5772 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5773 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5774 // check if it is a hypothesis
5775 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5776 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5777 aDataset->OpenOnDisk();
5778 size = aDataset->GetSize();
5779 char* refFromFile = new char[ size ];
5780 aDataset->ReadFromDisk( refFromFile );
5781 aDataset->CloseOnDisk();
5783 int id = atoi( refFromFile );
5784 string anIOR = myStudyContext->getIORbyOldId( id );
5785 if ( !anIOR.empty() ) {
5786 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5787 if ( !CORBA::is_nil( hypObject ) ) {
5788 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5789 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5790 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5793 delete [] refFromFile;
5796 // close "APPLIED HYPOTHESES" hdf group
5797 aSubSubGroup->CloseOnDisk();
5800 // close SUB-MESH hdf group
5801 aSubGroup->CloseOnDisk();
5804 // close SUB-MESHES containers hdf group
5805 aGroup->CloseOnDisk();
5809 // try to get GROUPS
5810 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5811 char name_group[ 30 ];
5812 if ( ii == GetNodeGroupsTag() )
5813 strcpy( name_group, "Groups of Nodes" );
5814 else if ( ii == GetEdgeGroupsTag() )
5815 strcpy( name_group, "Groups of Edges" );
5816 else if ( ii == GetFaceGroupsTag() )
5817 strcpy( name_group, "Groups of Faces" );
5818 else if ( ii == GetVolumeGroupsTag() )
5819 strcpy( name_group, "Groups of Volumes" );
5820 else if ( ii == Get0DElementsGroupsTag() )
5821 strcpy( name_group, "Groups of 0D Elements" );
5822 else if ( ii == GetBallElementsGroupsTag() )
5823 strcpy( name_group, "Groups of Balls" );
5825 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5826 aGroup = new HDFgroup( name_group, aTopGroup );
5827 aGroup->OpenOnDisk();
5828 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5829 // within aGroup->ExistInternalObject( name )
5830 std::vector< std::string > subNames;
5831 TColStd_MapOfAsciiString mapOfNames;
5832 aGroup->GetAllObjects( subNames );
5833 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5834 mapOfNames.Add( subNames[ iN ].c_str() );
5836 for ( size_t j = 0; j < subNames.size(); j++ ) {
5837 const std::string& name_dataset = subNames[ j ];
5838 // check if it is a group
5839 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5842 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5845 int groupID = -1; // group local ID (also persistent)
5847 groupID = atoi( endptr + 1 );
5848 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5849 aDataset->OpenOnDisk();
5851 // Retrieve actual group name
5852 size = aDataset->GetSize();
5853 char* nameFromFile = new char[ size ];
5854 aDataset->ReadFromDisk( nameFromFile );
5855 aDataset->CloseOnDisk();
5857 // Try to find a shape reference
5858 TopoDS_Shape aShape;
5859 char aRefName[ 30 ];
5860 sprintf( aRefName, "Ref on shape %d", subid);
5861 if ( mapOfNames.Contains( aRefName ))
5863 // load mesh "Ref on shape" - it's an entry to SObject
5864 aDataset = new HDFdataset( aRefName, aGroup );
5865 aDataset->OpenOnDisk();
5866 size = aDataset->GetSize();
5867 char* refFromFile = new char[ size ];
5868 aDataset->ReadFromDisk( refFromFile );
5869 aDataset->CloseOnDisk();
5870 if ( strlen( refFromFile ) > 0 ) {
5871 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5872 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5873 if ( !CORBA::is_nil( shapeObject ) ) {
5874 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5875 if ( !aShapeObject->_is_nil() )
5876 aShape = GeomObjectToShape( aShapeObject );
5879 delete [] refFromFile;
5881 // Try to read a filter of SMESH_GroupOnFilter
5882 SMESH::Filter_var filter;
5883 SMESH_PredicatePtr predicate;
5884 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5885 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5887 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5888 aDataset->OpenOnDisk();
5889 size = aDataset->GetSize();
5890 char* persistStr = new char[ size ];
5891 aDataset->ReadFromDisk( persistStr );
5892 aDataset->CloseOnDisk();
5893 if ( strlen( persistStr ) > 0 ) {
5894 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5895 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5896 filters.push_back( filter );
5898 delete [] persistStr;
5901 // Create group servant
5902 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5903 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5904 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5905 delete [] nameFromFile;
5906 // Obtain a SMESHDS_Group object
5907 if ( aNewGroup->_is_nil() )
5910 string iorSubString = GetORB()->object_to_string( aNewGroup );
5911 int newSubId = myStudyContext->findId( iorSubString );
5912 myStudyContext->mapOldToNew( subid, newSubId );
5914 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5918 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5919 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5921 aFilterGroup->SetFilter( filter );
5922 filter->UnRegister();
5924 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5925 if ( !aGroupBaseDS )
5928 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5931 // Read color of the group
5932 char aGroupColorName[ 30 ];
5933 sprintf( aGroupColorName, "ColorGroup %d", subid);
5934 if ( mapOfNames.Contains( aGroupColorName ))
5936 aDataset = new HDFdataset( aGroupColorName, aGroup );
5937 aDataset->OpenOnDisk();
5938 size = aDataset->GetSize();
5939 double* anRGB = new double[ size ];
5940 aDataset->ReadFromDisk( anRGB );
5941 aDataset->CloseOnDisk();
5942 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5943 aGroupBaseDS->SetColor( aColor );
5948 aGroup->CloseOnDisk();
5952 // instead of reading mesh data, we read only brief information of all
5953 // objects: mesh, groups, sub-meshes (issue 0021208)
5956 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5957 meshfile.ToCString(), filename.ToCString(),
5961 // read Sub-Mesh ORDER if any
5962 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5963 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5964 aDataset->OpenOnDisk();
5965 size = aDataset->GetSize();
5966 int* smIDs = new int[ size ];
5967 aDataset->ReadFromDisk( smIDs );
5968 aDataset->CloseOnDisk();
5969 TListOfListOfInt anOrderIds;
5970 anOrderIds.push_back( TListOfInt() );
5971 for ( int i = 0; i < size; i++ )
5972 if ( smIDs[ i ] < 0 ) // is separator
5973 anOrderIds.push_back( TListOfInt() );
5975 anOrderIds.back().push_back(smIDs[ i ]);
5977 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5980 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5982 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5983 aDataset->OpenOnDisk();
5984 size = aDataset->GetSize();
5985 std::string dataString; dataString.resize( size );
5986 aDataset->ReadFromDisk((char*) dataString.data() );
5987 aDataset->CloseOnDisk();
5989 std::istringstream istream( dataString.data() );
5990 boost::archive::text_iarchive archive( istream );
5991 std::list< std::list< std::string > > orderEntryLists;
5993 archive >> orderEntryLists;
5997 TListOfListOfInt anOrderIds;
5998 for ( const std::list< std::string >& entryList : orderEntryLists )
6000 anOrderIds.emplace_back();
6001 for ( const std::string & entry : entryList )
6003 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6004 TopoDS_Shape shape = GeomObjectToShape( go );
6005 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6006 anOrderIds.back().emplace_back( sm->GetId() );
6009 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6013 // update hyps needing full mesh data restored (issue 20918)
6014 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6016 SMESH_Hypothesis_i* hyp = hyp_data->first;
6017 hyp->UpdateAsMeshesRestored();
6020 // notify algos on completed restoration to set sub-mesh event listeners
6021 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6023 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6024 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6026 TopoDS_Shape myLocShape;
6027 if(myLocMesh.HasShapeToMesh())
6028 myLocShape = myLocMesh.GetShapeToMesh();
6030 myLocShape = SMESH_Mesh::PseudoShape();
6032 myLocMesh.GetSubMesh(myLocShape)->
6033 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6036 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6037 list< SMESH::Filter_var >::iterator f = filters.begin();
6038 for ( ; f != filters.end(); ++f )
6039 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6040 fi->FindBaseObjects();
6045 aTopGroup->CloseOnDisk();
6048 aFile->CloseOnDisk();
6051 // Remove temporary files created from the stream
6054 SMESH_File meshFile( meshfile.ToCString() );
6055 if ( !meshFile ) // no meshfile exists
6057 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6061 Engines::Container_var container = GetContainerRef();
6062 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6064 container_i->registerTemporaryFile( filename.ToCString() );
6065 container_i->registerTemporaryFile( meshfile.ToCString() );
6066 container_i->registerTemporaryFile( tmpDir.ToCString() );
6071 // creation of tree nodes for all data objects in the study
6072 // to support tree representation customization and drag-n-drop:
6073 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6074 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6075 useCaseBuilder->SetRootCurrent();
6076 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6077 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6078 for (it->InitEx(true); it->More(); it->Next()) {
6079 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6086 //=============================================================================
6088 * SMESH_Gen_i::LoadASCII
6090 * Load SMESH module's data in ASCII format
6092 //=============================================================================
6094 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6095 const SALOMEDS::TMPFile& theStream,
6097 bool isMultiFile ) {
6098 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6099 return Load( theComponent, theStream, theURL, isMultiFile );
6101 //before call main ::Load method it's need for decipher text format to
6102 //binary ( "|xx" => x' )
6103 int size = theStream.length();
6104 if ( int((size / 3 )*3) != size ) //error size of buffer
6107 int real_size = int(size / 3);
6109 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6112 unsigned int c = -1;
6113 for ( int i = 0; i < real_size; i++ )
6115 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6116 sscanf( tmp, "%x", &c );
6117 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6120 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6122 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6125 //=============================================================================
6127 * SMESH_Gen_i::Close
6129 * Clears study-connected data when it is closed
6131 //=============================================================================
6133 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6135 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6137 // Clear study contexts data
6138 myStudyContext->Clear();
6140 // remove the tmp files meshes are loaded from
6141 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6143 // Clean trace of API methods calls
6149 //=============================================================================
6151 * SMESH_Gen_i::ComponentDataType
6153 * Get component data type
6155 //=============================================================================
6157 char* SMESH_Gen_i::ComponentDataType()
6159 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6160 return CORBA::string_dup( "SMESH" );
6164 //=============================================================================
6166 * SMESH_Gen_i::IORToLocalPersistentID
6168 * Transform data from transient form to persistent
6170 //=============================================================================
6172 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6173 const char* IORString,
6174 CORBA::Boolean /*isMultiFile*/,
6175 CORBA::Boolean /*isASCII*/ )
6177 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6179 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6180 int anId = myStudyContext->findId( IORString );
6182 if(MYDEBUG) MESSAGE( "VSR " << anId )
6184 sprintf( strId, "%d", anId );
6185 return CORBA::string_dup( strId );
6188 return CORBA::string_dup( "" );
6191 //=============================================================================
6193 * SMESH_Gen_i::LocalPersistentIDToIOR
6195 * Transform data from persistent form to transient
6197 //=============================================================================
6199 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6200 const char* aLocalPersistentID,
6201 CORBA::Boolean /*isMultiFile*/,
6202 CORBA::Boolean /*isASCII*/ )
6204 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6206 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6207 int anId = atoi( aLocalPersistentID );
6208 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6210 return CORBA::string_dup( "" );
6213 //=======================================================================
6214 //function : RegisterObject
6216 //=======================================================================
6218 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6220 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6221 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6222 return myStudyContext->addObject( string( iorString.in() ) );
6227 //================================================================================
6229 * \brief Return id of registered object
6230 * \param theObject - the Object
6231 * \retval int - Object id
6233 //================================================================================
6235 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6237 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6238 string iorString = GetORB()->object_to_string( theObject );
6239 return myStudyContext->findId( iorString );
6244 //=============================================================================
6246 * SMESH_Gen_i::SetName
6248 * Set a new object name
6250 //=============================================================================
6252 void SMESH_Gen_i::SetName(const char* theIOR,
6253 const char* theName)
6255 if ( theIOR && strcmp( theIOR, "" ) ) {
6256 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6257 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6258 if ( !aSO->_is_nil() ) {
6259 SetName( aSO, theName );
6264 // Version information
6265 char* SMESH_Gen_i::getVersion()
6267 #if SMESH_DEVELOPMENT
6268 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6270 return CORBA::string_dup(SMESH_VERSION_STR);
6274 //=================================================================================
6275 // function : Move()
6276 // purpose : Moves objects to the specified position.
6277 // Is used in the drag-n-drop functionality.
6278 //=================================================================================
6280 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6281 SALOMEDS::SObject_ptr where,
6284 if ( CORBA::is_nil( where ) ) return;
6286 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6287 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6288 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6289 std::string dataType = father->ComponentDataType();
6290 if ( dataType != "SMESH" ) return; // not a SMESH component
6292 SALOMEDS::SObject_var objAfter;
6293 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6294 // insert at given row -> find insertion position
6295 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6297 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6298 if ( i == row && useCaseIt->More() ) {
6299 objAfter = useCaseIt->Value();
6303 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6304 SALOMEDS::SObject_var sobj = what[i];
6305 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6306 // insert the object to the use case tree
6307 if ( !CORBA::is_nil( objAfter ) )
6308 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6310 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6313 //================================================================================
6315 * \brief Returns true if algorithm can be used to mesh a given geometry
6316 * \param [in] theAlgoType - the algorithm type
6317 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6318 * \param [in] theGeomObject - the geometry to mesh
6319 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6320 * else, returns \c True if at least one shape is meshable
6321 * \return CORBA::Boolean - can or can't
6323 //================================================================================
6325 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6326 const char* theLibName,
6327 GEOM::GEOM_Object_ptr theGeomObject,
6328 CORBA::Boolean toCheckAll)
6332 std::string aPlatformLibName;
6333 GenericHypothesisCreator_i* aCreator =
6334 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6337 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6338 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6339 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6346 SMESH_CATCH( SMESH::doNothing );
6349 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6354 //================================================================================
6356 * \brief Collect indices of elements, which are located inside the sphere
6358 //================================================================================
6360 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6361 SMESH::ElementType theElemType,
6367 SMESH::long_array_var aResult = new SMESH::long_array();
6368 if ( meshPart->_is_nil() )
6369 return aResult._retn();
6371 // 1. Create geometrical object
6372 gp_Pnt aP( theX, theY, theZ );
6373 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6375 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6377 if ( lst.size() > 0 ) {
6378 aResult->length( lst.size() );
6379 for ( size_t i = 0; i < lst.size(); i++ ) {
6380 aResult[i] = lst[i];
6383 return aResult._retn();
6386 //================================================================================
6388 * \brief Collect indices of elements, which are located inside the box
6390 //================================================================================
6392 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6393 SMESH::ElementType theElemType,
6394 CORBA::Double theX1,
6395 CORBA::Double theY1,
6396 CORBA::Double theZ1,
6397 CORBA::Double theX2,
6398 CORBA::Double theY2,
6399 CORBA::Double theZ2)
6401 SMESH::long_array_var aResult = new SMESH::long_array();
6402 if( meshPart->_is_nil() )
6403 return aResult._retn();
6405 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6406 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6408 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6410 if( lst.size() > 0 ) {
6411 aResult->length( lst.size() );
6412 for ( size_t i = 0; i < lst.size(); i++ ) {
6413 aResult[i] = lst[i];
6416 return aResult._retn();
6419 //================================================================================
6421 * \brief Collect indices of elements, which are located inside the cylinder
6423 //================================================================================
6425 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6426 SMESH::ElementType theElemType,
6430 CORBA::Double theDX,
6431 CORBA::Double theDY,
6432 CORBA::Double theDZ,
6434 CORBA::Double theR )
6436 SMESH::long_array_var aResult = new SMESH::long_array();
6437 if( meshPart->_is_nil() )
6438 return aResult._retn();
6440 gp_Pnt aP( theX, theY, theZ );
6441 gp_Vec aV( theDX, theDY, theDZ );
6442 gp_Ax2 anAxes (aP, aV);
6444 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6446 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6448 if( lst.size() > 0 ) {
6449 aResult->length( lst.size() );
6450 for ( size_t i = 0; i < lst.size(); i++ ) {
6451 aResult[i] = lst[i];
6454 return aResult._retn();
6457 //================================================================================
6459 * \brief Collect indices of elements, which are located inside the geom object
6461 //================================================================================
6463 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6464 SMESH::ElementType theElemType,
6465 GEOM::GEOM_Object_ptr theGeom,
6466 CORBA::Double theTolerance )
6468 SMESH::long_array_var aResult = new SMESH::long_array();
6469 if( meshPart->_is_nil() || theGeom->_is_nil() )
6470 return aResult._retn();
6472 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6474 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6476 if( lst.size() > 0 ) {
6477 aResult->length( lst.size() );
6478 for ( size_t i = 0; i < lst.size(); i++ ) {
6479 aResult[i] = lst[i];
6482 return aResult._retn();
6485 //================================================================================
6487 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6489 //================================================================================
6491 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6492 SMESH::ElementType theElemType,
6493 const TopoDS_Shape& theShape,
6494 double* theTolerance) {
6496 std::vector<long> res;
6497 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6499 if ( mesh->_is_nil() )
6502 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6506 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6511 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6512 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6513 anElementsOnShape->SetAllNodes( true );
6514 anElementsOnShape->SetMesh( meshDS );
6515 anElementsOnShape->SetShape( theShape, aType );
6518 anElementsOnShape->SetTolerance(*theTolerance);
6520 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6521 if ( !msource->_is_nil() ) { // Mesh case
6522 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6524 while ( elemIt->more() ) {
6525 const SMDS_MeshElement* anElem = elemIt->next();
6526 long anId = anElem->GetID();
6527 if ( anElementsOnShape->IsSatisfy( anId ) )
6528 res.push_back( anId );
6532 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6533 if ( !gsource->_is_nil() ) {
6534 if(theElemType == SMESH::NODE) {
6535 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6536 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6537 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6538 long anId = node->GetID();
6539 if ( anElementsOnShape->IsSatisfy( anId ) )
6540 res.push_back( anId );
6543 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6544 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6545 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6546 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6547 long anId = elem->GetID();
6548 if ( anElementsOnShape->IsSatisfy( anId ) )
6549 res.push_back( anId );
6554 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6555 if ( !smsource->_is_nil() ) {
6556 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6557 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6558 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6560 long anId = elem->GetID();
6561 if ( anElementsOnShape->IsSatisfy( anId ) )
6562 res.push_back( anId );