1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
161 CORBA::ORB_var SMESH_Gen_i::myOrb;
162 PortableServer::POA_var SMESH_Gen_i::myPoa;
163 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
164 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
165 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
168 const int nbElemPerDiagonal = 10;
170 //=============================================================================
172 * GetServant [ static ]
174 * Get servant of the CORBA object
176 //=============================================================================
178 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
180 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
183 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
186 catch (PortableServer::POA::ObjectNotActive &ex)
188 INFOS("GetServant: ObjectNotActive");
191 catch (PortableServer::POA::WrongAdapter &ex)
193 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
196 catch (PortableServer::POA::WrongPolicy &ex)
198 INFOS("GetServant: WrongPolicy");
203 INFOS( "GetServant - Unknown exception was caught!!!" );
208 //=============================================================================
210 * SObjectToObject [ static ]
212 * Get CORBA object corresponding to the SALOMEDS::SObject
214 //=============================================================================
216 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
218 SALOMEDS::GenericAttribute_wrap anAttr;
219 CORBA::Object_var anObj;
220 if ( !theSObject->_is_nil() ) {
222 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
223 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
224 CORBA::String_var aValue = anIOR->Value();
225 if( strcmp( aValue, "" ) != 0 )
226 anObj = GetORB()->string_to_object( aValue );
230 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
236 //=============================================================================
240 * Get SALOME_NamingService object
242 //=============================================================================
244 SALOME_NamingService* SMESH_Gen_i::GetNS()
246 if ( myNS == NULL ) {
247 myNS = SINGLETON_<SALOME_NamingService>::Instance();
248 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
249 myNS->init_orb( GetORB() );
254 //=============================================================================
258 * Get SALOME_LifeCycleCORBA object
260 //=============================================================================
261 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
262 if ( myLCC == NULL ) {
263 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
269 //=============================================================================
271 * GetGeomEngine [ static ]
273 * Get GEOM::GEOM_Gen reference
275 //=============================================================================
276 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
277 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
278 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
279 //CCRT return aGeomEngine._retn();
280 if(CORBA::is_nil(myGeomGen))
282 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
283 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
288 //=============================================================================
290 * SMESH_Gen_i::SMESH_Gen_i
292 * Default constructor: not for use
294 //=============================================================================
296 SMESH_Gen_i::SMESH_Gen_i()
300 //=============================================================================
302 * SMESH_Gen_i::SMESH_Gen_i
304 * Standard constructor, used with Container
306 //=============================================================================
308 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
309 PortableServer::POA_ptr poa,
310 PortableServer::ObjectId* contId,
311 const char* instanceName,
312 const char* interfaceName )
313 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
316 myOrb = CORBA::ORB::_duplicate(orb);
317 myPoa = PortableServer::POA::_duplicate(poa);
320 _id = myPoa->activate_object( _thisObj );
322 myStudyContext = new StudyContext;
324 myIsEmbeddedMode = false;
325 myIsEnablePublish = true;
326 myShapeReader = NULL; // shape reader
328 myIsHistoricalPythonDump = true;
329 myToForgetMeshDataOnHypModif = false;
331 // set it in standalone mode only
332 //OSD::SetSignal( true );
334 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
335 // find out mode (embedded or standalone) here else
336 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
337 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
338 if ( SALOME_NamingService* ns = GetNS() )
340 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
341 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
342 if ( !session->_is_nil() )
344 CORBA::String_var str_host = session->getHostname();
345 CORBA::Long s_pid = session->getPID();
346 string my_host = Kernel_Utils::GetHostname();
348 long my_pid = (long)_getpid();
350 long my_pid = (long) getpid();
352 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
357 //=============================================================================
359 * SMESH_Gen_i::~SMESH_Gen_i
363 //=============================================================================
365 SMESH_Gen_i::~SMESH_Gen_i()
367 // delete hypothesis creators
368 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
369 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
371 // same creator can be mapped under different names
372 GenericHypothesisCreator_i* creator = (*itHyp).second;
376 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
377 if ( creator == (*itHyp2).second )
378 (*itHyp2).second = 0;
380 myHypCreatorMap.clear();
382 // Clear study contexts data
383 delete myStudyContext;
385 // delete shape reader
387 delete myShapeReader;
389 //=============================================================================
391 * SMESH_Gen_i::getHypothesisCreator
393 * Get hypothesis creator
395 //=============================================================================
396 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
397 const char* theLibName,
398 std::string& thePlatformLibName)
399 throw (SALOME::SALOME_Exception)
401 std::string aPlatformLibName;
402 /* It's Need to translate lib name for WIN32 or X platform */
403 if ( theLibName && theLibName[0] != '\0' )
405 int libNameLen = strlen(theLibName);
406 //check for old format "libXXXXXXX.so"
407 if (libNameLen > 7 &&
408 !strncmp( theLibName, "lib", 3 ) &&
409 !strcmp( theLibName+libNameLen-3, ".so" ))
413 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
414 #elif defined(__APPLE__)
415 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
417 aPlatformLibName = theLibName;
422 //try to use new format
424 aPlatformLibName = theLibName;
425 aPlatformLibName += ".dll";
426 #elif defined(__APPLE__)
427 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
429 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
433 thePlatformLibName = aPlatformLibName;
435 Unexpect aCatch(SALOME_SalomeException);
436 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
438 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
439 GenericHypothesisCreator_i* aCreator;
442 // check, if creator for this hypothesis type already exists
443 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
445 // load plugin library
446 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
449 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
451 const char* path = aPlatformLibName.c_str();
454 const char* path = aPlatformLibName.c_str();
456 LibHandle libHandle = LoadLib( path );
457 #if defined(WIN32) && defined(UNICODE)
462 // report any error, if occurred
464 const char* anError = dlerror();
465 throw(SALOME_Exception( anError ));
467 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
468 << aPlatformLibName));
472 // get method, returning hypothesis creator
473 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
474 GetHypothesisCreator procHandle =
475 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
478 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
479 << aPlatformLibName ));
480 UnLoadLib(libHandle);
483 // get hypothesis creator
484 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
485 aCreator = procHandle(theHypName);
488 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
489 << aPlatformLibName));
491 // map hypothesis creator to a hypothesis name
492 myHypCreatorMap[string(theHypName)] = aCreator;
497 return myHypCreatorMap[string(theHypName)];
500 catch (SALOME_Exception& S_ex)
502 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
507 //=============================================================================
509 * SMESH_Gen_i::createHypothesis
511 * Create hypothesis of given type
513 //=============================================================================
514 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
515 const char* theLibName)
517 SMESH_Hypothesis_i* myHypothesis_i = 0;
518 SMESH::SMESH_Hypothesis_var hypothesis_i;
519 std::string aPlatformLibName;
520 GenericHypothesisCreator_i* aCreator =
521 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
523 // create a new hypothesis object, store its ref. in studyContext
524 myHypothesis_i = aCreator->Create(myPoa, &myGen);
527 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
528 CORBA::String_var hypName = myHypothesis_i->GetName();
529 myHypCreatorMap[ hypName.in() ] = aCreator;
531 // activate the CORBA servant of hypothesis
532 hypothesis_i = myHypothesis_i->_this();
533 int nextId = RegisterObject( hypothesis_i );
534 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
535 else { nextId = 0; } // avoid "unused variable" warning in release mode
537 return hypothesis_i._retn();
540 //=============================================================================
542 * SMESH_Gen_i::createMesh
544 * Create empty mesh on shape
546 //=============================================================================
547 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
548 throw ( SALOME::SALOME_Exception )
550 Unexpect aCatch(SALOME_SalomeException);
551 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
553 // Get or create the GEOM_Client instance
555 // create a new mesh object servant, store it in a map in study context
556 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
557 // create a new mesh object
558 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
559 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
561 // activate the CORBA servant of Mesh
562 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
563 int nextId = RegisterObject( mesh );
564 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
565 else { nextId = 0; } // avoid "unused variable" warning in release mode
568 catch (SALOME_Exception& S_ex) {
569 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
571 return SMESH::SMESH_Mesh::_nil();
574 //=============================================================================
576 * SMESH_Gen_i::GetShapeReader
580 //=============================================================================
581 GEOM_Client* SMESH_Gen_i::GetShapeReader()
583 // create shape reader if necessary
584 if ( !myShapeReader )
585 myShapeReader = new GEOM_Client(GetContainerRef());
586 ASSERT( myShapeReader );
587 return myShapeReader;
590 //=============================================================================
592 * SMESH_Gen_i::SetGeomEngine
594 * Set GEOM::GEOM_Gen reference
596 //=============================================================================
597 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
598 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
600 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
601 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
602 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
606 //=============================================================================
608 * SMESH_Gen_i::SetEmbeddedMode
612 //=============================================================================
614 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
616 myIsEmbeddedMode = theMode;
618 if ( !myIsEmbeddedMode ) {
619 //PAL10867: disable signals catching with "noexcepthandler" option
620 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
621 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
626 char* envDisableFPE = getenv("DISABLE_FPE");
627 if (envDisableFPE && atoi(envDisableFPE))
632 OSD::SetSignal( raiseFPE );
634 // else OSD::SetSignal() is called in GUI
638 //=============================================================================
640 * SMESH_Gen_i::IsEmbeddedMode
644 //=============================================================================
646 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
648 return myIsEmbeddedMode;
651 //=============================================================================
653 * SMESH_Gen_i::SetEnablePublish
655 * Set enable publishing in the study
657 //=============================================================================
658 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
660 myIsEnablePublish = theIsEnablePublish;
663 //=============================================================================
665 * SMESH_Gen_i::IsEnablePublish
667 * Check enable publishing
669 //=============================================================================
671 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
673 return myIsEnablePublish;
676 //=============================================================================
678 * SMESH_Gen_i::UpdateStudy
680 * Update study (needed at switching GEOM->SMESH)
682 //=============================================================================
684 void SMESH_Gen_i::UpdateStudy()
686 if ( !myStudyContext )
687 myStudyContext = new StudyContext;
689 SALOMEDS::Study_var aStudy = getStudyServant();
690 if ( !CORBA::is_nil( aStudy ) ) {
691 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
692 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
693 if( !GEOM_var->_is_nil() )
694 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
695 // NPAL16168, issue 0020210
696 // Let meshes update their data depending on GEOM groups that could change
697 CORBA::String_var compDataType = ComponentDataType();
698 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
699 if ( !me->_is_nil() ) {
700 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
701 for ( ; anIter->More(); anIter->Next() ) {
702 SALOMEDS::SObject_wrap so = anIter->Value();
703 CORBA::Object_var ior = SObjectToObject( so );
704 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
705 mesh->CheckGeomModif();
711 //=============================================================================
713 * SMESH_Gen_i::GetStudyContext
717 //=============================================================================
718 StudyContext* SMESH_Gen_i::GetStudyContext()
720 return myStudyContext;
723 //=============================================================================
725 * SMESH_Gen_i::CreateHypothesis
727 * Create hypothesis/algorithm of given type and publish it in the study
729 //=============================================================================
731 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
732 const char* theLibName )
733 throw ( SALOME::SALOME_Exception )
735 Unexpect aCatch(SALOME_SalomeException);
736 // Create hypothesis/algorithm
737 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
739 // Publish hypothesis/algorithm in the study
740 if ( CanPublishInStudy( hyp ) ) {
741 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
742 if ( !aSO->_is_nil() ) {
743 // Update Python script
744 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
745 << theHypName << "', '" << theLibName << "')";
752 //================================================================================
754 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
755 * existing on the given geometry or to size of the geometry.
756 * \param theHypType - hypothesis type name
757 * \param theLibName - plugin library name
758 * \param theMesh - The mesh of interest
759 * \param theGeom - The shape to get parameter values from
760 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
761 * in a study and used to compute the mesh, or a temporary one created just to pass
764 //================================================================================
766 SMESH::SMESH_Hypothesis_ptr
767 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
768 const char* theLibName,
769 SMESH::SMESH_Mesh_ptr theMesh,
770 GEOM::GEOM_Object_ptr theGeom,
771 CORBA::Boolean byMesh)
772 throw ( SALOME::SALOME_Exception )
774 Unexpect aCatch(SALOME_SalomeException);
775 if ( byMesh && CORBA::is_nil( theMesh ) )
776 return SMESH::SMESH_Hypothesis::_nil();
777 if ( byMesh && CORBA::is_nil( theGeom ) )
778 return SMESH::SMESH_Hypothesis::_nil();
780 // -----------------------------------------------
781 // find hypothesis used to mesh theGeom
782 // -----------------------------------------------
784 // get mesh and shape
785 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
786 TopoDS_Shape shape = GeomObjectToShape( theGeom );
787 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
788 return SMESH::SMESH_Hypothesis::_nil();
789 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
791 // create a temporary hypothesis to know its dimension
792 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
793 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
795 return SMESH::SMESH_Hypothesis::_nil();
796 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
799 // look for a hypothesis of theHypType used to mesh the shape
800 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
803 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
804 int nbLocalHyps = aHypList->length();
805 for ( int i = 0; i < nbLocalHyps; i++ ) {
806 CORBA::String_var hypName = aHypList[i]->GetName();
807 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
808 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
810 // check super shapes
811 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
812 while ( nbLocalHyps == 0 && itShape.More() ) {
813 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
814 if ( ! CORBA::is_nil( geomObj )) {
815 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
816 nbLocalHyps = aHypList->length();
817 for ( int i = 0; i < nbLocalHyps; i++ )
818 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
819 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
825 // let the temporary hypothesis find out somehow parameter values by mesh
826 if ( hyp->SetParametersByMesh( mesh, shape ))
827 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
832 diagonal = mesh->GetShapeDiagonalSize();
834 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
835 ::SMESH_Hypothesis::TDefaults dflts;
836 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
837 dflts._nbSegments = myGen.GetDefaultNbSegments();
838 dflts._shape = &shape;
839 // let the temporary hypothesis initialize it's values
840 if ( hyp->SetParametersByDefaults( dflts, mesh ))
841 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
844 return SMESH::SMESH_Hypothesis::_nil();
847 //=============================================================================
849 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
850 * \param [in] theHyp - the hypothesis of interest
851 * \param [out] theMesh - the sole mesh using \a theHyp
852 * \param [out] theShape - the sole geometry \a theHyp is assigned to
853 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
855 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
856 * considered as SAME sub-mesh => result is \c true.
857 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
858 * a shape to which an hyp being edited is assigned.
860 //=============================================================================
862 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
863 SMESH::SMESH_Mesh_out theMesh,
864 GEOM::GEOM_Object_out theShape)
866 if ( CORBA::is_nil( theHyp ))
869 // get Mesh component SO
870 CORBA::String_var compDataType = ComponentDataType();
871 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
872 if ( CORBA::is_nil( comp ))
875 // look for child SO of meshes
876 SMESH::SMESH_Mesh_var foundMesh;
877 TopoDS_Shape foundShape;
879 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
880 for ( ; meshIter->More() && isSole; meshIter->Next() )
882 SALOMEDS::SObject_wrap curSO = meshIter->Value();
883 CORBA::Object_var obj = SObjectToObject( curSO );
884 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
888 // look for a sole shape where theHyp is assigned
889 bool isHypFound = false;
890 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
891 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
892 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
894 const THypList& hyps = s2hypsIt.Value();
895 THypList::const_iterator h = hyps.begin();
896 for ( ; h != hyps.end(); ++h )
897 if ( (*h)->GetID() == theHyp->GetId() )
899 if ( h != hyps.end()) // theHyp found
902 if ( ! foundShape.IsNull() &&
903 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
905 foundShape.Nullify();
909 foundShape = s2hypsIt.Key();
911 } // loop on assigned hyps
913 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
915 if ( !foundMesh->_is_nil() ) // not a sole mesh
917 if ( !foundMesh->HasShapeToMesh() ||
918 !mesh_i ->HasShapeToMesh() )
920 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
924 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
925 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
926 isSole = s1->IsSame( s2 );
929 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
935 ! foundMesh->_is_nil() &&
936 ! foundShape.IsNull() )
938 theMesh = foundMesh._retn();
939 theShape = ShapeToGeomObject( foundShape );
940 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
945 //=============================================================================
947 * Sets number of segments per diagonal of boundary box of geometry by which
948 * default segment length of appropriate 1D hypotheses is defined
950 //=============================================================================
952 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
953 throw ( SALOME::SALOME_Exception )
955 if ( theNbSegments > 0 )
956 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
958 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
960 //=============================================================================
962 * \brief Sets default number of segments per edge
964 //=============================================================================
965 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
966 throw ( SALOME::SALOME_Exception )
968 if ( theNbSegments > 0 )
969 myGen.SetDefaultNbSegments( int(theNbSegments) );
971 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
974 //=============================================================================
978 //=============================================================================
980 void SMESH_Gen_i::SetOption(const char* name, const char* value)
982 if ( name && value && strlen( value ) > 0 )
985 if ( strcmp(name, "historical_python_dump") == 0 )
987 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
988 msgToGUI = "preferences/SMESH/historical_python_dump/";
989 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
991 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
993 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
994 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
995 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
997 else if ( strcmp(name, "default_grp_color") == 0 )
1001 // color must be presented as a string of following form:
1002 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1003 str = str.substr(1);
1004 for ( size_t i = 0; i < str.length()/2; i++ )
1005 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1006 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1008 else if ( value ) { // rgb color ("255,170,0", for example)
1009 string tempValue( value );
1010 char* colorValue = strtok( &tempValue[0], "," );
1011 while ( colorValue != NULL ) {
1012 int c_value = atoi( colorValue );
1013 if ( c_value >= 0 && c_value <= 255 )
1014 color.push_back( c_value );
1015 colorValue = strtok( NULL, "," );
1018 if ( color.size() == 3 ) { // color must have three valid component
1019 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1020 myDefaultGroupColor = value;
1021 msgToGUI = "preferences/SMESH/default_grp_color/";
1026 // update preferences in case if SetOption() is invoked from python console
1027 if ( !msgToGUI.empty() )
1029 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1030 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1031 if ( !CORBA::is_nil( session ) )
1032 session->emitMessageOneWay(msgToGUI.c_str());
1037 //=============================================================================
1039 Return an option value
1041 //=============================================================================
1043 char* SMESH_Gen_i::GetOption(const char* name)
1047 if ( strcmp(name, "historical_python_dump") == 0 )
1049 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1051 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1053 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1055 if ( strcmp(name, "default_grp_color") == 0 )
1057 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1060 return CORBA::string_dup( "" );
1063 //=============================================================================
1065 * SMESH_Gen_i::CreateMesh
1067 * Create empty mesh on a shape and publish it in the study
1069 //=============================================================================
1071 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1072 throw ( SALOME::SALOME_Exception )
1074 Unexpect aCatch(SALOME_SalomeException);
1075 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1077 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1079 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1080 ASSERT( meshServant );
1081 meshServant->SetShape( theShapeObject );
1083 // publish mesh in the study
1084 if ( CanPublishInStudy( mesh ) ) {
1085 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1086 aStudyBuilder->NewCommand(); // There is a transaction
1087 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1088 aStudyBuilder->CommitCommand();
1089 if ( !aSO->_is_nil() ) {
1090 // Update Python script
1091 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1095 return mesh._retn();
1098 //=============================================================================
1100 * SMESH_Gen_i::CreateEmptyMesh
1104 //=============================================================================
1106 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1107 throw ( SALOME::SALOME_Exception )
1109 Unexpect aCatch(SALOME_SalomeException);
1110 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1112 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1114 // publish mesh in the study
1115 if ( CanPublishInStudy( mesh ) ) {
1116 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1117 aStudyBuilder->NewCommand(); // There is a transaction
1118 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1119 aStudyBuilder->CommitCommand();
1120 if ( !aSO->_is_nil() ) {
1121 // Update Python script
1122 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1126 return mesh._retn();
1131 //================================================================================
1133 * \brief Throws an exception in case if the file can't be read
1135 //================================================================================
1137 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1139 SMESH_File f ( theFileName );
1142 if ( !f.error().empty() )
1143 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1145 THROW_SALOME_CORBA_EXCEPTION
1146 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1147 SALOME::BAD_PARAM );
1152 //=============================================================================
1154 * SMESH_Gen_i::CreateMeshFromUNV
1156 * Create mesh and import data from UNV file
1158 //=============================================================================
1160 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1161 throw ( SALOME::SALOME_Exception )
1163 Unexpect aCatch(SALOME_SalomeException);
1165 checkFileReadable( theFileName );
1167 SMESH::SMESH_Mesh_var aMesh = createMesh();
1169 // publish mesh in the study
1170 if ( CanPublishInStudy( aMesh ) ) {
1171 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1172 aStudyBuilder->NewCommand(); // There is a transaction
1173 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1174 aStudyBuilder->CommitCommand();
1175 if ( !aSO->_is_nil() ) {
1176 // Update Python script
1177 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1181 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1183 aServant->ImportUNVFile( theFileName );
1185 // Dump creation of groups
1186 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1188 aServant->GetImpl().GetMeshDS()->Modified();
1189 return aMesh._retn();
1192 //=============================================================================
1194 * SMESH_Gen_i::CreateMeshFromMED
1196 * Create mesh and import data from MED file
1198 //=============================================================================
1200 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1201 SMESH::DriverMED_ReadStatus& theStatus,
1202 const char* theCommandNameForPython,
1203 const char* theFileNameForPython)
1206 char bname[ _MAX_FNAME ];
1207 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1208 string aFileName = bname;
1210 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1212 // Retrieve mesh names from the file
1213 DriverMED_R_SMESHDS_Mesh myReader;
1214 myReader.SetFile( theFileName );
1215 myReader.SetMeshId( -1 );
1216 Driver_Mesh::Status aStatus;
1217 list<string> aNames = myReader.GetMeshNames(aStatus);
1218 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1219 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1221 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1224 TPythonDump aPythonDump;
1225 aPythonDump << "([";
1227 if (theStatus == SMESH::DRS_OK) {
1228 SALOMEDS::StudyBuilder_var aStudyBuilder;
1229 aStudyBuilder = getStudyServant()->NewBuilder();
1230 aStudyBuilder->NewCommand(); // There is a transaction
1232 aResult->length( aNames.size() );
1235 // Iterate through all meshes and create mesh objects
1236 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1239 if (i > 0) aPythonDump << ", ";
1242 SMESH::SMESH_Mesh_var mesh = createMesh();
1244 // publish mesh in the study
1245 SALOMEDS::SObject_wrap aSO;
1246 if ( CanPublishInStudy( mesh ) )
1247 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1248 // - as names of meshes are stored in MED file, we use them for data publishing
1249 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1250 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1253 if ( !aSO->_is_nil() ) {
1256 aPythonDump << "mesh_" << i;
1259 // Read mesh data (groups are published automatically by ImportMEDFile())
1260 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1261 ASSERT( meshServant );
1262 SMESH::DriverMED_ReadStatus status1 =
1263 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1264 if (status1 > theStatus)
1265 theStatus = status1;
1267 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1268 meshServant->GetImpl().GetMeshDS()->Modified();
1270 if ( !aStudyBuilder->_is_nil() )
1271 aStudyBuilder->CommitCommand();
1274 // Update Python script
1275 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1277 // Dump creation of groups
1278 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1279 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1281 return aResult._retn();
1284 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1285 SMESH::DriverMED_ReadStatus& theStatus)
1286 throw ( SALOME::SALOME_Exception )
1288 Unexpect aCatch(SALOME_SalomeException);
1289 checkFileReadable( theFileName );
1291 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1295 //=============================================================================
1297 * SMESH_Gen_i::CreateMeshFromSAUV
1299 * Create mesh and import data from SAUV file
1301 //=============================================================================
1303 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1304 SMESH::DriverMED_ReadStatus& theStatus)
1305 throw ( SALOME::SALOME_Exception )
1307 Unexpect aCatch(SALOME_SalomeException);
1308 checkFileReadable( theFileName );
1310 std::string sauvfilename(theFileName);
1311 std::string medfilename(theFileName);
1312 medfilename += ".med";
1315 cmd = "%PYTHONBIN% ";
1320 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1322 system(cmd.c_str());
1323 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1325 cmd = "%PYTHONBIN% ";
1330 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1332 system(cmd.c_str());
1336 //=============================================================================
1338 * SMESH_Gen_i::CreateMeshFromSTL
1340 * Create mesh and import data from STL file
1342 //=============================================================================
1344 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1345 throw ( SALOME::SALOME_Exception )
1347 Unexpect aCatch(SALOME_SalomeException);
1348 checkFileReadable( theFileName );
1350 SMESH::SMESH_Mesh_var aMesh = createMesh();
1353 char bname[ _MAX_FNAME ];
1354 _splitpath( theFileName, NULL, NULL, bname, NULL );
1355 string aFileName = bname;
1357 string aFileName = basename( const_cast<char *>(theFileName) );
1359 // publish mesh in the study
1360 if ( CanPublishInStudy( aMesh ) ) {
1361 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1362 aStudyBuilder->NewCommand(); // There is a transaction
1363 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1364 aStudyBuilder->CommitCommand();
1365 if ( !aSO->_is_nil() ) {
1366 // Update Python script
1367 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1371 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1373 aServant->ImportSTLFile( theFileName );
1374 aServant->GetImpl().GetMeshDS()->Modified();
1375 return aMesh._retn();
1378 //================================================================================
1380 * \brief Create meshes and import data from the CGSN file
1382 //================================================================================
1384 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1385 SMESH::DriverMED_ReadStatus& theStatus)
1386 throw ( SALOME::SALOME_Exception )
1388 Unexpect aCatch(SALOME_SalomeException);
1389 checkFileReadable( theFileName );
1391 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1394 // Retrieve nb meshes from the file
1395 DriverCGNS_Read myReader;
1396 myReader.SetFile( theFileName );
1397 Driver_Mesh::Status aStatus;
1398 int nbMeshes = myReader.GetNbMeshes(aStatus);
1399 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1401 aResult->length( nbMeshes );
1403 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1406 TPythonDump aPythonDump;
1407 aPythonDump << "([";
1409 if (theStatus == SMESH::DRS_OK)
1411 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1412 aStudyBuilder->NewCommand(); // There is a transaction
1416 // Iterate through all meshes and create mesh objects
1417 for ( ; i < nbMeshes; ++i )
1420 if (i > 0) aPythonDump << ", ";
1423 SMESH::SMESH_Mesh_var mesh = createMesh();
1424 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1426 // Read mesh data (groups are published automatically by ImportMEDFile())
1427 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1428 ASSERT( meshServant );
1430 SMESH::DriverMED_ReadStatus status1 =
1431 meshServant->ImportCGNSFile( theFileName, i, meshName );
1432 if (status1 > theStatus)
1433 theStatus = status1;
1435 meshServant->GetImpl().GetMeshDS()->Modified();
1436 // publish mesh in the study
1437 SALOMEDS::SObject_wrap aSO;
1438 if ( CanPublishInStudy( mesh ) )
1439 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1442 if ( !aSO->_is_nil() ) {
1446 aPythonDump << "mesh_" << i;
1449 aStudyBuilder->CommitCommand();
1452 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1454 // Dump creation of groups
1455 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1456 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1458 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1461 return aResult._retn();
1464 //================================================================================
1466 * \brief Create a mesh and import data from a GMF file
1468 //================================================================================
1470 SMESH::SMESH_Mesh_ptr
1471 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1472 CORBA::Boolean theMakeRequiredGroups,
1473 SMESH::ComputeError_out theError)
1474 throw ( SALOME::SALOME_Exception )
1476 Unexpect aCatch(SALOME_SalomeException);
1477 checkFileReadable( theFileName );
1479 SMESH::SMESH_Mesh_var aMesh = createMesh();
1481 char bname[ _MAX_FNAME ];
1482 _splitpath( theFileName, NULL, NULL, bname, NULL );
1483 string aFileName = bname;
1485 string aFileName = basename( const_cast<char *>(theFileName) );
1487 // publish mesh in the study
1488 if ( CanPublishInStudy( aMesh ) ) {
1489 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1490 aStudyBuilder->NewCommand(); // There is a transaction
1491 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1492 aStudyBuilder->CommitCommand();
1493 if ( !aSO->_is_nil() ) {
1494 // Update Python script
1495 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1496 << theFileName << "', "
1497 << theMakeRequiredGroups << " )";
1500 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1502 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1503 aServant->GetImpl().GetMeshDS()->Modified();
1504 return aMesh._retn();
1508 //=============================================================================
1510 * SMESH_Gen_i::IsReadyToCompute
1512 * Returns true if mesh contains enough data to be computed
1514 //=============================================================================
1516 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1517 GEOM::GEOM_Object_ptr theShapeObject )
1518 throw ( SALOME::SALOME_Exception )
1520 Unexpect aCatch(SALOME_SalomeException);
1521 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1523 if ( CORBA::is_nil( theShapeObject ) )
1524 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1525 SALOME::BAD_PARAM );
1527 if ( CORBA::is_nil( theMesh ) )
1528 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1529 SALOME::BAD_PARAM );
1533 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1534 ASSERT( meshServant );
1535 if ( meshServant ) {
1536 // get local TopoDS_Shape
1537 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1538 // call implementation
1539 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1540 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1543 catch ( SALOME_Exception& S_ex ) {
1544 INFOS( "catch exception "<< S_ex.what() );
1549 //================================================================================
1551 * \brief Find SObject for an algo
1553 //================================================================================
1555 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1558 SALOMEDS::Study_var aStudy = getStudyServant();
1559 if ( !aStudy->_is_nil() ) {
1560 // find algo in the study
1561 CORBA::String_var compDataType = ComponentDataType();
1562 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1563 if ( !father->_is_nil() ) {
1564 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1565 for ( ; itBig->More(); itBig->Next() ) {
1566 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1567 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1568 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1569 for ( ; algoIt->More(); algoIt->Next() ) {
1570 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1571 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1572 if ( !CORBA::is_nil( algoIOR )) {
1573 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1574 if ( impl && impl->GetImpl() == algo )
1575 return algoSO._retn();
1577 } // loop on algo SO's
1580 } // SMESH component iterator
1584 return SALOMEDS::SObject::_nil();
1587 //================================================================================
1589 * \brief Return errors of mesh computation
1591 //================================================================================
1593 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1594 GEOM::GEOM_Object_ptr theSubObject )
1595 throw ( SALOME::SALOME_Exception )
1597 Unexpect aCatch(SALOME_SalomeException);
1598 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1600 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1601 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1603 if ( CORBA::is_nil( theMesh ) )
1604 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1606 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1608 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1611 if(theMesh->HasShapeToMesh())
1612 shape = GeomObjectToShape( theSubObject );
1614 shape = SMESH_Mesh::PseudoShape();
1616 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1618 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1621 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1622 const bool includeSelf = true, complexShapeFirst = true;
1623 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1625 while ( smIt->more() )
1628 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1630 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1631 if ( error && !error->IsOK() )
1633 if ( !( error->myAlgo ) &&
1634 !( error->myAlgo = sm->GetAlgo() ))
1636 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1637 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1638 errStruct.comment = error->myComment.c_str();
1639 errStruct.subShapeID = sm->GetId();
1640 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1641 if ( !algoSO->_is_nil() ) {
1642 CORBA::String_var algoName = algoSO->GetName();
1643 errStruct.algoName = algoName;
1646 errStruct.algoName = error->myAlgo->GetName();
1648 errStruct.hasBadMesh = error->HasBadElems();
1651 error_array->length( nbErr );
1654 catch ( SALOME_Exception& S_ex ) {
1655 INFOS( "catch exception "<< S_ex.what() );
1658 return error_array._retn();
1661 //================================================================================
1663 * \brief Return mesh elements preventing computation of a subshape
1665 //================================================================================
1667 SMESH::MeshPreviewStruct*
1668 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1669 CORBA::Short theSubShapeID )
1670 throw ( SALOME::SALOME_Exception )
1672 Unexpect aCatch(SALOME_SalomeException);
1673 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1675 if ( CORBA::is_nil( theMesh ) )
1676 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1678 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1681 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1683 // mesh implementation
1684 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1685 // submesh by subshape id
1686 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1689 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1690 if ( error && error->HasBadElems() )
1692 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1693 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1695 // get nodes of elements and count elements
1696 TNode2LocalIDMap mapNode2LocalID;
1697 list< TNodeLocalID > connectivity;
1698 int i, nbElements = 0, nbConnNodes = 0;
1700 const list<const SMDS_MeshElement*>& badElems =
1701 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1702 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1703 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1704 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1706 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1707 while ( nIt->more() )
1708 connectivity.push_back
1709 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1711 // fill node coords and assign local ids to the nodes
1712 int nbNodes = mapNode2LocalID.size();
1713 result->nodesXYZ.length( nbNodes );
1714 TNodeLocalID node2ID = mapNode2LocalID.begin();
1715 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1716 node2ID->second = i;
1717 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1718 result->nodesXYZ[i].x = node->X();
1719 result->nodesXYZ[i].y = node->Y();
1720 result->nodesXYZ[i].z = node->Z();
1722 // fill connectivity
1723 result->elementConnectivities.length( nbConnNodes );
1724 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1725 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1726 result->elementConnectivities[i] = (*connIt)->second;
1728 // fill element types
1729 result->elementTypes.length( nbElements );
1730 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1732 const SMDS_MeshElement* elem = *elemIt;
1733 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1734 result->elementTypes[i].isPoly = elem->IsPoly();
1735 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1741 catch ( SALOME_Exception& S_ex ) {
1742 INFOS( "catch exception "<< S_ex.what() );
1745 return result._retn();
1748 //================================================================================
1750 * \brief Create a group of elements preventing computation of a sub-shape
1752 //================================================================================
1754 SMESH::ListOfGroups*
1755 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1756 CORBA::Short theSubShapeID,
1757 const char* theGroupName )
1758 throw ( SALOME::SALOME_Exception )
1760 Unexpect aCatch(SALOME_SalomeException);
1762 SMESH::ListOfGroups_var groups;
1764 if ( CORBA::is_nil( theMesh ) )
1765 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1768 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1770 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1771 TPythonDump() << groups << " = " << this
1772 << ".MakeGroupsOfBadInputElements( "
1773 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1776 catch ( SALOME_Exception& S_ex ) {
1777 INFOS( "catch exception "<< S_ex.what() );
1779 return groups._retn();
1782 //================================================================================
1784 * \brief Returns errors of hypotheses definition
1785 * \param theMesh - the mesh
1786 * \param theSubObject - the main or sub- shape
1787 * \retval SMESH::algo_error_array* - sequence of errors
1789 //================================================================================
1791 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1792 GEOM::GEOM_Object_ptr theSubObject )
1793 throw ( SALOME::SALOME_Exception )
1795 Unexpect aCatch(SALOME_SalomeException);
1796 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1798 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1799 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1801 if ( CORBA::is_nil( theMesh ) )
1802 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1804 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1806 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1807 ASSERT( meshServant );
1808 if ( meshServant ) {
1809 TopoDS_Shape myLocShape;
1810 if(theMesh->HasShapeToMesh())
1811 myLocShape = GeomObjectToShape( theSubObject );
1813 myLocShape = SMESH_Mesh::PseudoShape();
1815 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1816 list< ::SMESH_Gen::TAlgoStateError > error_list;
1817 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1818 // call ::SMESH_Gen::GetAlgoState()
1819 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1820 error_array->length( error_list.size() );
1822 for ( error = error_list.begin(); error != error_list.end(); ++error )
1824 // fill AlgoStateError structure
1825 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1826 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1827 errStruct.algoDim = error->_algoDim;
1828 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1829 errStruct.algoName = "";
1830 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1831 if ( !algoSO->_is_nil() ) {
1832 CORBA::String_var algoName = algoSO->GetName();
1833 errStruct.algoName = algoName.in();
1838 catch ( SALOME_Exception& S_ex ) {
1839 INFOS( "catch exception "<< S_ex.what() );
1841 return error_array._retn();
1844 //=============================================================================
1846 * SMESH_Gen_i::GetSubShapesId
1848 * Get sub-shapes unique ID's list
1850 //=============================================================================
1853 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1854 const SMESH::object_array& theListOfSubShapeObject )
1855 throw ( SALOME::SALOME_Exception )
1857 Unexpect aCatch(SALOME_SalomeException);
1858 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1860 SMESH::long_array_var shapesId = new SMESH::long_array;
1863 if ( CORBA::is_nil( theMainShapeObject ) )
1864 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1868 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1869 TopTools_IndexedMapOfShape myIndexToShape;
1870 TopExp::MapShapes(myMainShape,myIndexToShape);
1872 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1874 GEOM::GEOM_Object_var aShapeObject
1875 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1876 if ( CORBA::is_nil( aShapeObject ) )
1877 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1878 SALOME::BAD_PARAM );
1880 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1881 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1883 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1884 setId.insert(myIndexToShape.FindIndex(F));
1885 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1887 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1889 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1890 setId.insert(myIndexToShape.FindIndex(E));
1891 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1893 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1895 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1896 setId.insert(myIndexToShape.FindIndex(V));
1897 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1900 shapesId->length(setId.size());
1901 set<int>::iterator iind;
1903 for (iind = setId.begin(); iind != setId.end(); iind++)
1905 if(MYDEBUG) SCRUTE((*iind));
1906 shapesId[i] = (*iind);
1907 if(MYDEBUG) SCRUTE(shapesId[i]);
1911 catch (SALOME_Exception& S_ex)
1913 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1916 return shapesId._retn();
1919 //=============================================================================
1921 * SMESH_Gen_i::Compute
1923 * Compute mesh on a shape
1925 //=============================================================================
1927 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1928 GEOM::GEOM_Object_ptr theShapeObject )
1929 throw ( SALOME::SALOME_Exception )
1932 Unexpect aCatch(SALOME_SalomeException);
1933 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1935 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1936 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1937 SALOME::BAD_PARAM );
1939 if ( CORBA::is_nil( theMesh ) )
1940 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1941 SALOME::BAD_PARAM );
1943 // Update Python script
1944 TPythonDump() << "isDone = " << this << ".Compute( "
1945 << theMesh << ", " << theShapeObject << ")";
1949 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1950 ASSERT( meshServant );
1951 if ( meshServant ) {
1952 meshServant->Load();
1953 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
1954 meshServant->CheckGeomModif();
1955 // get local TopoDS_Shape
1956 TopoDS_Shape myLocShape;
1957 if(theMesh->HasShapeToMesh())
1958 myLocShape = GeomObjectToShape( theShapeObject );
1960 myLocShape = SMESH_Mesh::PseudoShape();
1961 // call implementation compute
1962 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1963 myGen.PrepareCompute( myLocMesh, myLocShape );
1964 int how = ::SMESH_Gen::COMPACT_MESH;
1965 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1966 how |= ::SMESH_Gen::SHAPE_ONLY;
1967 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1968 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1969 myLocMesh.GetMeshDS()->Modified();
1970 UpdateIcons( theMesh );
1972 HighLightInvalid( theMesh, /*isInvalid=*/false );
1976 catch ( std::bad_alloc ) {
1977 INFOS( "Compute(): lack of memory" );
1979 catch ( SALOME_Exception& S_ex ) {
1980 INFOS( "Compute(): catch exception "<< S_ex.what() );
1983 INFOS( "Compute(): unknown exception " );
1988 //=============================================================================
1990 * SMESH_Gen_i::CancelCompute
1992 * Cancel Compute mesh on a shape
1994 //=============================================================================
1996 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1997 GEOM::GEOM_Object_ptr theShapeObject )
1999 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2001 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2002 TopoDS_Shape myLocShape;
2003 if(theMesh->HasShapeToMesh())
2004 myLocShape = GeomObjectToShape( theShapeObject );
2006 myLocShape = SMESH_Mesh::PseudoShape();
2007 myGen.CancelCompute( myLocMesh, myLocShape);
2011 //=============================================================================
2013 * SMESH_Gen_i::Precompute
2015 * Compute mesh as preview till indicated dimension on shape
2017 //=============================================================================
2019 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2020 GEOM::GEOM_Object_ptr theShapeObject,
2021 SMESH::Dimension theDimension,
2022 SMESH::long_array& theShapesId)
2023 throw ( SALOME::SALOME_Exception )
2025 Unexpect aCatch(SALOME_SalomeException);
2026 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2028 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2029 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2030 SALOME::BAD_PARAM );
2032 if ( CORBA::is_nil( theMesh ) )
2033 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2034 SALOME::BAD_PARAM );
2036 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2039 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2040 meshServant->Load();
2041 ASSERT( meshServant );
2042 if ( meshServant ) {
2043 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2044 meshServant->CheckGeomModif();
2045 // get local TopoDS_Shape
2046 TopoDS_Shape myLocShape;
2047 if(theMesh->HasShapeToMesh())
2048 myLocShape = GeomObjectToShape( theShapeObject );
2050 return result._retn();;
2052 // call implementation compute
2053 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2055 ::MeshDimension aDim = (MeshDimension)theDimension;
2056 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2058 int nbShapeId = shapeIds.size();
2059 theShapesId.length( nbShapeId );
2060 // iterates on shapes and collect mesh entities into mesh preview
2061 TSetOfInt::const_iterator idIt = shapeIds.begin();
2062 TSetOfInt::const_iterator idEnd = shapeIds.end();
2063 std::map< int, int > mapOfShIdNb;
2064 std::set< SMESH_TLink > setOfEdge;
2065 std::list< SMDSAbs_ElementType > listOfElemType;
2066 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2067 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2068 TNode2LocalIDMap mapNode2LocalID;
2069 list< TNodeLocalID > connectivity;
2070 int i, nbConnNodes = 0;
2071 std::set< const SMESH_subMesh* > setOfVSubMesh;
2072 // iterates on shapes
2073 for ( ; idIt != idEnd; idIt++ )
2075 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2077 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2078 if ( !sm || !sm->IsMeshComputed() )
2081 const TopoDS_Shape& aSh = sm->GetSubShape();
2082 const int shDim = myGen.GetShapeDim( aSh );
2083 if ( shDim < 1 || shDim > theDimension )
2086 mapOfShIdNb[ *idIt ] = 0;
2087 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2089 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2090 if ( !smDS ) continue;
2092 if ( theDimension == SMESH::DIM_2D )
2094 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2095 while ( faceIt->more() )
2097 const SMDS_MeshElement* face = faceIt->next();
2098 int aNbNode = face->NbNodes();
2100 aNbNode /= 2; // do not take into account additional middle nodes
2102 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2103 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2105 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2106 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2108 listOfElemType.push_back( SMDSAbs_Edge );
2109 connectivity.push_back
2110 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2111 connectivity.push_back
2112 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2118 else if ( theDimension == SMESH::DIM_1D )
2120 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2121 while ( nodeIt->more() )
2123 listOfElemType.push_back( SMDSAbs_Node );
2124 connectivity.push_back
2125 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2127 // add corner nodes by first vertex from edge
2128 SMESH_subMeshIteratorPtr edgeSmIt =
2129 sm->getDependsOnIterator(/*includeSelf*/false,
2130 /*complexShapeFirst*/false);
2131 while ( edgeSmIt->more() )
2133 SMESH_subMesh* vertexSM = edgeSmIt->next();
2134 // check that vertex is not already treated
2135 if ( !setOfVSubMesh.insert( vertexSM ).second )
2137 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2140 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2141 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2142 while ( nodeIt->more() )
2144 listOfElemType.push_back( SMDSAbs_Node );
2145 connectivity.push_back
2146 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2152 // fill node coords and assign local ids to the nodes
2153 int nbNodes = mapNode2LocalID.size();
2154 result->nodesXYZ.length( nbNodes );
2155 TNodeLocalID node2ID = mapNode2LocalID.begin();
2156 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2157 node2ID->second = i;
2158 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2159 result->nodesXYZ[i].x = node->X();
2160 result->nodesXYZ[i].y = node->Y();
2161 result->nodesXYZ[i].z = node->Z();
2163 // fill connectivity
2164 result->elementConnectivities.length( nbConnNodes );
2165 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2166 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2167 result->elementConnectivities[i] = (*connIt)->second;
2170 // fill element types
2171 result->elementTypes.length( listOfElemType.size() );
2172 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2173 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2174 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2176 SMDSAbs_ElementType elemType = *typeIt;
2177 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2178 result->elementTypes[i].isPoly = false;
2179 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2182 // correct number of shapes
2183 theShapesId.length( mapOfShIdNb.size() );
2187 catch ( std::bad_alloc ) {
2188 INFOS( "Precompute(): lack of memory" );
2190 catch ( SALOME_Exception& S_ex ) {
2191 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2194 INFOS( "Precompute(): unknown exception " );
2196 return result._retn();
2200 //=============================================================================
2202 * SMESH_Gen_i::Evaluate
2204 * Evaluate mesh on a shape
2206 //=============================================================================
2208 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2209 GEOM::GEOM_Object_ptr theShapeObject)
2210 // SMESH::long_array& theNbElems)
2211 throw ( SALOME::SALOME_Exception )
2213 Unexpect aCatch(SALOME_SalomeException);
2214 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2216 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2217 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2218 SALOME::BAD_PARAM );
2220 if ( CORBA::is_nil( theMesh ) )
2221 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2222 SALOME::BAD_PARAM );
2224 SMESH::long_array_var nbels = new SMESH::long_array;
2225 nbels->length(SMESH::Entity_Last);
2226 int i = SMESH::Entity_Node;
2227 for (; i < SMESH::Entity_Last; i++)
2230 // Update Python script
2231 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2232 << theMesh << ", " << theShapeObject << ")";
2236 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2237 ASSERT( meshServant );
2238 if ( meshServant ) {
2239 meshServant->Load();
2240 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2241 meshServant->CheckGeomModif();
2242 // get local TopoDS_Shape
2243 TopoDS_Shape myLocShape;
2244 if(theMesh->HasShapeToMesh())
2245 myLocShape = GeomObjectToShape( theShapeObject );
2247 myLocShape = SMESH_Mesh::PseudoShape();
2248 // call implementation compute
2249 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2250 MapShapeNbElems aResMap;
2251 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2252 MapShapeNbElemsItr anIt = aResMap.begin();
2253 for(; anIt!=aResMap.end(); anIt++) {
2254 const vector<int>& aVec = (*anIt).second;
2255 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2256 int nbElem = aVec[i];
2257 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2259 SMESH_subMesh* sm = anIt->first;
2260 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2261 const SMESH_Algo* algo = sm->GetAlgo();
2262 if ( (algo && !error.get()) || error->IsOK() )
2263 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2267 nbels[i] += aVec[i];
2271 return nbels._retn();
2274 catch ( std::bad_alloc ) {
2275 INFOS( "Evaluate(): lack of memory" );
2277 catch ( SALOME_Exception& S_ex ) {
2278 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2281 INFOS( "Evaluate(): unknown exception " );
2284 return nbels._retn();
2287 //================================================================================
2289 * \brief Return geometrical object the given element is built on
2290 * \param theMesh - the mesh the element is in
2291 * \param theElementID - the element ID
2292 * \param theGeomName - the name of the result geom object if it is not yet published
2293 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2295 //================================================================================
2297 GEOM::GEOM_Object_ptr
2298 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2299 CORBA::Long theElementID,
2300 const char* theGeomName)
2301 throw ( SALOME::SALOME_Exception )
2303 Unexpect aCatch(SALOME_SalomeException);
2305 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2306 if ( !geom->_is_nil() ) {
2307 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2308 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2310 // try to find the corresponding SObject
2311 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2312 if ( SObj->_is_nil() ) // submesh can be not found even if published
2314 // try to find published submesh
2315 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2316 if ( !geom->IsMainShape() && list->length() == 1 ) {
2317 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2318 SALOMEDS::ChildIterator_wrap it;
2319 if ( !mainSO->_is_nil() ) {
2320 it = getStudyServant()->NewChildIterator( mainSO );
2322 if ( !it->_is_nil() ) {
2323 for ( it->InitEx(true); it->More(); it->Next() ) {
2324 SALOMEDS::SObject_wrap so = it->Value();
2325 CORBA::Object_var obj = SObjectToObject( so );
2326 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2327 if ( !subGeom->_is_nil() ) {
2328 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2329 if ( subList->length() == 1 && list[0] == subList[0] ) {
2339 if ( SObj->_is_nil() ) // publish a new subshape
2340 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2342 // return only published geometry
2343 if ( !SObj->_is_nil() ) {
2344 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2345 CORBA::Object_var obj = SObjectToObject( SObj );
2346 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2350 return GEOM::GEOM_Object::_nil();
2353 //================================================================================
2355 * \brief Return geometrical object the given element is built on.
2356 * \param theMesh - the mesh the element is in
2357 * \param theElementID - the element ID
2358 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2360 //================================================================================
2362 GEOM::GEOM_Object_ptr
2363 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2364 CORBA::Long theElementID)
2365 throw ( SALOME::SALOME_Exception )
2367 Unexpect aCatch(SALOME_SalomeException);
2368 if ( CORBA::is_nil( theMesh ) )
2369 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2371 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2372 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2374 // get a core mesh DS
2375 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2376 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2378 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2379 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2380 // find the element in mesh
2381 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2382 // find a shape id by the element
2383 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2384 // get a geom object by the shape id
2385 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2386 if ( geom->_is_nil() ) {
2387 // try to find a published sub-shape
2388 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2389 SALOMEDS::ChildIterator_wrap it;
2390 if ( !mainSO->_is_nil() ) {
2391 it = getStudyServant()->NewChildIterator( mainSO );
2393 if ( !it->_is_nil() ) {
2394 for ( it->InitEx(true); it->More(); it->Next() ) {
2395 SALOMEDS::SObject_wrap so = it->Value();
2396 CORBA::Object_var obj = SObjectToObject( so );
2397 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2398 if ( !subGeom->_is_nil() ) {
2399 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2400 if ( subList->length() == 1 && shapeID == subList[0] ) {
2408 if ( geom->_is_nil() ) {
2410 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2411 if ( !op->_is_nil() )
2412 geom = op->GetSubShape( mainShape, shapeID );
2417 if ( !geom->_is_nil() ) {
2418 GeomObjectToShape( geom ); // let geom client remember the found shape
2419 return geom._retn();
2424 return GEOM::GEOM_Object::_nil();
2427 //================================================================================
2429 * SMESH_Gen_i::Concatenate
2431 * Concatenate the given meshes into one mesh
2433 //================================================================================
2435 SMESH::SMESH_Mesh_ptr
2436 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2437 CORBA::Boolean theUniteIdenticalGroups,
2438 CORBA::Boolean theMergeNodesAndElements,
2439 CORBA::Double theMergeTolerance,
2440 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2441 throw ( SALOME::SALOME_Exception )
2443 return ConcatenateCommon(theMeshesArray,
2444 theUniteIdenticalGroups,
2445 theMergeNodesAndElements,
2451 //================================================================================
2453 * SMESH_Gen_i::ConcatenateWithGroups
2455 * Concatenate the given meshes into one mesh
2456 * Create the groups of all elements from initial meshes
2458 //================================================================================
2460 SMESH::SMESH_Mesh_ptr
2461 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2462 CORBA::Boolean theUniteIdenticalGroups,
2463 CORBA::Boolean theMergeNodesAndElements,
2464 CORBA::Double theMergeTolerance,
2465 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2466 throw ( SALOME::SALOME_Exception )
2468 return ConcatenateCommon(theMeshesArray,
2469 theUniteIdenticalGroups,
2470 theMergeNodesAndElements,
2476 //================================================================================
2478 * SMESH_Gen_i::ConcatenateCommon
2480 * Concatenate the given meshes into one mesh
2482 //================================================================================
2484 SMESH::SMESH_Mesh_ptr
2485 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2486 CORBA::Boolean theUniteIdenticalGroups,
2487 CORBA::Boolean theMergeNodesAndElements,
2488 CORBA::Double theMergeTolerance,
2489 CORBA::Boolean theCommonGroups,
2490 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2491 throw ( SALOME::SALOME_Exception )
2493 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2494 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2496 // create mesh if theMeshToAppendTo not provided
2497 SMESH::SMESH_Mesh_var newMesh;
2498 if ( CORBA::is_nil( theMeshToAppendTo ))
2499 newMesh = CreateEmptyMesh();
2501 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2502 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2503 if ( !newImpl ) return newMesh._retn();
2506 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2507 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2509 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2510 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2511 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2512 TGroupsMap groupsMap;
2513 TListOfNewGroups listOfNewGroups;
2515 if ( !CORBA::is_nil( theMeshToAppendTo ))
2517 // fill groupsMap with existing groups
2518 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2519 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2521 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2522 if ( !group->_is_nil() )
2524 CORBA::String_var name = group->GetName();
2525 SMESH::ElementType type = group->GetType();
2526 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2531 ::SMESH_MeshEditor newEditor( &locMesh );
2532 ::SMESH_MeshEditor::ElemFeatures elemType;
2534 // loop on sub-meshes
2535 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2537 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2538 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2539 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2540 if ( !initImpl ) continue;
2541 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2545 // assure that IDs increment by one during iteration
2546 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2547 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2548 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2549 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2551 initMeshDS->Modified();
2552 initMeshDS->CompactMesh();
2555 // remember nb of elements before filling in
2556 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2560 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2561 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2562 while ( elemIt->more() )
2564 SMESH_NodeXYZ node = elemIt->next();
2565 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2570 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2571 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2573 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2574 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2575 while ( elemIt->more() )
2577 const SMDS_MeshElement* elem = elemIt->next();
2578 elemType.myNodes.resize( elem->NbNodes() );
2580 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2581 for ( int k = 0; itNodes->more(); k++)
2583 const SMDS_MeshNode* node = itNodes->next();
2584 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2587 // creates a corresponding element on existent nodes in new mesh
2588 newElems[ elem->GetID() ] =
2589 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2591 newEditor.ClearLastCreated(); // forget the history
2594 // create groups of just added elements
2595 SMESH::SMESH_Group_var newGroup;
2596 SMESH::ElementType groupType;
2597 if ( theCommonGroups )
2600 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2601 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2602 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2603 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2606 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2608 for( groupType = SMESH::NODE;
2609 groupType < SMESH::NB_ELEMENT_TYPES;
2610 groupType = (SMESH::ElementType)( groupType + 1 ))
2612 if ( curState[ groupType ] <= prevState[ groupType ])
2613 continue; // no elements of groupType added from the i-th mesh
2615 // make a group name
2616 std::string groupName = "Gr";
2617 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2619 CORBA::String_var name = meshSO->GetName();
2623 groupName += typeNames[ groupType ];
2625 // make and fill a group
2626 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2627 std::vector< const SMDS_MeshElement* > & elemVec =
2628 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2629 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2631 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2633 for ( size_t j = 0; j < elemVec.size(); ++j )
2635 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2636 grpDS->Add( elemVec[j] );
2640 listOfNewGroups.clear();
2641 listOfNewGroups.push_back( newGroup );
2642 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2647 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2651 SMESH::SMESH_GroupBase_ptr group;
2652 CORBA::String_var groupName;
2653 SMESH::long_array_var newIDs = new SMESH::long_array();
2655 // loop on groups of a source mesh
2656 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2657 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2659 group = listOfGroups[iG];
2660 groupType = group->GetType();
2661 groupName = group->GetName();
2662 std::string name = groupName.in();
2664 // convert a list of IDs
2665 newIDs->length( group->Size() );
2666 std::vector< const SMDS_MeshElement* > & elemVec =
2667 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2668 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2670 while ( itGrElems->more() )
2672 const SMDS_MeshElement* elem = itGrElems->next();
2673 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2675 newIDs[ nbElems++ ] = newElem->GetID();
2677 newIDs->length( nbElems );
2679 // check that a current group name and type don't have identical ones in final mesh
2680 listOfNewGroups.clear();
2681 TNameAndType nameAndType( name, groupType );
2682 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2683 if ( anIter == groupsMap.end() )
2685 // add a new group in the mesh
2686 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2687 newGroup->Add( newIDs );
2689 listOfNewGroups.push_back( newGroup );
2690 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2692 else if ( theUniteIdenticalGroups )
2694 // unite identical groups
2695 TListOfNewGroups& aNewGroups = anIter->second;
2696 aNewGroups.front()->Add( newIDs );
2700 // rename identical groups
2701 newGroup = newImpl->CreateGroup( groupType, groupName );
2702 newGroup->Add( newIDs );
2704 TListOfNewGroups& newGroups = anIter->second;
2705 std::string newGroupName;
2706 if ( newGroups.size() == 1 )
2708 newGroupName = name + "_1";
2709 newGroups.front()->SetName( newGroupName.c_str() );
2711 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2712 newGroup->SetName( newGroupName.c_str() );
2713 newGroups.push_back( newGroup );
2716 } // if an IDSource is a mesh
2719 if ( theMergeNodesAndElements ) // merge nodes
2721 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2722 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2723 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2724 /*SeparateCornersAndMedium=*/ false );
2725 newEditor.MergeNodes( groupsOfNodes );
2727 newEditor.MergeEqualElements();
2730 // Update Python script
2731 pythonDump << newMesh << " = " << this
2732 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2733 << theMeshesArray << ", "
2734 << theUniteIdenticalGroups << ", "
2735 << theMergeNodesAndElements << ", "
2736 << TVar( theMergeTolerance ) << ", "
2737 << theMeshToAppendTo << " )";
2739 pPythonDump.reset(); // enable python dump from GetGroups()
2741 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2742 if ( !newMesh->_is_nil() )
2744 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2747 // IPAL21468 Change icon of compound because it need not be computed.
2748 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2749 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2751 newMeshDS->Modified();
2753 return newMesh._retn();
2756 //================================================================================
2758 * \brief Create a mesh by copying a part of another mesh
2759 * \param meshPart - a part of mesh to copy
2760 * \param toCopyGroups - to create in the new mesh groups
2761 * the copied elements belongs to
2762 * \param toKeepIDs - to preserve IDs of the copied elements or not
2763 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2765 //================================================================================
2767 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2768 const char* meshName,
2769 CORBA::Boolean toCopyGroups,
2770 CORBA::Boolean toKeepIDs)
2771 throw ( SALOME::SALOME_Exception )
2773 Unexpect aCatch(SALOME_SalomeException);
2775 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2776 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2778 // 1. Get source mesh
2780 if ( CORBA::is_nil( meshPart ))
2781 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2783 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2784 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2786 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2788 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2790 // 2. Make a new mesh
2792 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2793 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2795 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2796 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2797 if ( !meshSO->_is_nil() )
2799 SetName( meshSO, meshName, "Mesh" );
2800 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2802 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2803 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2804 ::SMESH_MeshEditor::ElemFeatures elemType;
2806 // 3. Get elements to copy
2808 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2809 TIDSortedElemSet srcElems;
2810 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2811 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2814 srcElemIt = srcMeshDS->elementsIterator();
2815 srcNodeIt = srcMeshDS->nodesIterator();
2819 SMESH::long_array_var ids = meshPart->GetIDs();
2820 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2822 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2823 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2824 srcElems.insert( elem );
2828 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2829 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2830 srcElems.insert( elem );
2832 if ( srcElems.empty() )
2833 return newMesh._retn();
2835 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2836 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2841 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2842 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2843 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2845 const SMDS_MeshNode *nSrc, *nTgt;
2846 vector< const SMDS_MeshNode* > nodes;
2847 while ( srcElemIt->more() )
2849 const SMDS_MeshElement * elem = srcElemIt->next();
2851 nodes.resize( elem->NbNodes());
2852 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2854 for ( iN = 0; nIt->more(); ++iN )
2856 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2857 nTgt = newMeshDS->FindNode( nSrc->GetID());
2859 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2864 for ( iN = 0; nIt->more(); ++iN )
2866 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2867 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2869 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2870 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2874 if ( elem->GetType() != SMDSAbs_Node )
2876 elemType.Init( elem, /*basicOnly=*/false );
2877 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2879 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2880 if ( toCopyGroups && !toKeepIDs )
2881 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2883 } // while ( srcElemIt->more() )
2885 // 4(b). Copy free nodes
2887 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2889 while ( srcNodeIt->more() )
2891 nSrc = srcNodeIt->next();
2892 if ( nSrc->NbInverseElements() == 0 )
2895 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2897 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2904 int nbNewGroups = 0;
2907 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2908 while ( gIt->more() )
2910 SMESH_Group* group = gIt->next();
2911 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2913 // Check group type. We copy nodal groups containing nodes of copied element
2914 SMDSAbs_ElementType groupType = groupDS->GetType();
2915 if ( groupType != SMDSAbs_Node &&
2916 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2917 continue; // group type differs from types of meshPart
2919 // Find copied elements in the group
2920 vector< const SMDS_MeshElement* > groupElems;
2921 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2924 const SMDS_MeshElement* foundElem;
2925 if ( groupType == SMDSAbs_Node )
2927 while ( eIt->more() )
2928 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2929 groupElems.push_back( foundElem );
2933 while ( eIt->more() )
2934 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2935 groupElems.push_back( foundElem );
2940 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2941 if ( e2eMap.empty() ) continue;
2942 int minID = e2eMap.begin()->first->GetID();
2943 int maxID = e2eMap.rbegin()->first->GetID();
2944 TE2EMap::iterator e2e;
2945 while ( eIt->more() && groupElems.size() < e2eMap.size())
2947 const SMDS_MeshElement* e = eIt->next();
2948 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2949 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2950 groupElems.push_back( e2e->second );
2954 if ( !groupElems.empty() )
2956 SMESH::SMESH_Group_var newGroupObj =
2957 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2958 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2960 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2961 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2962 for ( unsigned i = 0; i < groupElems.size(); ++i )
2963 smdsGroup.Add( groupElems[i] );
2971 newMeshDS->Modified();
2973 *pyDump << newMesh << " = " << this
2974 << ".CopyMesh( " << meshPart << ", "
2975 << "'" << meshName << "', "
2976 << toCopyGroups << ", "
2977 << toKeepIDs << ")";
2979 pyDumpDeleter.reset(); // allow dump in GetGroups()
2981 if ( nbNewGroups > 0 ) // dump created groups
2982 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2984 return newMesh._retn();
2988 namespace // utils for CopyMeshWithGeom()
2990 typedef std::map< std::string, std::string > TStr2StrMap;
2991 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
2992 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
2993 typedef std::map< std::string, int > TName2IndexMap;
2995 //================================================================================
2997 * \brief Return a new sub-shape corresponding to an old one
2999 //================================================================================
3003 SMESH_Mesh_i* mySrcMesh_i;
3004 SMESH_Mesh_i* myNewMesh_i;
3005 SMESH_Gen_i* myGen_i;
3009 TStr2StrMap myOld2NewEntryMap; // map of study entries
3011 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3012 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3013 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3016 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3018 // not directly relating to shape search
3019 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3021 //================================================================================
3023 * \brief Constructor
3025 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3026 SMESH_Mesh_i* newMesh_i,
3027 SMESH_Gen_i* smeshGen_i )
3028 : mySrcMesh_i( srcMesh_i ),
3029 myNewMesh_i( newMesh_i ),
3030 myGen_i ( smeshGen_i ),
3031 myToPublish( smeshGen_i->IsEnablePublish() ),
3032 myGIPMapDone( false )
3034 // retrieve from the study shape mapping made thanks to
3035 // "Set presentation parameters and sub-shapes from arguments" option
3037 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3038 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3039 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3040 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3041 if ( newSO->_is_nil() )
3043 myToPublish = false;
3046 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3048 CORBA::String_var oldEntry = oldSO->GetID();
3049 CORBA::String_var newEntry = newSO->GetID();
3050 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3051 std::string( newEntry.in() )));
3052 std::string newMainEntry = newEntry.in();
3054 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3055 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3056 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3057 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3058 /*groupsOnly=*/false );
3059 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3061 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3062 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3063 bool refFound = false;
3064 for ( ; anIter->More(); anIter->Next() )
3066 SALOMEDS::SObject_wrap so = anIter->Value();
3067 if ( so->ReferencedObject( oldSO.inout() ))
3069 oldEntry = oldSO->GetID();
3070 newEntry = newSO->GetID();
3071 if (( refFound = ( newMainEntry != oldEntry.in() )))
3072 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3073 std::string( newEntry.in() )));
3078 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3079 if ( father->_is_equivalent( mainShapeNew ))
3081 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3082 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3083 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3084 CORBA::String_var name = newSO->GetName();
3086 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3092 //================================================================================
3094 * \brief Find a new sub-shape corresponding to an old one
3096 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3099 return GEOM::GEOM_Object::_duplicate( oldShape );
3101 GEOM::GEOM_Object_var newShape;
3103 if ( CORBA::is_nil( oldShape ))
3104 return newShape._retn();
3106 if ( !isChildOfOld( oldShape ))
3107 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3109 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3110 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3112 // try to find by entry or name
3115 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3116 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3117 if ( o2nID != myOld2NewEntryMap.end() )
3119 newShape = getShapeByEntry( o2nID->second );
3121 if ( newShape->_is_nil() )
3123 CORBA::String_var name = oldShape->GetName();
3124 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3125 if ( n2ind != myName2SubshapeIndex.end() )
3127 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3128 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3129 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3130 if ( oldIndices->length() == 0 ||
3131 newIndices->length() == 0 ||
3132 getShapeType( myNewMesh_i, newIndices[0] ) !=
3133 getShapeType( mySrcMesh_i, oldIndices[0] ))
3134 newShape = GEOM::GEOM_Object::_nil();
3139 if ( newShape->_is_nil() )
3141 // try to construct a new sub-shape using myGIPMap
3143 std::vector< int > newIndices;
3144 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3145 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3147 findNewIDs( oldIndices[i], newIndices );
3149 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3152 newShape = getInPlace( oldShape );
3154 if ( !newIndices.empty() && newShape->_is_nil() )
3156 // search for a sub-shape with same ids
3157 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3158 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3159 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3160 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3162 if ( newShape->_is_nil() )
3165 // create a new shape
3166 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3168 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3170 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3171 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3173 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3174 newIndicesList->length( newIndices.size() );
3175 for ( size_t i = 0; i < newIndices.size(); ++i )
3176 newIndicesList[ i ] = newIndices[ i ];
3177 grOp->UnionIDs( newShape, newIndicesList );
3181 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3182 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3191 if ( !newShape->_is_nil() && myToPublish )
3193 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3194 if ( !newEntry.in() || !newEntry.in()[0] )
3196 CORBA::String_var name = oldShape->GetName();
3197 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3198 newEntry = newShape->GetStudyEntry();
3199 oldEntry = oldShape->GetStudyEntry();
3200 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3201 std::string( newEntry.in() )));
3205 return newShape._retn();
3208 //================================================================================
3210 * \brief Return a study entry of a new shape by study entry of the old one
3212 std::string FindNew( const std::string & oldEntry )
3217 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3218 if ( o2nID != myOld2NewEntryMap.end() )
3219 return o2nID->second;
3221 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3222 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3225 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3226 if ( newShape->_is_nil() )
3227 return std::string();
3229 CORBA::String_var newEntry = newShape->GetStudyEntry();
3230 return newEntry.in();
3233 //================================================================================
3235 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3236 * Return zero if not found or there are more than one new ID
3238 int FindNew( int oldID )
3247 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3249 if ( myGIPMap[ oldID ].length() == 1 )
3251 newID = myGIPMap[ oldID ][ 0 ];
3253 else if ( myGIPMap[ oldID ].length() > 1 &&
3254 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3256 // select a meshed VERTEX
3257 SMESH_subMesh* newSM;
3258 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3259 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3260 ( !newSM->IsEmpty() ))
3261 newID = myGIPMap[ oldID ][ i ];
3267 //================================================================================
3269 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3270 * Return zero if the old shape is not kept as is in the new shape.
3272 int FindNewNotChanged( SMESH_subMesh* oldSM )
3275 return oldSM->GetId();
3277 int newID = FindNew( oldSM->GetId() );
3281 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3285 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3286 // one new sub-shape of the same type.
3288 if ( oldSM->DependsOn().size() !=
3289 newSM->DependsOn().size() )
3292 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3293 while ( srcSMIt->more() )
3295 oldSM = srcSMIt->next();
3296 int newSubID = FindNew( oldSM->GetId() );
3297 if ( getShapeType( myNewMesh_i, newSubID ) !=
3298 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3304 //================================================================================
3306 * \brief Return shape by study entry
3308 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3310 GEOM::GEOM_Object_var shape;
3311 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3312 if ( !so->_is_nil() )
3314 CORBA::Object_var obj = so->GetObject();
3315 shape = GEOM::GEOM_Object::_narrow( obj );
3317 return shape._retn();
3320 //================================================================================
3322 * \brief Fill myGIPMap by calling GetInPlaceMap()
3326 if ( !myGIPMapDone )
3328 myGIPMapDone = true;
3330 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3331 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3332 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3333 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3336 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3340 myGIPMap = new GEOM::ListOfListOfLong();
3345 //================================================================================
3347 * \brief Get new sub-shape by calling GetInPlace()
3349 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3351 GEOM::GEOM_Object_var newShape;
3353 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3354 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3355 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3358 newShape = op->GetInPlace( mainShapeNew, oldShape );
3363 return newShape._retn();
3366 //================================================================================
3368 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3369 * number of found IDs
3371 int findNewIDs( int oldID, std::vector< int >& newIDs )
3373 size_t prevNbIDs = newIDs.size();
3375 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3377 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3378 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3380 return newIDs.size() - prevNbIDs;
3383 //================================================================================
3385 * \brief Check if an object relates to the old shape
3387 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3389 if ( CORBA::is_nil( oldShape ))
3391 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3392 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3393 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3394 mainShapeOld1->_is_equivalent( oldShape ));
3397 //================================================================================
3399 * \brief Return shape type by shape ID
3401 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3403 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3404 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3405 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3408 //================================================================================
3410 * \brief Store a source sub-shape for which a counterpart not found and
3411 * a smesh object invalid due to that
3413 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3414 SALOMEDS::SObject_wrap smeshSO )
3416 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3417 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3419 CORBA::String_var smeshEntry = smeshSO->GetID();
3420 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3424 //================================================================================
3426 * \brief Store a source sub-shape for which a counterpart not found and
3427 * a smesh object invalid due to that
3429 void AddInvalid( std::string geomEntry,
3430 SALOMEDS::SObject_wrap smeshSO )
3432 if ( !geomEntry.empty() )
3434 CORBA::String_var smeshEntry = smeshSO->GetID();
3435 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3439 //================================================================================
3441 * \brief Store a source sub-shape for which a counterpart not found and
3442 * a smesh object invalid due to that
3444 void AddInvalid( int oldGeomID,
3445 SALOMEDS::SObject_wrap smeshSO )
3447 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3448 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3451 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3452 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3454 SMESH_Comment geomName( typeName[ shapeType ]);
3455 geomName << " #" << oldGeomID;
3457 CORBA::String_var smeshEntry = smeshSO->GetID();
3458 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3461 //================================================================================
3463 * \brief Return entries of a source sub-shape for which a counterpart not found and
3464 * of smesh objects invalid due to that
3466 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3467 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3470 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3471 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3473 nbSO += 1 + entry2entrySet->second.size();
3475 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3476 theInvalidEntries->length ( nbSO );
3477 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3479 entry2entrySet = myInvalidMap.begin();
3480 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3482 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3484 std::set< std::string > & entrySet = entry2entrySet->second;
3485 std::set< std::string >::iterator entry = entrySet.begin();
3486 for ( ; entry != entrySet.end(); ++entry )
3488 theInvalidEntries[ iEntry++ ] = entry->c_str();
3490 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3491 if ( !so->_is_nil() )
3492 theInvalidMeshSObjects[ iSO++ ] = so;
3497 }; // struct ShapeMapper
3499 //================================================================================
3501 * \brief Append an item to a CORBA sequence
3503 template < class CORBA_seq, class ITEM >
3504 void append( CORBA_seq& seq, ITEM item )
3506 if ( !CORBA::is_nil( item ))
3508 seq->length( 1 + seq->length() );
3509 seq[ seq->length() - 1 ] = item;
3512 } // namespace // utils for CopyMeshWithGeom()
3514 //================================================================================
3516 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3517 * \param [in] sourceMesh - a mesh to copy
3518 * \param [in] newGeometry - a new geometry
3519 * \param [in] toCopyGroups - to create groups in the new mesh
3520 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3521 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3522 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3523 * \param [out] newMesh - return a new mesh
3524 * \param [out] newGroups - return new groups
3525 * \param [out] newSubmeshes - return new sub-meshes
3526 * \param [out] newHypotheses - return new algorithms and hypotheses
3527 * \param [out] invalidEntries - return study entries of objects whose
3528 * counterparts are not found in the newGeometry, followed by entries
3529 * of mesh sub-objects that are invalid because they depend on a not found
3530 * preceding sub-shape
3531 * \return CORBA::Boolean - is a success
3533 //================================================================================
3535 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3536 GEOM::GEOM_Object_ptr theNewGeometry,
3537 const char* theMeshName,
3538 CORBA::Boolean theToCopyGroups,
3539 CORBA::Boolean theToReuseHypotheses,
3540 CORBA::Boolean theToCopyElements,
3541 SMESH::SMESH_Mesh_out theNewMesh,
3542 SMESH::ListOfGroups_out theNewGroups,
3543 SMESH::submesh_array_out theNewSubmeshes,
3544 SMESH::ListOfHypothesis_out theNewHypotheses,
3545 SMESH::string_array_out theInvalidEntries)
3546 throw ( SALOME::SALOME_Exception )
3548 if ( CORBA::is_nil( theSourceMesh ) ||
3549 CORBA::is_nil( theNewGeometry ))
3550 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3552 if ( !theSourceMesh->HasShapeToMesh() )
3553 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3558 TPythonDump pyDump; // prevent dump from CreateMesh()
3560 theNewMesh = CreateMesh( theNewGeometry );
3561 theNewGroups = new SMESH::ListOfGroups();
3562 theNewSubmeshes = new SMESH::submesh_array();
3563 theNewHypotheses = new SMESH::ListOfHypothesis();
3564 theInvalidEntries = new SMESH::string_array();
3566 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3568 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3569 GEOM::GEOM_Object_var geom, newGeom;
3570 SALOMEDS::SObject_wrap so;
3572 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3573 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3576 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3578 // treat hypotheses of mesh and sub-meshes
3579 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3580 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3582 bool isSubMesh = ( iSM < smList->length() );
3585 // create a new sub-mesh
3586 SMESH::SMESH_subMesh_var newSM;
3587 geom = smList[iSM]->GetSubShape();
3588 so = ObjectToSObject( smList[iSM] );
3589 CORBA::String_var name;
3590 if ( !so->_is_nil() )
3591 name = so->GetName();
3592 newGeom = shapeMapper.FindNew( geom );
3593 if ( newGeom->_is_nil() )
3595 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3596 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3601 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3603 append( theNewSubmeshes, newSM );
3605 if ( newGeom->_is_nil() )
3606 continue; // don't assign hypotheses
3610 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3612 so = ObjectToSObject( theNewMesh );
3613 SetName( so, theMeshName, "Mesh" );
3616 // assign hypotheses
3617 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3618 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3620 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3621 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3623 // get geometry hyp depends on
3624 std::vector< std::string > entryArray;
3625 std::vector< int > subIDArray;
3626 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3628 if ( !theToReuseHypotheses || dependsOnGeom )
3630 // create a new hypothesis
3631 CORBA::String_var type = hyp->GetName();
3632 CORBA::String_var lib = hyp->GetLibName();
3633 CORBA::String_var data = hyp_i->SaveTo();
3636 hyp = CreateHypothesis( type, lib );
3637 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3638 hyp_i->LoadFrom( data.in() );
3639 append( theNewHypotheses, hyp );
3643 // update geometry hyp depends on
3644 if ( dependsOnGeom )
3646 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3648 if ( !entryArray[ iGeo ].empty() )
3650 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3651 if ( newEntry.empty() )
3654 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3655 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3657 entryArray[ iGeo ] = newEntry;
3660 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3662 if ( subIDArray[ iGeo ] > 0 )
3664 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3668 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3669 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3671 subIDArray[ iGeo ] = newID;
3674 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3678 CORBA::String_var errorText;
3679 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3680 if ( errorText.in()[0] )
3683 } // loop on hypotheses
3684 } // loop on sub-meshes and mesh
3687 // copy mesh elements, keeping IDs
3688 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3689 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3691 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3692 ::SMESH_MeshEditor::ElemFeatures elemData;
3694 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3695 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3696 /*vertexLast=*/false);
3697 while ( srcSMIt->more() )
3699 SMESH_subMesh* srcSM = srcSMIt->next();
3700 if ( srcSM->IsEmpty() )
3701 continue; // not yet computed
3702 int newID = shapeMapper.FindNewNotChanged( srcSM );
3706 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3707 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3708 while ( nIt->more() )
3710 SMESH_NodeXYZ node( nIt->next() );
3711 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3713 const SMDS_PositionPtr pos = node->GetPosition();
3714 const double* uv = pos->GetParameters();
3715 switch ( pos->GetTypeOfPosition() )
3717 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3718 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3719 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3720 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3724 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3725 while( eIt->more() )
3727 const SMDS_MeshElement* e = eIt->next();
3728 elemData.Init( e, /*basicOnly=*/false );
3729 elemData.SetID( e->GetID() );
3730 elemData.myNodes.resize( e->NbNodes() );
3731 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3733 for ( iN = 0; nnIt->more(); ++iN )
3735 const SMDS_MeshNode* srcNode = nnIt->next();
3736 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3737 if ( !elemData.myNodes[ iN ])
3740 if ( iN == elemData.myNodes.size() )
3741 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3742 newMeshDS->SetMeshElementOnShape( newElem, newID );
3744 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3745 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3748 newMeshDS->Modified();
3754 TStr2StrMap old2newGroupMap;
3756 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3758 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3759 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3760 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3762 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3763 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3764 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3766 CORBA::String_var name = groups[ i ]->GetName();
3767 SMESH::ElementType elemType = groups[ i ]->GetType();
3769 SMESH::SMESH_GroupBase_var newGroup;
3771 if ( !stdlGroup->_is_nil() )
3773 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3775 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3776 const bool isElem = ( elemType != SMESH::NODE );
3777 CORBA::ULong iE = 0;
3778 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3779 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3781 if ( iE < elemIDs->length() )
3783 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3784 stdlGroup->Add( elemIDs );
3785 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3789 else if ( !geomGroup->_is_nil() )
3791 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3792 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3793 if ( newGeom->_is_nil() )
3795 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3796 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3801 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3804 else if ( !fltrGroup->_is_nil() )
3806 // replace geometry in a filter
3807 SMESH::Filter_var filter = fltrGroup->GetFilter();
3808 SMESH::Filter::Criteria_var criteria;
3809 filter->GetCriteria( criteria.out() );
3811 bool isMissingGroup = false;
3812 std::vector< std::string > badEntries;
3814 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3816 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3817 switch ( criteria[ iCr ].Type )
3819 case SMESH::FT_BelongToMeshGroup:
3821 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3822 btgg->SetGroupID( thresholdID );
3823 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3824 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3825 if ( refGroupSO->_is_nil() )
3827 CORBA::String_var refID = refGroupSO->GetID();
3828 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3829 if ( o2nID == old2newGroupMap.end() )
3831 isMissingGroup = true; // corresponding new group not yet created
3834 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3836 if ( o2nID->second.empty() ) // new referred group is invalid
3837 badEntries.push_back( refID.in() );
3840 case SMESH::FT_BelongToGeom:
3841 case SMESH::FT_BelongToPlane:
3842 case SMESH::FT_BelongToCylinder:
3843 case SMESH::FT_BelongToGenSurface:
3844 case SMESH::FT_LyingOnGeom:
3846 std::string newID = shapeMapper.FindNew( thresholdID );
3847 criteria[ iCr ].ThresholdID = newID.c_str();
3848 if ( newID.empty() )
3849 badEntries.push_back( thresholdID );
3852 case SMESH::FT_ConnectedElements:
3854 if ( thresholdID && thresholdID[0] )
3856 std::string newID = shapeMapper.FindNew( thresholdID );
3857 criteria[ iCr ].ThresholdID = newID.c_str();
3858 if ( newID.empty() )
3859 badEntries.push_back( thresholdID );
3865 } // loop on criteria
3867 if ( isMissingGroup && i < nbGroups )
3869 // to treat the group again
3870 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3874 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3875 newFilter->SetCriteria( criteria );
3877 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3878 newFilter->UnRegister();
3880 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3881 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3882 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3884 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3886 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3889 if ( !badEntries.empty() )
3892 } // treat a group on filter
3894 append( theNewGroups, newGroup );
3896 // fill old2newGroupMap
3897 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3898 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3899 if ( !srcSO->_is_nil() )
3901 CORBA::String_var srcID, newID("");
3902 srcID = srcSO->GetID();
3903 if ( !newSO->_is_nil() )
3904 newID = newSO->GetID();
3905 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3906 std::string( newID.in() )));
3909 if ( newGroup->_is_nil() )
3914 newMeshDS->CompactMesh();
3917 if ( !theMeshName || !theMeshName[0] )
3919 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3920 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3921 CORBA::String_var oldName = soOld->GetName();
3922 SetName( soNew, oldName.in(), "Mesh" );
3924 // mark invalid objects
3925 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3927 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3928 highLightInvalid( invalidSObjects[i].in(), true );
3931 << theNewMesh << ", "
3932 << theNewGroups << ", "
3933 << *theNewSubmeshes.ptr() << ", "
3934 << *theNewHypotheses.ptr() << ", "
3935 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3936 << theSourceMesh << ", "
3937 << theNewGeometry << ", "
3938 << "'" << theMeshName << "', "
3939 << theToCopyGroups << ", "
3940 << theToReuseHypotheses << ", "
3941 << theToCopyElements << " )";
3943 SMESH_CATCH( SMESH::throwCorbaException );
3948 //================================================================================
3950 * \brief Get version of MED format being used.
3952 //================================================================================
3954 char* SMESH_Gen_i::GetMEDFileVersion()
3956 MED::TInt majeur, mineur, release;
3957 majeur = mineur = release = 0;
3958 MED::GetVersionRelease(majeur, mineur, release);
3959 std::ostringstream version;
3960 version << majeur << "." << mineur << "." << release;
3961 return CORBA::string_dup( version.str().c_str() );
3964 //================================================================================
3966 * SMESH_Gen_i::GetMEDVersion
3968 * Get MED version of the file by its name
3970 //================================================================================
3971 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
3973 std::string version = MED::GetMEDVersion( theFileName );
3974 return CORBA::string_dup( version.c_str() );
3977 //================================================================================
3979 * SMESH_Gen_i::CheckCompatibility
3981 * Check compatibility of file with MED format being used, read only.
3983 //================================================================================
3984 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
3986 return MED::CheckCompatibility( theFileName );
3989 //================================================================================
3991 * SMESH_Gen_i::CheckWriteCompatibility
3993 * Check compatibility of file with MED format being used, for append on write.
3995 //================================================================================
3996 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
3998 return MED::CheckCompatibility( theFileName, true );
4001 //================================================================================
4003 * SMESH_Gen_i::GetMeshNames
4005 * Get names of meshes defined in file with the specified name
4007 //================================================================================
4008 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4010 //MESSAGE("GetMeshNames " << theFileName);
4011 SMESH::string_array_var aResult = new SMESH::string_array();
4012 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4014 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4015 //MESSAGE("---" << aNbMeshes);
4017 aResult->length( aNbMeshes );
4018 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4019 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4020 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4023 return aResult._retn();
4026 //=============================================================================
4030 * Save SMESH module's data
4032 //=============================================================================
4033 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4038 Kernel_Utils::Localizer loc;
4040 if (!myStudyContext)
4043 // Store study contents as a set of python commands
4046 SALOMEDS::Study_var aStudy = getStudyServant();
4048 // Declare a byte stream
4049 SALOMEDS::TMPFile_var aStreamFile;
4051 // Obtain a temporary dir
4052 TCollection_AsciiString tmpDir =
4053 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4055 // Create a sequence of files processed
4056 SALOMEDS_Tool::ListOfFiles aFileSeq;
4057 aFileSeq.reserve( NUM_TMP_FILES );
4059 TCollection_AsciiString aStudyName( "" );
4061 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4063 // Set names of temporary files
4064 TCollection_AsciiString filename =
4065 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4066 TCollection_AsciiString meshfile =
4067 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4068 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4069 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4070 filename = tmpDir + filename;
4071 meshfile = tmpDir + meshfile;
4074 HDFdataset* aDataset;
4075 HDFgroup* aTopGroup;
4077 HDFgroup* aSubGroup;
4078 HDFgroup* aSubSubGroup;
4079 hdf_size aSize[ 1 ];
4082 //Remove the files if they exist: BugID: 11225
4083 #ifndef WIN32 /* unix functionality */
4084 TCollection_AsciiString cmd("rm -f \"");
4086 TCollection_AsciiString cmd("del /F \"");
4096 system(cmd.ToCString());
4098 // MED writer to be used by storage process
4099 DriverMED_W_SMESHDS_Mesh myWriter;
4100 myWriter.SetFile( meshfile.ToCString() );
4103 // SetStoreName() to groups before storing hypotheses to let them refer to
4104 // groups using "store name", which is "Group <group_persistent_id>"
4106 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4107 for ( ; itBig->More(); itBig->Next() ) {
4108 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4109 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4110 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4111 if ( !CORBA::is_nil( anObject ) ) {
4112 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4113 if ( !myMesh->_is_nil() ) {
4114 myMesh->Load(); // load from study file if not yet done
4115 TPythonDump pd; // not to dump GetGroups()
4116 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4117 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4119 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4122 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4123 int anId = myStudyContext->findId( string( objStr.in() ) );
4125 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4126 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4127 aGrpBaseDS->SetStoreName( grpName );
4137 // ---> create HDF file
4138 aFile = new HDFfile( (char*) filename.ToCString() );
4139 aFile->CreateOnDisk();
4141 // --> iterator for top-level objects
4142 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4143 for ( ; itBig->More(); itBig->Next() ) {
4144 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4146 // --> hypotheses root branch (only one for the study)
4147 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4148 // create hypotheses root HDF group
4149 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4150 aTopGroup->CreateOnDisk();
4152 // iterator for all hypotheses
4153 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4154 for ( ; it->More(); it->Next() ) {
4155 SALOMEDS::SObject_wrap mySObject = it->Value();
4156 CORBA::Object_var anObject = SObjectToObject( mySObject );
4157 if ( !CORBA::is_nil( anObject ) ) {
4158 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4159 if ( !myHyp->_is_nil() ) {
4160 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4162 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4163 std::string hypname = hn.in();
4164 std::string libname = ln.in();
4166 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4167 // WIN32 and ".so" for X-system) must be deleted
4168 int libname_len = libname.length();
4170 if( libname_len > 4 )
4171 libname.resize( libname_len - 4 );
4173 // PAL17753 (Regression: missing hypothesis in restored study)
4174 // "lib" also should be removed from the beginning
4175 //if( libname_len > 3 )
4176 //libname.resize( libname_len - 3 );
4177 if( libname_len > 6 )
4178 libname = libname.substr( 3, libname_len - 3 - 3 );
4180 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4181 CORBA::String_var hypdata = myImpl->SaveTo();
4182 int id = myStudyContext->findId( string( objStr.in() ));
4184 // for each hypothesis create HDF group basing on its id
4185 char hypGrpName[30];
4186 sprintf( hypGrpName, "Hypothesis %d", id );
4187 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4188 aGroup->CreateOnDisk();
4189 // --> type name of hypothesis
4190 aSize[ 0 ] = hypname.length() + 1;
4191 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4192 aDataset->CreateOnDisk();
4193 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4194 aDataset->CloseOnDisk();
4195 // --> server plugin library name of hypothesis
4196 aSize[ 0 ] = libname.length() + 1;
4197 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4198 aDataset->CreateOnDisk();
4199 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4200 aDataset->CloseOnDisk();
4201 // --> persistent data of hypothesis
4202 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4203 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4204 aDataset->CreateOnDisk();
4205 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4206 aDataset->CloseOnDisk();
4207 // close hypothesis HDF group
4208 aGroup->CloseOnDisk();
4213 // close hypotheses root HDF group
4214 aTopGroup->CloseOnDisk();
4216 // --> algorithms root branch (only one for the study)
4217 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4218 // create algorithms root HDF group
4219 aTopGroup = new HDFgroup( "Algorithms", aFile );
4220 aTopGroup->CreateOnDisk();
4222 // iterator for all algorithms
4223 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4224 for ( ; it->More(); it->Next() ) {
4225 SALOMEDS::SObject_wrap mySObject = it->Value();
4226 CORBA::Object_var anObject = SObjectToObject( mySObject );
4227 if ( !CORBA::is_nil( anObject ) ) {
4228 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4229 if ( !myHyp->_is_nil() ) {
4230 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4232 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4233 std::string hypname = hn.in();
4234 std::string libname = ln.in();
4236 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4237 // WIN32 and ".so" for X-system) must be deleted
4238 int libname_len = libname.length();
4240 if( libname_len > 4 )
4241 libname.resize( libname_len - 4 );
4243 // PAL17753 (Regression: missing hypothesis in restored study)
4244 // "lib" also should be removed from the beginning
4245 //if( libname_len > 3 )
4246 //libname.resize( libname_len - 3 );
4247 if( libname_len > 6 )
4248 libname = libname.substr( 3, libname_len - 3 - 3 );
4250 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4251 CORBA::String_var hypdata = myImpl->SaveTo();
4252 int id = myStudyContext->findId( string( objStr.in() ) );
4254 // for each algorithm create HDF group basing on its id
4255 char hypGrpName[30];
4256 sprintf( hypGrpName, "Algorithm %d", id );
4257 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4258 aGroup->CreateOnDisk();
4259 // --> type name of algorithm
4260 aSize[0] = hypname.length() + 1;
4261 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4262 aDataset->CreateOnDisk();
4263 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4264 aDataset->CloseOnDisk();
4265 // --> server plugin library name of hypothesis
4266 aSize[0] = libname.length() + 1;
4267 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4268 aDataset->CreateOnDisk();
4269 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4270 aDataset->CloseOnDisk();
4271 // --> persistent data of algorithm
4272 aSize[0] = strlen( hypdata.in() ) + 1;
4273 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4274 aDataset->CreateOnDisk();
4275 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4276 aDataset->CloseOnDisk();
4277 // close algorithm HDF group
4278 aGroup->CloseOnDisk();
4283 // close algorithms root HDF group
4284 aTopGroup->CloseOnDisk();
4286 // --> mesh objects roots branches
4287 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4288 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4289 if ( !CORBA::is_nil( anObject ) ) {
4290 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4291 if ( !myMesh->_is_nil() ) {
4292 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4294 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4295 int id = myStudyContext->findId( string( objStr.in() ) );
4296 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4297 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4298 bool hasShape = myLocMesh.HasShapeToMesh();
4300 // for each mesh open the HDF group basing on its id
4301 char meshGrpName[ 30 ];
4302 sprintf( meshGrpName, "Mesh %d", id );
4303 aTopGroup = new HDFgroup( meshGrpName, aFile );
4304 aTopGroup->CreateOnDisk();
4306 // --> put dataset to hdf file which is a flag that mesh has data
4307 string strHasData = "0";
4308 // check if the mesh is not empty
4309 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4310 // write mesh data to med file
4311 myWriter.SetMesh( mySMESHDSMesh );
4312 myWriter.SetMeshId( id );
4315 aSize[ 0 ] = strHasData.length() + 1;
4316 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4317 aDataset->CreateOnDisk();
4318 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4319 aDataset->CloseOnDisk();
4322 // for each mesh open the HDF group basing on its auto color parameter
4323 char meshAutoColorName[ 30 ];
4324 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4326 anAutoColor[0] = myImpl->GetAutoColor();
4328 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4329 aDataset->CreateOnDisk();
4330 aDataset->WriteOnDisk( anAutoColor );
4331 aDataset->CloseOnDisk();
4333 // issue 0020693. Store _isModified flag
4334 int isModified = myLocMesh.GetIsModified();
4336 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4337 aDataset->CreateOnDisk();
4338 aDataset->WriteOnDisk( &isModified );
4339 aDataset->CloseOnDisk();
4341 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4342 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4344 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4345 aDataset->CreateOnDisk();
4346 aDataset->WriteOnDisk( &meshPersistentId );
4347 aDataset->CloseOnDisk();
4349 // write reference on a shape if exists
4350 SALOMEDS::SObject_wrap myRef;
4351 bool shapeRefFound = false;
4352 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4354 SALOMEDS::SObject_wrap myShape;
4355 bool ok = myRef->ReferencedObject( myShape.inout() );
4357 CORBA::Object_var shapeObj = myShape->GetObject();
4358 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4359 CORBA::String_var myRefOnObject = myShape->GetID();
4360 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4361 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4362 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4363 aDataset->CreateOnDisk();
4364 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4365 aDataset->CloseOnDisk();
4371 std::string info = myImpl->FileInfoToString();
4372 if ( !info.empty() )
4374 aSize[ 0 ] = info.size();
4375 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4376 aDataset->CreateOnDisk();
4377 aDataset->WriteOnDisk( (char*) info.data() );
4378 aDataset->CloseOnDisk();
4381 // write applied hypotheses if exist
4382 SALOMEDS::SObject_wrap myHypBranch;
4383 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4384 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4385 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4387 if ( found && (shapeRefFound || !hasShape) ) {
4388 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4389 aGroup->CreateOnDisk();
4391 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4393 for ( ; it->More(); it->Next() ) {
4394 SALOMEDS::SObject_wrap mySObject = it->Value();
4395 SALOMEDS::SObject_wrap myRefOnHyp;
4396 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4398 // san - it is impossible to recover applied hypotheses
4399 // using their entries within Load() method,
4400 // for there are no AttributeIORs in the study when Load() is working.
4401 // Hence, it is better to store persistent IDs of hypotheses as references to them
4403 //string myRefOnObject = myRefOnHyp->GetID();
4404 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4405 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4406 int id = myStudyContext->findId( string( objStr.in() ) );
4407 //if ( myRefOnObject.length() > 0 ) {
4408 //aSize[ 0 ] = myRefOnObject.length() + 1;
4409 char hypName[ 30 ], hypId[ 30 ];
4410 sprintf( hypName, "Hyp %d", ++hypNb );
4411 sprintf( hypId, "%d", id );
4412 aSize[ 0 ] = strlen( hypId ) + 1;
4413 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4414 aDataset->CreateOnDisk();
4415 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4416 aDataset->WriteOnDisk( hypId );
4417 aDataset->CloseOnDisk();
4421 aGroup->CloseOnDisk();
4424 // write applied algorithms if exist
4425 SALOMEDS::SObject_wrap myAlgoBranch;
4426 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4427 myAlgoBranch.inout() );
4428 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4429 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4431 if ( found && (shapeRefFound || !hasShape)) {
4432 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4433 aGroup->CreateOnDisk();
4435 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4437 for ( ; it->More(); it->Next() ) {
4438 SALOMEDS::SObject_wrap mySObject = it->Value();
4439 SALOMEDS::SObject_wrap myRefOnAlgo;
4440 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4442 // san - it is impossible to recover applied algorithms
4443 // using their entries within Load() method,
4444 // for there are no AttributeIORs in the study when Load() is working.
4445 // Hence, it is better to store persistent IDs of algorithms as references to them
4447 //string myRefOnObject = myRefOnAlgo->GetID();
4448 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4449 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4450 int id = myStudyContext->findId( string( objStr.in() ) );
4451 //if ( myRefOnObject.length() > 0 ) {
4452 //aSize[ 0 ] = myRefOnObject.length() + 1;
4453 char algoName[ 30 ], algoId[ 30 ];
4454 sprintf( algoName, "Algo %d", ++algoNb );
4455 sprintf( algoId, "%d", id );
4456 aSize[ 0 ] = strlen( algoId ) + 1;
4457 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4458 aDataset->CreateOnDisk();
4459 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4460 aDataset->WriteOnDisk( algoId );
4461 aDataset->CloseOnDisk();
4465 aGroup->CloseOnDisk();
4468 // --> submesh objects sub-branches
4470 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4471 SALOMEDS::SObject_wrap mySubmeshBranch;
4472 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4474 if ( found ) // check if there is shape reference in submeshes
4476 bool hasShapeRef = false;
4477 SALOMEDS::ChildIterator_wrap itSM =
4478 aStudy->NewChildIterator( mySubmeshBranch );
4479 for ( ; itSM->More(); itSM->Next() ) {
4480 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4481 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4482 mySubRef->ReferencedObject( myShape.inout() );
4483 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4486 { // remove one submesh
4487 if ( shapeRefFound )
4488 { // unassign hypothesis
4489 SMESH::SMESH_subMesh_var mySubMesh =
4490 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4491 if ( !mySubMesh->_is_nil() ) {
4492 int shapeID = mySubMesh->GetId();
4493 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4494 const list<const SMESHDS_Hypothesis*>& hypList =
4495 mySMESHDSMesh->GetHypothesis( S );
4496 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4497 while ( hyp != hypList.end() ) {
4498 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4499 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4503 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4505 } // loop on submeshes of a type
4506 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4507 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4510 } // end check if there is shape reference in submeshes
4512 char name_meshgroup[ 30 ];
4513 if ( i == GetSubMeshOnVertexTag() )
4514 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4515 else if ( i == GetSubMeshOnEdgeTag() )
4516 strcpy( name_meshgroup, "SubMeshes On Edge" );
4517 else if ( i == GetSubMeshOnWireTag() )
4518 strcpy( name_meshgroup, "SubMeshes On Wire" );
4519 else if ( i == GetSubMeshOnFaceTag() )
4520 strcpy( name_meshgroup, "SubMeshes On Face" );
4521 else if ( i == GetSubMeshOnShellTag() )
4522 strcpy( name_meshgroup, "SubMeshes On Shell" );
4523 else if ( i == GetSubMeshOnSolidTag() )
4524 strcpy( name_meshgroup, "SubMeshes On Solid" );
4525 else if ( i == GetSubMeshOnCompoundTag() )
4526 strcpy( name_meshgroup, "SubMeshes On Compound" );
4528 // for each type of submeshes create container HDF group
4529 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4530 aGroup->CreateOnDisk();
4532 // iterator for all submeshes of given type
4533 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4534 for ( ; itSM->More(); itSM->Next() ) {
4535 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4536 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4537 if ( !CORBA::is_nil( anSubObject ))
4539 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4540 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4541 int subid = myStudyContext->findId( string( objStr.in() ) );
4543 // for each mesh open the HDF group basing on its id
4544 char submeshGrpName[ 30 ];
4545 sprintf( submeshGrpName, "SubMesh %d", subid );
4546 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4547 aSubGroup->CreateOnDisk();
4549 // write reference on a shape, already checked if it exists
4550 SALOMEDS::SObject_wrap mySubRef, myShape;
4551 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4552 mySubRef->ReferencedObject( myShape.inout() );
4553 string myRefOnObject = myShape->GetID();
4554 if ( myRefOnObject.length() > 0 ) {
4555 aSize[ 0 ] = myRefOnObject.length() + 1;
4556 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4557 aDataset->CreateOnDisk();
4558 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4559 aDataset->CloseOnDisk();
4562 // write applied hypotheses if exist
4563 SALOMEDS::SObject_wrap mySubHypBranch;
4564 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4565 mySubHypBranch.inout() );
4567 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4568 aSubSubGroup->CreateOnDisk();
4570 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4572 for ( ; it->More(); it->Next() ) {
4573 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4574 SALOMEDS::SObject_wrap myRefOnHyp;
4575 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4577 //string myRefOnObject = myRefOnHyp->GetID();
4578 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4579 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4580 int id = myStudyContext->findId( string( objStr.in() ) );
4581 //if ( myRefOnObject.length() > 0 ) {
4582 //aSize[ 0 ] = myRefOnObject.length() + 1;
4583 char hypName[ 30 ], hypId[ 30 ];
4584 sprintf( hypName, "Hyp %d", ++hypNb );
4585 sprintf( hypId, "%d", id );
4586 aSize[ 0 ] = strlen( hypId ) + 1;
4587 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4588 aDataset->CreateOnDisk();
4589 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4590 aDataset->WriteOnDisk( hypId );
4591 aDataset->CloseOnDisk();
4595 aSubSubGroup->CloseOnDisk();
4598 // write applied algorithms if exist
4599 SALOMEDS::SObject_wrap mySubAlgoBranch;
4600 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4601 mySubAlgoBranch.inout() );
4603 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4604 aSubSubGroup->CreateOnDisk();
4606 SALOMEDS::ChildIterator_wrap it =
4607 aStudy->NewChildIterator( mySubAlgoBranch );
4609 for ( ; it->More(); it->Next() ) {
4610 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4611 SALOMEDS::SObject_wrap myRefOnAlgo;
4612 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4614 //string myRefOnObject = myRefOnAlgo->GetID();
4615 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4616 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4617 int id = myStudyContext->findId( string( objStr.in() ) );
4618 //if ( myRefOnObject.length() > 0 ) {
4619 //aSize[ 0 ] = myRefOnObject.length() + 1;
4620 char algoName[ 30 ], algoId[ 30 ];
4621 sprintf( algoName, "Algo %d", ++algoNb );
4622 sprintf( algoId, "%d", id );
4623 aSize[ 0 ] = strlen( algoId ) + 1;
4624 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4625 aDataset->CreateOnDisk();
4626 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4627 aDataset->WriteOnDisk( algoId );
4628 aDataset->CloseOnDisk();
4632 aSubSubGroup->CloseOnDisk();
4634 // close submesh HDF group
4635 aSubGroup->CloseOnDisk();
4638 // close container of submeshes by type HDF group
4639 aGroup->CloseOnDisk();
4642 // All sub-meshes will be stored in MED file
4643 // .. will NOT (PAL 12992)
4644 //if ( shapeRefFound )
4645 //myWriter.AddAllSubMeshes();
4647 // store submesh order if any
4648 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4649 if ( theOrderIds.size() ) {
4650 char order_list[ 30 ];
4651 strcpy( order_list, "Mesh Order" );
4652 // count number of submesh ids
4654 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4655 for ( ; idIt != theOrderIds.end(); idIt++ )
4656 nbIDs += (*idIt).size();
4657 // number of values = number of IDs +
4658 // number of lists (for separators) - 1
4659 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4660 idIt = theOrderIds.begin();
4661 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4662 const TListOfInt& idList = *idIt;
4663 if (idIt != theOrderIds.begin()) // not first list
4664 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4665 // dump submesh ids from current list
4666 TListOfInt::const_iterator id_smId = idList.begin();
4667 for( ; id_smId != idList.end(); id_smId++ )
4668 smIDs[ i++ ] = *id_smId;
4671 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4673 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4674 aDataset->CreateOnDisk();
4675 aDataset->WriteOnDisk( smIDs );
4676 aDataset->CloseOnDisk();
4681 // groups root sub-branch
4682 SALOMEDS::SObject_wrap myGroupsBranch;
4683 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4684 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4686 char name_group[ 30 ];
4687 if ( i == GetNodeGroupsTag() )
4688 strcpy( name_group, "Groups of Nodes" );
4689 else if ( i == GetEdgeGroupsTag() )
4690 strcpy( name_group, "Groups of Edges" );
4691 else if ( i == GetFaceGroupsTag() )
4692 strcpy( name_group, "Groups of Faces" );
4693 else if ( i == GetVolumeGroupsTag() )
4694 strcpy( name_group, "Groups of Volumes" );
4695 else if ( i == Get0DElementsGroupsTag() )
4696 strcpy( name_group, "Groups of 0D Elements" );
4697 else if ( i == GetBallElementsGroupsTag() )
4698 strcpy( name_group, "Groups of Balls" );
4700 aGroup = new HDFgroup( name_group, aTopGroup );
4701 aGroup->CreateOnDisk();
4703 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4704 for ( ; it->More(); it->Next() ) {
4705 SALOMEDS::SObject_wrap mySObject = it->Value();
4706 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4707 if ( !CORBA::is_nil( aSubObject ) ) {
4708 SMESH_GroupBase_i* myGroupImpl =
4709 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4712 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4716 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4717 int anId = myStudyContext->findId( string( objStr.in() ) );
4719 // For each group, create a dataset named "Group <group_persistent_id>"
4720 // and store the group's user name into it
4721 const char* grpName = aGrpBaseDS->GetStoreName();
4722 CORBA::String_var aUserName = myGroupImpl->GetName();
4723 aSize[ 0 ] = strlen( aUserName ) + 1;
4725 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4726 aDataset->CreateOnDisk();
4727 aDataset->WriteOnDisk( aUserName );
4728 aDataset->CloseOnDisk();
4731 // For each group, create a dataset named "Group <group_persistent_id> Color"
4732 // and store the group's color into it
4733 char grpColorName[ 30 ];
4734 sprintf( grpColorName, "ColorGroup %d", anId );
4735 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4737 anRGB[ 0 ] = aColor.R;
4738 anRGB[ 1 ] = aColor.G;
4739 anRGB[ 2 ] = aColor.B;
4741 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4742 aDataset->CreateOnDisk();
4743 aDataset->WriteOnDisk( anRGB );
4744 aDataset->CloseOnDisk();
4746 // Pass SMESHDS_Group to MED writer
4747 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4749 myWriter.AddGroup( aGrpDS );
4751 // write reference on a shape if exists
4752 SMESHDS_GroupOnGeom* aGeomGrp =
4753 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4755 SALOMEDS::SObject_wrap mySubRef, myShape;
4756 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4757 mySubRef->ReferencedObject( myShape.inout() ) &&
4758 !CORBA::is_nil( myShape->GetObject() ))
4760 CORBA::String_var myRefOnObject = myShape->GetID();
4761 if ( myRefOnObject.in()[0] ) {
4762 char aRefName[ 30 ];
4763 sprintf( aRefName, "Ref on shape %d", anId);
4764 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4765 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4766 aDataset->CreateOnDisk();
4767 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4768 aDataset->CloseOnDisk();
4771 else // shape ref is invalid:
4773 // save a group on geometry as ordinary group
4774 myWriter.AddGroup( aGeomGrp );
4777 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4778 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4780 std::string str = aFilterGrp_i->FilterToString();
4781 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4782 aSize[ 0 ] = str.length() + 1;
4783 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4784 aDataset->CreateOnDisk();
4785 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4786 aDataset->CloseOnDisk();
4790 aGroup->CloseOnDisk();
4794 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4796 // Flush current mesh information into MED file
4799 // save info on nb of elements
4800 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4802 // maybe a shape was deleted in the study
4803 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4804 TopoDS_Shape nullShape;
4805 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4808 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4813 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4814 aGroup->CreateOnDisk();
4816 // each element belongs to one or none submesh,
4817 // so for each node/element, we store a submesh ID
4819 // Store submesh IDs
4820 for ( int isNode = 0; isNode < 2; ++isNode )
4822 SMDS_ElemIteratorPtr eIt =
4823 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4824 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4827 std::vector<int> smIDs; smIDs.reserve( nbElems );
4828 while ( eIt->more() )
4829 if ( const SMDS_MeshElement* e = eIt->next())
4830 smIDs.push_back( e->getshapeId() );
4832 aSize[ 0 ] = nbElems;
4833 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4834 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4835 aDataset->CreateOnDisk();
4836 aDataset->WriteOnDisk( & smIDs[0] );
4837 aDataset->CloseOnDisk();
4840 aGroup->CloseOnDisk();
4842 // Store node positions on sub-shapes (SMDS_Position):
4843 // ----------------------------------------------------
4845 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4846 aGroup->CreateOnDisk();
4848 // in aGroup, create 5 datasets to contain:
4849 // "Nodes on Edges" - ID of node on edge
4850 // "Edge positions" - U parameter on node on edge
4851 // "Nodes on Faces" - ID of node on face
4852 // "Face U positions" - U parameter of node on face
4853 // "Face V positions" - V parameter of node on face
4855 // Find out nb of nodes on edges and faces
4856 // Collect corresponding sub-meshes
4857 int nbEdgeNodes = 0, nbFaceNodes = 0;
4858 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4859 // loop on SMESHDS_SubMesh'es
4860 while ( smIt->more() )
4862 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4863 if ( aSubMesh->IsComplexSubmesh() )
4864 continue; // submesh containing other submeshs
4865 int nbNodes = aSubMesh->NbNodes();
4866 if ( nbNodes == 0 ) continue;
4868 int aShapeID = aSubMesh->GetID();
4869 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4871 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4872 // write only SMDS_FacePosition and SMDS_EdgePosition
4873 switch ( aShapeType ) {
4875 nbFaceNodes += nbNodes;
4876 aFaceSM.push_back( aSubMesh );
4879 nbEdgeNodes += nbNodes;
4880 aEdgeSM.push_back( aSubMesh );
4886 // Treat positions on edges or faces
4887 for ( int onFace = 0; onFace < 2; onFace++ )
4889 // Create arrays to store in datasets
4890 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4891 if (!nbNodes) continue;
4892 int* aNodeIDs = new int [ nbNodes ];
4893 double* aUPos = new double [ nbNodes ];
4894 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4897 // loop on sub-meshes
4898 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4899 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4900 for ( ; itSM != pListSM->end(); itSM++ )
4902 SMESHDS_SubMesh* aSubMesh = (*itSM);
4904 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4905 // loop on nodes in aSubMesh
4906 while ( itNode->more() )
4909 const SMDS_MeshNode* node = itNode->next();
4910 aNodeIDs [ iNode ] = node->GetID();
4913 const SMDS_PositionPtr pos = node->GetPosition();
4914 if ( onFace ) { // on FACE
4915 SMDS_FacePositionPtr fPos = pos;
4917 aUPos[ iNode ] = fPos->GetUParameter();
4918 aVPos[ iNode ] = fPos->GetVParameter();
4925 SMDS_EdgePositionPtr ePos = pos;
4927 aUPos[ iNode ] = ePos->GetUParameter();
4933 } // loop on nodes in aSubMesh
4934 } // loop on sub-meshes
4939 aSize[ 0 ] = nbNodes;
4941 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4942 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4943 aDataset->CreateOnDisk();
4944 aDataset->WriteOnDisk( aNodeIDs );
4945 aDataset->CloseOnDisk();
4948 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4949 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4950 aDataset->CreateOnDisk();
4951 aDataset->WriteOnDisk( aUPos );
4952 aDataset->CloseOnDisk();
4955 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4956 aDataset->CreateOnDisk();
4957 aDataset->WriteOnDisk( aVPos );
4958 aDataset->CloseOnDisk();
4963 if ( aVPos ) delete [] aVPos;
4965 } // treat positions on edges or faces
4967 // close "Node Positions" group
4968 aGroup->CloseOnDisk();
4970 } // if ( there are submeshes in SMESHDS_Mesh )
4973 // close mesh HDF group
4974 aTopGroup->CloseOnDisk();
4982 aFile->CloseOnDisk();
4985 // Convert temporary files to stream
4986 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
4988 // Remove temporary files and directory
4990 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4992 return aStreamFile._retn();
4995 //=============================================================================
4997 * SMESH_Gen_i::SaveASCII
4999 * Save SMESH module's data in ASCII format
5001 //=============================================================================
5003 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5005 bool isMultiFile ) {
5006 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5007 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5008 return aStreamFile._retn();
5010 //after usual saving needs to encipher binary to text string
5011 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5012 int size = aStreamFile.in().length();
5013 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5014 for ( int i = 0; i < size; i++ )
5015 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5017 buffer[size * 3] = '\0';
5019 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5021 return anAsciiStreamFile._retn();
5024 //=============================================================================
5026 * SMESH_Gen_i::loadGeomData
5028 * Load GEOM module data
5030 //=============================================================================
5032 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
5034 if ( theCompRoot->_is_nil() )
5037 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
5038 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
5041 //=============================================================================
5045 * Load SMESH module's data
5047 //=============================================================================
5049 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5050 const SALOMEDS::TMPFile& theStream,
5055 Kernel_Utils::Localizer loc;
5057 //if (!myStudyContext)
5059 SALOMEDS::Study_var aStudy = getStudyServant();
5060 /* if( !theComponent->_is_nil() )
5062 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
5063 loadGeomData( aStudy->FindComponent( "GEOM" ) );
5066 // Get temporary files location
5067 TCollection_AsciiString tmpDir =
5068 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5070 // Convert the stream into sequence of files to process
5071 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5074 TCollection_AsciiString aStudyName( "" );
5075 if ( isMultiFile ) {
5076 CORBA::WString_var url = aStudy->URL();
5077 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5079 // Set names of temporary files
5080 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5081 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5085 HDFdataset* aDataset;
5086 HDFgroup* aTopGroup;
5088 HDFgroup* aSubGroup;
5089 HDFgroup* aSubSubGroup;
5092 // ---> open HDF file
5093 aFile = new HDFfile( (char*) filename.ToCString() );
5095 aFile->OpenOnDisk( HDF_RDONLY );
5097 catch ( HDFexception ) {
5098 INFOS( "Load(): " << filename << " not found!" );
5102 TPythonDump pd; // prevent dump during loading
5104 // DriverMED_R_SMESHDS_Mesh myReader;
5105 // myReader.SetFile( meshfile.ToCString() );
5107 // For PAL13473 ("Repetitive mesh") implementation.
5108 // New dependencies between SMESH objects are established:
5109 // now hypotheses can refer to meshes, shapes and other hypotheses.
5110 // To keep data consistent, the following order of data restoration
5112 // 1. Create hypotheses
5113 // 2. Create all meshes
5114 // 3. Load hypotheses' data
5117 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5118 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5119 list< SMESH::Filter_var > filters;
5121 // get total number of top-level groups
5122 int aNbGroups = aFile->nInternalObjects();
5123 if ( aNbGroups > 0 ) {
5124 // --> in first turn we should read&create hypotheses
5125 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5126 // open hypotheses root HDF group
5127 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5128 aTopGroup->OpenOnDisk();
5130 // get number of hypotheses
5131 int aNbObjects = aTopGroup->nInternalObjects();
5132 for ( int j = 0; j < aNbObjects; j++ ) {
5133 // try to identify hypothesis
5134 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5135 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5137 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5138 // open hypothesis group
5139 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5140 aGroup->OpenOnDisk();
5142 // --> get hypothesis id
5143 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5148 // get number of datasets
5149 int aNbSubObjects = aGroup->nInternalObjects();
5150 for ( int k = 0; k < aNbSubObjects; k++ ) {
5152 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5153 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5154 // --> get hypothesis name
5155 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5156 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5157 aDataset->OpenOnDisk();
5158 size = aDataset->GetSize();
5159 char* hypname_str = new char[ size ];
5160 aDataset->ReadFromDisk( hypname_str );
5161 hypname = string( hypname_str );
5162 delete [] hypname_str;
5163 aDataset->CloseOnDisk();
5165 // --> get hypothesis plugin library name
5166 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5167 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5168 aDataset->OpenOnDisk();
5169 size = aDataset->GetSize();
5170 char* libname_str = new char[ size ];
5171 aDataset->ReadFromDisk( libname_str );
5172 if(MYDEBUG) SCRUTE( libname_str );
5173 libname = string( libname_str );
5174 delete [] libname_str;
5175 aDataset->CloseOnDisk();
5177 // --> get hypothesis data
5178 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5179 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5180 aDataset->OpenOnDisk();
5181 size = aDataset->GetSize();
5182 char* hypdata_str = new char[ size ];
5183 aDataset->ReadFromDisk( hypdata_str );
5184 hypdata = string( hypdata_str );
5185 delete [] hypdata_str;
5186 aDataset->CloseOnDisk();
5189 // close hypothesis HDF group
5190 aGroup->CloseOnDisk();
5192 // --> restore hypothesis from data
5193 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5194 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5195 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5196 SMESH::SMESH_Hypothesis_var myHyp;
5198 try { // protect persistence mechanism against exceptions
5199 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5202 INFOS( "Exception during hypothesis creation" );
5205 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5207 // myImpl->LoadFrom( hypdata.c_str() );
5208 hypDataList.push_back( make_pair( myImpl, hypdata ));
5209 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5210 int newId = myStudyContext->findId( iorString.in() );
5211 myStudyContext->mapOldToNew( id, newId );
5214 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5218 // close hypotheses root HDF group
5219 aTopGroup->CloseOnDisk();
5223 // --> then we should read&create algorithms
5224 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5225 // open algorithms root HDF group
5226 aTopGroup = new HDFgroup( "Algorithms", aFile );
5227 aTopGroup->OpenOnDisk();
5229 // get number of algorithms
5230 int aNbObjects = aTopGroup->nInternalObjects();
5231 for ( int j = 0; j < aNbObjects; j++ ) {
5232 // try to identify algorithm
5233 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5234 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5236 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5237 // open algorithm group
5238 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5239 aGroup->OpenOnDisk();
5241 // --> get algorithm id
5242 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5247 // get number of datasets
5248 int aNbSubObjects = aGroup->nInternalObjects();
5249 for ( int k = 0; k < aNbSubObjects; k++ ) {
5251 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5252 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5253 // --> get algorithm name
5254 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5255 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5256 aDataset->OpenOnDisk();
5257 size = aDataset->GetSize();
5258 char* hypname_str = new char[ size ];
5259 aDataset->ReadFromDisk( hypname_str );
5260 hypname = string( hypname_str );
5261 delete [] hypname_str;
5262 aDataset->CloseOnDisk();
5264 // --> get algorithm plugin library name
5265 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5266 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5267 aDataset->OpenOnDisk();
5268 size = aDataset->GetSize();
5269 char* libname_str = new char[ size ];
5270 aDataset->ReadFromDisk( libname_str );
5271 if(MYDEBUG) SCRUTE( libname_str );
5272 libname = string( libname_str );
5273 delete [] libname_str;
5274 aDataset->CloseOnDisk();
5276 // --> get algorithm data
5277 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5278 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5279 aDataset->OpenOnDisk();
5280 size = aDataset->GetSize();
5281 char* hypdata_str = new char[ size ];
5282 aDataset->ReadFromDisk( hypdata_str );
5283 if(MYDEBUG) SCRUTE( hypdata_str );
5284 hypdata = string( hypdata_str );
5285 delete [] hypdata_str;
5286 aDataset->CloseOnDisk();
5289 // close algorithm HDF group
5290 aGroup->CloseOnDisk();
5292 // --> restore algorithm from data
5293 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5294 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5295 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5296 SMESH::SMESH_Hypothesis_var myHyp;
5298 try { // protect persistence mechanism against exceptions
5299 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5301 catch( SALOME::SALOME_Exception& ex )
5303 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5306 INFOS( "Exception during hypothesis creation" );
5309 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5311 //myImpl->LoadFrom( hypdata.c_str() );
5312 hypDataList.push_back( make_pair( myImpl, hypdata ));
5313 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5314 int newId = myStudyContext->findId( iorString.in() );
5315 myStudyContext->mapOldToNew( id, newId );
5318 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5322 // close algorithms root HDF group
5323 aTopGroup->CloseOnDisk();
5327 // --> the rest groups should be meshes
5328 for ( int i = 0; i < aNbGroups; i++ ) {
5329 // identify next group
5330 char meshName[ HDF_NAME_MAX_LEN+1 ];
5331 aFile->InternalObjectIndentify( i, meshName );
5333 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5335 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5339 // open mesh HDF group
5340 aTopGroup = new HDFgroup( meshName, aFile );
5341 aTopGroup->OpenOnDisk();
5343 // get number of child HDF objects
5344 int aNbObjects = aTopGroup->nInternalObjects();
5345 if ( aNbObjects > 0 ) {
5347 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5348 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5349 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5350 if ( !myNewMeshImpl )
5352 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5354 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5355 int newId = myStudyContext->findId( iorString.in() );
5356 myStudyContext->mapOldToNew( id, newId );
5359 // try to read and set auto color flag
5360 char aMeshAutoColorName[ 30 ];
5361 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5362 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5364 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5365 aDataset->OpenOnDisk();
5366 size = aDataset->GetSize();
5367 int* anAutoColor = new int[ size ];
5368 aDataset->ReadFromDisk( anAutoColor );
5369 aDataset->CloseOnDisk();
5370 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5371 delete [] anAutoColor;
5374 // try to read and set reference to shape
5375 GEOM::GEOM_Object_var aShapeObject;
5376 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5377 // load mesh "Ref on shape" - it's an entry to SObject
5378 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5379 aDataset->OpenOnDisk();
5380 size = aDataset->GetSize();
5381 char* refFromFile = new char[ size ];
5382 aDataset->ReadFromDisk( refFromFile );
5383 aDataset->CloseOnDisk();
5384 if ( strlen( refFromFile ) > 0 ) {
5385 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5387 // Make sure GEOM data are loaded first
5388 //loadGeomData( shapeSO->GetFatherComponent() );
5390 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5391 if ( !CORBA::is_nil( shapeObject ) ) {
5392 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5393 if ( !aShapeObject->_is_nil() )
5394 myNewMeshImpl->SetShape( aShapeObject );
5397 delete [] refFromFile;
5400 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5401 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5403 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5404 aDataset->OpenOnDisk();
5405 size = aDataset->GetSize();
5406 int* meshPersistentId = new int[ size ];
5407 aDataset->ReadFromDisk( meshPersistentId );
5408 aDataset->CloseOnDisk();
5409 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5410 delete [] meshPersistentId;
5413 // Restore file info
5414 if ( aTopGroup->ExistInternalObject( "file info" ))
5416 aDataset = new HDFdataset( "file info", aTopGroup );
5417 aDataset->OpenOnDisk();
5418 size = aDataset->GetSize();
5419 std::string info( size, ' ');
5420 aDataset->ReadFromDisk( (char*) info.data() );
5421 aDataset->CloseOnDisk();
5422 myNewMeshImpl->FileInfoFromString( info );
5428 // As all object that can be referred by hypothesis are created,
5429 // we can restore hypothesis data
5431 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5432 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5434 SMESH_Hypothesis_i* hyp = hyp_data->first;
5435 string & data = hyp_data->second;
5436 hyp->LoadFrom( data.c_str() );
5439 // Restore the rest mesh data
5441 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5442 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5444 aTopGroup = meshi_group->second;
5445 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5446 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5447 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5449 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5450 bool hasData = false;
5453 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5454 int newId = myStudyContext->findId( iorString.in() );
5455 int meshOldId = myStudyContext->getOldId( newId );
5457 // try to find mesh data dataset
5458 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5459 // load mesh "has data" flag
5460 aDataset = new HDFdataset( "Has data", aTopGroup );
5461 aDataset->OpenOnDisk();
5462 size = aDataset->GetSize();
5463 char* strHasData = new char[ size ];
5464 aDataset->ReadFromDisk( strHasData );
5465 aDataset->CloseOnDisk();
5466 if ( strcmp( strHasData, "1") == 0 ) {
5469 delete [] strHasData;
5472 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5473 // nodes and elements are not yet put into sub-meshes)
5474 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5475 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5476 aGroup->OpenOnDisk();
5477 // get number of applied algorithms
5478 int aNbSubObjects = aGroup->nInternalObjects();
5479 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5480 for ( int j = 0; j < aNbSubObjects; j++ ) {
5481 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5482 aGroup->InternalObjectIndentify( j, name_dataset );
5483 // check if it is an algorithm
5484 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5485 aDataset = new HDFdataset( name_dataset, aGroup );
5486 aDataset->OpenOnDisk();
5487 size = aDataset->GetSize();
5488 char* refFromFile = new char[ size ];
5489 aDataset->ReadFromDisk( refFromFile );
5490 aDataset->CloseOnDisk();
5491 // san - it is impossible to recover applied algorithms using their entries within Load() method
5492 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5493 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5494 int id = atoi( refFromFile );
5495 delete [] refFromFile;
5496 string anIOR = myStudyContext->getIORbyOldId( id );
5497 if ( !anIOR.empty() ) {
5498 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5499 if ( !CORBA::is_nil( hypObject ) ) {
5500 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5501 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5502 || !myNewMeshImpl->HasShapeToMesh()) )
5503 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5508 aGroup->CloseOnDisk();
5511 // try to get applied hypotheses
5512 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5513 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5514 aGroup->OpenOnDisk();
5515 // get number of applied hypotheses
5516 int aNbSubObjects = aGroup->nInternalObjects();
5517 for ( int j = 0; j < aNbSubObjects; j++ ) {
5518 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5519 aGroup->InternalObjectIndentify( j, name_dataset );
5520 // check if it is a hypothesis
5521 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5522 aDataset = new HDFdataset( name_dataset, aGroup );
5523 aDataset->OpenOnDisk();
5524 size = aDataset->GetSize();
5525 char* refFromFile = new char[ size ];
5526 aDataset->ReadFromDisk( refFromFile );
5527 aDataset->CloseOnDisk();
5528 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5529 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5530 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5531 int id = atoi( refFromFile );
5532 delete [] refFromFile;
5533 string anIOR = myStudyContext->getIORbyOldId( id );
5534 if ( !anIOR.empty() ) {
5535 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5536 if ( !CORBA::is_nil( hypObject ) ) {
5537 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5538 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5539 || !myNewMeshImpl->HasShapeToMesh()) )
5540 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5545 aGroup->CloseOnDisk();
5548 // --> try to find SUB-MESHES containers for each type of submesh
5549 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5550 const char* name_meshgroup = 0;
5551 if ( j == GetSubMeshOnVertexTag() )
5552 name_meshgroup = "SubMeshes On Vertex";
5553 else if ( j == GetSubMeshOnEdgeTag() )
5554 name_meshgroup = "SubMeshes On Edge";
5555 else if ( j == GetSubMeshOnWireTag() )
5556 name_meshgroup = "SubMeshes On Wire";
5557 else if ( j == GetSubMeshOnFaceTag() )
5558 name_meshgroup = "SubMeshes On Face";
5559 else if ( j == GetSubMeshOnShellTag() )
5560 name_meshgroup = "SubMeshes On Shell";
5561 else if ( j == GetSubMeshOnSolidTag() )
5562 name_meshgroup = "SubMeshes On Solid";
5563 else if ( j == GetSubMeshOnCompoundTag() )
5564 name_meshgroup = "SubMeshes On Compound";
5566 // try to get submeshes container HDF group
5567 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5568 // open submeshes containers HDF group
5569 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5570 aGroup->OpenOnDisk();
5572 // get number of submeshes
5573 int aNbSubMeshes = aGroup->nInternalObjects();
5574 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5576 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5577 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5578 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5579 // --> get submesh id
5580 int subid = atoi( name_submeshgroup + 7 );
5583 // open submesh HDF group
5584 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5585 aSubGroup->OpenOnDisk();
5587 // try to read and set reference to subshape
5588 GEOM::GEOM_Object_var aSubShapeObject;
5589 SMESH::SMESH_subMesh_var aSubMesh;
5591 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5592 // load submesh "Ref on shape" - it's an entry to SObject
5593 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5594 aDataset->OpenOnDisk();
5595 size = aDataset->GetSize();
5596 char* refFromFile = new char[ size ];
5597 aDataset->ReadFromDisk( refFromFile );
5598 aDataset->CloseOnDisk();
5599 if ( strlen( refFromFile ) > 0 ) {
5600 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5601 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5602 if ( !CORBA::is_nil( subShapeObject ) ) {
5603 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5604 if ( !aSubShapeObject->_is_nil() )
5605 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5606 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5607 if ( aSubMesh->_is_nil() )
5609 string iorSubString = GetORB()->object_to_string( aSubMesh );
5610 int newSubId = myStudyContext->findId( iorSubString );
5611 myStudyContext->mapOldToNew( subid, newSubId );
5614 delete [] refFromFile;
5617 if ( aSubMesh->_is_nil() )
5620 // try to get applied algorithms
5621 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5622 // open "applied algorithms" HDF group
5623 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5624 aSubSubGroup->OpenOnDisk();
5625 // get number of applied algorithms
5626 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5627 for ( int l = 0; l < aNbSubObjects; l++ ) {
5628 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5629 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5630 // check if it is an algorithm
5631 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5632 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5633 aDataset->OpenOnDisk();
5634 size = aDataset->GetSize();
5635 char* refFromFile = new char[ size ];
5636 aDataset->ReadFromDisk( refFromFile );
5637 aDataset->CloseOnDisk();
5639 int id = atoi( refFromFile );
5640 string anIOR = myStudyContext->getIORbyOldId( id );
5641 if ( !anIOR.empty() ) {
5642 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5643 if ( !CORBA::is_nil( hypObject ) ) {
5644 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5645 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5646 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5649 delete [] refFromFile;
5652 // close "applied algorithms" HDF group
5653 aSubSubGroup->CloseOnDisk();
5656 // try to get applied hypotheses
5657 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5658 // open "applied hypotheses" HDF group
5659 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5660 aSubSubGroup->OpenOnDisk();
5661 // get number of applied hypotheses
5662 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5663 for ( int l = 0; l < aNbSubObjects; l++ ) {
5664 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5665 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5666 // check if it is a hypothesis
5667 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5668 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5669 aDataset->OpenOnDisk();
5670 size = aDataset->GetSize();
5671 char* refFromFile = new char[ size ];
5672 aDataset->ReadFromDisk( refFromFile );
5673 aDataset->CloseOnDisk();
5675 int id = atoi( refFromFile );
5676 string anIOR = myStudyContext->getIORbyOldId( id );
5677 if ( !anIOR.empty() ) {
5678 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5679 if ( !CORBA::is_nil( hypObject ) ) {
5680 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5681 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5682 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5685 delete [] refFromFile;
5688 // close "APPLIED HYPOTHESES" hdf group
5689 aSubSubGroup->CloseOnDisk();
5692 // close SUB-MESH hdf group
5693 aSubGroup->CloseOnDisk();
5696 // close SUB-MESHES containers hdf group
5697 aGroup->CloseOnDisk();
5701 // try to get GROUPS
5702 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5703 char name_group[ 30 ];
5704 if ( ii == GetNodeGroupsTag() )
5705 strcpy( name_group, "Groups of Nodes" );
5706 else if ( ii == GetEdgeGroupsTag() )
5707 strcpy( name_group, "Groups of Edges" );
5708 else if ( ii == GetFaceGroupsTag() )
5709 strcpy( name_group, "Groups of Faces" );
5710 else if ( ii == GetVolumeGroupsTag() )
5711 strcpy( name_group, "Groups of Volumes" );
5712 else if ( ii == Get0DElementsGroupsTag() )
5713 strcpy( name_group, "Groups of 0D Elements" );
5714 else if ( ii == GetBallElementsGroupsTag() )
5715 strcpy( name_group, "Groups of Balls" );
5717 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5718 aGroup = new HDFgroup( name_group, aTopGroup );
5719 aGroup->OpenOnDisk();
5720 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5721 // within aGroup->ExistInternalObject( name )
5722 std::vector< std::string > subNames;
5723 TColStd_MapOfAsciiString mapOfNames;
5724 aGroup->GetAllObjects( subNames );
5725 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5726 mapOfNames.Add( subNames[ iN ].c_str() );
5728 for ( size_t j = 0; j < subNames.size(); j++ ) {
5729 const std::string& name_dataset = subNames[ j ];
5730 // check if it is a group
5731 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5734 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5737 int groupID = -1; // group local ID (also persistent)
5739 groupID = atoi( endptr + 1 );
5740 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5741 aDataset->OpenOnDisk();
5743 // Retrieve actual group name
5744 size = aDataset->GetSize();
5745 char* nameFromFile = new char[ size ];
5746 aDataset->ReadFromDisk( nameFromFile );
5747 aDataset->CloseOnDisk();
5749 // Try to find a shape reference
5750 TopoDS_Shape aShape;
5751 char aRefName[ 30 ];
5752 sprintf( aRefName, "Ref on shape %d", subid);
5753 if ( mapOfNames.Contains( aRefName ))
5755 // load mesh "Ref on shape" - it's an entry to SObject
5756 aDataset = new HDFdataset( aRefName, aGroup );
5757 aDataset->OpenOnDisk();
5758 size = aDataset->GetSize();
5759 char* refFromFile = new char[ size ];
5760 aDataset->ReadFromDisk( refFromFile );
5761 aDataset->CloseOnDisk();
5762 if ( strlen( refFromFile ) > 0 ) {
5763 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5764 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5765 if ( !CORBA::is_nil( shapeObject ) ) {
5766 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5767 if ( !aShapeObject->_is_nil() )
5768 aShape = GeomObjectToShape( aShapeObject );
5771 delete [] refFromFile;
5773 // Try to read a filter of SMESH_GroupOnFilter
5774 SMESH::Filter_var filter;
5775 SMESH_PredicatePtr predicate;
5776 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5777 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5779 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5780 aDataset->OpenOnDisk();
5781 size = aDataset->GetSize();
5782 char* persistStr = new char[ size ];
5783 aDataset->ReadFromDisk( persistStr );
5784 aDataset->CloseOnDisk();
5785 if ( strlen( persistStr ) > 0 ) {
5786 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5787 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5788 filters.push_back( filter );
5790 delete [] persistStr;
5793 // Create group servant
5794 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5795 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5796 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5797 delete [] nameFromFile;
5798 // Obtain a SMESHDS_Group object
5799 if ( aNewGroup->_is_nil() )
5802 string iorSubString = GetORB()->object_to_string( aNewGroup );
5803 int newSubId = myStudyContext->findId( iorSubString );
5804 myStudyContext->mapOldToNew( subid, newSubId );
5806 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5810 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5811 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5813 aFilterGroup->SetFilter( filter );
5814 filter->UnRegister();
5816 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5817 if ( !aGroupBaseDS )
5820 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5823 // Read color of the group
5824 char aGroupColorName[ 30 ];
5825 sprintf( aGroupColorName, "ColorGroup %d", subid);
5826 if ( mapOfNames.Contains( aGroupColorName ))
5828 aDataset = new HDFdataset( aGroupColorName, aGroup );
5829 aDataset->OpenOnDisk();
5830 size = aDataset->GetSize();
5831 double* anRGB = new double[ size ];
5832 aDataset->ReadFromDisk( anRGB );
5833 aDataset->CloseOnDisk();
5834 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5835 aGroupBaseDS->SetColor( aColor );
5840 aGroup->CloseOnDisk();
5844 // instead of reading mesh data, we read only brief information of all
5845 // objects: mesh, groups, sub-meshes (issue 0021208)
5848 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5849 meshfile.ToCString(), filename.ToCString(),
5853 // read Sub-Mesh ORDER if any
5854 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5855 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5856 aDataset->OpenOnDisk();
5857 size = aDataset->GetSize();
5858 int* smIDs = new int[ size ];
5859 aDataset->ReadFromDisk( smIDs );
5860 aDataset->CloseOnDisk();
5861 TListOfListOfInt anOrderIds;
5862 anOrderIds.push_back( TListOfInt() );
5863 for ( int i = 0; i < size; i++ )
5864 if ( smIDs[ i ] < 0 ) // is separator
5865 anOrderIds.push_back( TListOfInt() );
5867 anOrderIds.back().push_back(smIDs[ i ]);
5869 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5874 // update hyps needing full mesh data restored (issue 20918)
5875 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5877 SMESH_Hypothesis_i* hyp = hyp_data->first;
5878 hyp->UpdateAsMeshesRestored();
5881 // notify algos on completed restoration to set sub-mesh event listeners
5882 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5884 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5885 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5887 TopoDS_Shape myLocShape;
5888 if(myLocMesh.HasShapeToMesh())
5889 myLocShape = myLocMesh.GetShapeToMesh();
5891 myLocShape = SMESH_Mesh::PseudoShape();
5893 myLocMesh.GetSubMesh(myLocShape)->
5894 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5897 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5898 list< SMESH::Filter_var >::iterator f = filters.begin();
5899 for ( ; f != filters.end(); ++f )
5900 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5901 fi->FindBaseObjects();
5906 aTopGroup->CloseOnDisk();
5909 aFile->CloseOnDisk();
5912 // Remove temporary files created from the stream
5915 SMESH_File meshFile( meshfile.ToCString() );
5916 if ( !meshFile ) // no meshfile exists
5918 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5922 Engines::Container_var container = GetContainerRef();
5923 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5925 container_i->registerTemporaryFile( filename.ToCString() );
5926 container_i->registerTemporaryFile( meshfile.ToCString() );
5927 container_i->registerTemporaryFile( tmpDir.ToCString() );
5931 pd << ""; // prevent optimizing pd out
5933 // creation of tree nodes for all data objects in the study
5934 // to support tree representation customization and drag-n-drop:
5935 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5936 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5937 useCaseBuilder->SetRootCurrent();
5938 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5939 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5940 for (it->InitEx(true); it->More(); it->Next()) {
5941 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5948 //=============================================================================
5950 * SMESH_Gen_i::LoadASCII
5952 * Load SMESH module's data in ASCII format
5954 //=============================================================================
5956 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5957 const SALOMEDS::TMPFile& theStream,
5959 bool isMultiFile ) {
5960 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5961 return Load( theComponent, theStream, theURL, isMultiFile );
5963 //before call main ::Load method it's need for decipher text format to
5964 //binary ( "|xx" => x' )
5965 int size = theStream.length();
5966 if ( int((size / 3 )*3) != size ) //error size of buffer
5969 int real_size = int(size / 3);
5971 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5974 unsigned int c = -1;
5975 for ( int i = 0; i < real_size; i++ )
5977 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5978 sscanf( tmp, "%x", &c );
5979 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5982 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5984 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5987 //=============================================================================
5989 * SMESH_Gen_i::Close
5991 * Clears study-connected data when it is closed
5993 //=============================================================================
5995 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
5997 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
5999 // Clear study contexts data
6000 myStudyContext->Clear();
6002 // remove the tmp files meshes are loaded from
6003 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6005 // Clean trace of API methods calls
6011 //=============================================================================
6013 * SMESH_Gen_i::ComponentDataType
6015 * Get component data type
6017 //=============================================================================
6019 char* SMESH_Gen_i::ComponentDataType()
6021 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6022 return CORBA::string_dup( "SMESH" );
6026 //=============================================================================
6028 * SMESH_Gen_i::IORToLocalPersistentID
6030 * Transform data from transient form to persistent
6032 //=============================================================================
6034 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6035 const char* IORString,
6036 CORBA::Boolean /*isMultiFile*/,
6037 CORBA::Boolean /*isASCII*/ )
6039 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6041 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6042 int anId = myStudyContext->findId( IORString );
6044 if(MYDEBUG) MESSAGE( "VSR " << anId )
6046 sprintf( strId, "%d", anId );
6047 return CORBA::string_dup( strId );
6050 return CORBA::string_dup( "" );
6053 //=============================================================================
6055 * SMESH_Gen_i::LocalPersistentIDToIOR
6057 * Transform data from persistent form to transient
6059 //=============================================================================
6061 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6062 const char* aLocalPersistentID,
6063 CORBA::Boolean /*isMultiFile*/,
6064 CORBA::Boolean /*isASCII*/ )
6066 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6068 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6069 int anId = atoi( aLocalPersistentID );
6070 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6072 return CORBA::string_dup( "" );
6075 //=======================================================================
6076 //function : RegisterObject
6078 //=======================================================================
6080 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6082 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6083 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6084 return myStudyContext->addObject( string( iorString.in() ) );
6089 //================================================================================
6091 * \brief Return id of registered object
6092 * \param theObject - the Object
6093 * \retval int - Object id
6095 //================================================================================
6097 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6099 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6100 string iorString = GetORB()->object_to_string( theObject );
6101 return myStudyContext->findId( iorString );
6106 //=============================================================================
6108 * SMESH_Gen_i::SetName
6110 * Set a new object name
6112 //=============================================================================
6113 void SMESH_Gen_i::SetName(const char* theIOR,
6114 const char* theName)
6116 if ( theIOR && strcmp( theIOR, "" ) ) {
6117 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6118 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6119 if ( !aSO->_is_nil() ) {
6120 SetName( aSO, theName );
6125 // Version information
6126 char* SMESH_Gen_i::getVersion()
6128 #if SMESH_DEVELOPMENT
6129 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6131 return CORBA::string_dup(SMESH_VERSION_STR);
6135 //=================================================================================
6136 // function : Move()
6137 // purpose : Moves objects to the specified position.
6138 // Is used in the drag-n-drop functionality.
6139 //=================================================================================
6140 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6141 SALOMEDS::SObject_ptr where,
6144 if ( CORBA::is_nil( where ) ) return;
6146 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6147 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6148 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6149 std::string dataType = father->ComponentDataType();
6150 if ( dataType != "SMESH" ) return; // not a SMESH component
6152 SALOMEDS::SObject_var objAfter;
6153 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6154 // insert at given row -> find insertion position
6155 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6157 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6158 if ( i == row && useCaseIt->More() ) {
6159 objAfter = useCaseIt->Value();
6163 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6164 SALOMEDS::SObject_var sobj = what[i];
6165 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6166 // insert the object to the use case tree
6167 if ( !CORBA::is_nil( objAfter ) )
6168 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6170 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6173 //================================================================================
6175 * \brief Returns true if algorithm can be used to mesh a given geometry
6176 * \param [in] theAlgoType - the algorithm type
6177 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6178 * \param [in] theGeomObject - the geometry to mesh
6179 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6180 * else, returns \c True if at least one shape is meshable
6181 * \return CORBA::Boolean - can or can't
6183 //================================================================================
6185 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6186 const char* theLibName,
6187 GEOM::GEOM_Object_ptr theGeomObject,
6188 CORBA::Boolean toCheckAll)
6192 std::string aPlatformLibName;
6193 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6194 GenericHypothesisCreator_i* aCreator =
6195 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6198 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6199 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6200 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6207 SMESH_CATCH( SMESH::doNothing );
6210 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6215 //=================================================================================
6216 // function : GetInsideSphere
6217 // purpose : Collect indices of elements, which are located inside the sphere
6218 //=================================================================================
6219 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6220 SMESH::ElementType theElemType,
6226 SMESH::long_array_var aResult = new SMESH::long_array();
6227 if ( meshPart->_is_nil() )
6228 return aResult._retn();
6230 // 1. Create geometrical object
6231 gp_Pnt aP( theX, theY, theZ );
6232 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6234 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6236 if ( lst.size() > 0 ) {
6237 aResult->length( lst.size() );
6238 for ( size_t i = 0; i < lst.size(); i++ ) {
6239 aResult[i] = lst[i];
6242 return aResult._retn();
6245 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6246 SMESH::ElementType theElemType,
6247 CORBA::Double theX1,
6248 CORBA::Double theY1,
6249 CORBA::Double theZ1,
6250 CORBA::Double theX2,
6251 CORBA::Double theY2,
6252 CORBA::Double theZ2) {
6253 SMESH::long_array_var aResult = new SMESH::long_array();
6254 if( meshPart->_is_nil() )
6255 return aResult._retn();
6257 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6259 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6261 if( lst.size() > 0 ) {
6262 aResult->length( lst.size() );
6263 for ( size_t i = 0; i < lst.size(); i++ ) {
6264 aResult[i] = lst[i];
6267 return aResult._retn();
6270 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6271 SMESH::ElementType theElemType,
6275 CORBA::Double theDX,
6276 CORBA::Double theDY,
6277 CORBA::Double theDZ,
6279 CORBA::Double theR ){
6280 SMESH::long_array_var aResult = new SMESH::long_array();
6281 if( meshPart->_is_nil() )
6282 return aResult._retn();
6284 gp_Pnt aP( theX, theY, theZ );
6285 gp_Vec aV( theDX, theDY, theDZ );
6286 gp_Ax2 anAxes (aP, aV);
6288 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6290 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6292 if( lst.size() > 0 ) {
6293 aResult->length( lst.size() );
6294 for ( size_t i = 0; i < lst.size(); i++ ) {
6295 aResult[i] = lst[i];
6298 return aResult._retn();
6301 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6302 SMESH::ElementType theElemType,
6303 GEOM::GEOM_Object_ptr theGeom,
6304 CORBA::Double theTolerance ) {
6305 SMESH::long_array_var aResult = new SMESH::long_array();
6306 if( meshPart->_is_nil() || theGeom->_is_nil() )
6307 return aResult._retn();
6309 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6311 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6313 if( lst.size() > 0 ) {
6314 aResult->length( lst.size() );
6315 for ( size_t i = 0; i < lst.size(); i++ ) {
6316 aResult[i] = lst[i];
6319 return aResult._retn();
6324 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6325 SMESH::ElementType theElemType,
6326 TopoDS_Shape& aShape,
6327 double* theTolerance) {
6329 std::vector<long> res;
6330 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6332 if ( mesh->_is_nil() )
6335 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6339 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6344 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6345 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6346 anElementsOnShape->SetAllNodes( true );
6347 anElementsOnShape->SetMesh( meshDS );
6348 anElementsOnShape->SetShape( aShape, aType );
6351 anElementsOnShape->SetTolerance(*theTolerance);
6353 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6354 if ( !msource->_is_nil() ) { // Mesh case
6355 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6357 while ( elemIt->more() ) {
6358 const SMDS_MeshElement* anElem = elemIt->next();
6359 long anId = anElem->GetID();
6360 if ( anElementsOnShape->IsSatisfy( anId ) )
6361 res.push_back( anId );
6365 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6366 if ( !gsource->_is_nil() ) {
6367 if(theElemType == SMESH::NODE) {
6368 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6369 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6370 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6371 long anId = node->GetID();
6372 if ( anElementsOnShape->IsSatisfy( anId ) )
6373 res.push_back( anId );
6376 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6377 SMESH::long_array_var elems = gsource->GetListOfID();
6378 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6379 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6380 long anId = elem->GetID();
6381 if ( anElementsOnShape->IsSatisfy( anId ) )
6382 res.push_back( anId );
6387 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6388 if ( !smsource->_is_nil() ) {
6389 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6390 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6391 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6393 long anId = elem->GetID();
6394 if ( anElementsOnShape->IsSatisfy( anId ) )
6395 res.push_back( anId );
6403 //=============================================================================
6405 * SMESHEngine_factory
6407 * C factory, accessible with dlsym, after dlopen
6409 //=============================================================================
6413 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6414 PortableServer::POA_ptr poa,
6415 PortableServer::ObjectId* contId,
6416 const char* instanceName,
6417 const char* interfaceName )
6419 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6420 if(MYDEBUG) SCRUTE(interfaceName);
6421 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6422 return aSMESHGen->getId() ;