1 // Copyright (C) 2007-2015 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
27 #include <TopExp_Explorer.hxx>
29 #include <TopoDS_Iterator.hxx>
30 #include <TopoDS_Compound.hxx>
31 #include <TopoDS_CompSolid.hxx>
32 #include <TopoDS_Solid.hxx>
33 #include <TopoDS_Shell.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TopoDS_Wire.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Vertex.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <BRep_Tool.hxx>
45 #include <TCollection_AsciiString.hxx>
47 #include <BRepPrimAPI_MakeSphere.hxx>
48 #include <BRepPrimAPI_MakeCylinder.hxx>
49 #include <BRepPrimAPI_MakeBox.hxx>
60 #define LibHandle HMODULE
61 #define LoadLib( name ) LoadLibrary( name )
62 #define GetProc GetProcAddress
63 #define UnLoadLib( handle ) FreeLibrary( handle );
65 #define LibHandle void*
66 #define LoadLib( name ) dlopen( name, RTLD_LAZY )
68 #define UnLoadLib( handle ) dlclose( handle );
71 #include "SMESH_Gen_i.hxx"
72 #include "SMESH_version.h"
74 #include "DriverMED_W_SMESHDS_Mesh.h"
75 #include "DriverMED_R_SMESHDS_Mesh.h"
77 #include "DriverCGNS_Read.hxx"
79 #include "MED_Factory.hxx"
80 #include "SMDS_EdgePosition.hxx"
81 #include "SMDS_FacePosition.hxx"
82 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
83 #include "SMDS_SetIterator.hxx"
84 #include "SMDS_SpacePosition.hxx"
85 #include "SMDS_VertexPosition.hxx"
86 #include "SMESHDS_Document.hxx"
87 #include "SMESHDS_Group.hxx"
88 #include "SMESHDS_GroupOnGeom.hxx"
89 #include "SMESH_Algo_i.hxx"
90 #include "SMESH_File.hxx"
91 #include "SMESH_Group.hxx"
92 #include "SMESH_Group_i.hxx"
93 #include "SMESH_Hypothesis.hxx"
94 #include "SMESH_Hypothesis_i.hxx"
95 #include "SMESH_Mesh.hxx"
96 #include "SMESH_MeshEditor.hxx"
97 #include "SMESH_Mesh_i.hxx"
98 #include "SMESH_PreMeshInfo.hxx"
99 #include "SMESH_PythonDump.hxx"
100 #include "SMESH_ControlsDef.hxx"
101 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
103 #include CORBA_SERVER_HEADER(SMESH_Group)
104 #include CORBA_SERVER_HEADER(SMESH_Filter)
105 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
108 #include <GEOM_Client.hxx>
110 #include <Basics_Utils.hxx>
111 #include <Basics_DirUtils.hxx>
113 #include <OpUtil.hxx>
114 #include <SALOMEDS_Tool.hxx>
115 #include <SALOME_Container_i.hxx>
116 #include <SALOME_LifeCycleCORBA.hxx>
117 #include <SALOME_NamingService.hxx>
118 #include <Utils_CorbaException.hxx>
119 #include <Utils_ExceptHandlers.hxx>
120 #include <Utils_SINGLETON.hxx>
121 #include <utilities.h>
123 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
124 #include CORBA_CLIENT_HEADER(SALOME_Session)
126 // helpers about SALOME::GenericObj
127 #include <SALOMEDS_wrap.hxx>
128 #include <SALOMEDS_Attributes_wrap.hxx>
129 #include <GEOM_wrap.hxx>
137 using SMESH::TPythonDump;
140 #define NUM_TMP_FILES 2
143 static int MYDEBUG = 0;
145 static int MYDEBUG = 0;
148 // Static variables definition
149 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
150 CORBA::ORB_var SMESH_Gen_i::myOrb;
151 PortableServer::POA_var SMESH_Gen_i::myPoa;
152 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
153 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
154 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
157 const int nbElemPerDiagonal = 10;
159 //=============================================================================
161 * GetServant [ static ]
163 * Get servant of the CORBA object
165 //=============================================================================
167 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
169 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
172 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
176 INFOS( "GetServant - Unknown exception was caught!!!" );
181 //=============================================================================
183 * SObjectToObject [ static ]
185 * Get CORBA object corresponding to the SALOMEDS::SObject
187 //=============================================================================
189 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
191 SALOMEDS::GenericAttribute_wrap anAttr;
192 CORBA::Object_var anObj;
193 if ( !theSObject->_is_nil() ) {
195 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
196 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
197 CORBA::String_var aValue = anIOR->Value();
198 if( strcmp( aValue, "" ) != 0 )
199 anObj = GetORB()->string_to_object( aValue );
203 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
209 //=============================================================================
213 * Get SALOME_NamingService object
215 //=============================================================================
217 SALOME_NamingService* SMESH_Gen_i::GetNS()
219 if ( myNS == NULL ) {
220 myNS = SINGLETON_<SALOME_NamingService>::Instance();
221 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
222 myNS->init_orb( GetORB() );
227 //=============================================================================
231 * Get SALOME_LifeCycleCORBA object
233 //=============================================================================
234 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
235 if ( myLCC == NULL ) {
236 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
242 //=============================================================================
244 * GetGeomEngine [ static ]
246 * Get GEOM::GEOM_Gen reference
248 //=============================================================================
249 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
250 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
251 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
252 //CCRT return aGeomEngine._retn();
253 if(CORBA::is_nil(myGeomGen))
255 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
256 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
261 //=============================================================================
263 * SMESH_Gen_i::SMESH_Gen_i
265 * Default constructor: not for use
267 //=============================================================================
269 SMESH_Gen_i::SMESH_Gen_i()
273 //=============================================================================
275 * SMESH_Gen_i::SMESH_Gen_i
277 * Standard constructor, used with Container
279 //=============================================================================
281 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
282 PortableServer::POA_ptr poa,
283 PortableServer::ObjectId* contId,
284 const char* instanceName,
285 const char* interfaceName )
286 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
288 MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
290 myOrb = CORBA::ORB::_duplicate(orb);
291 myPoa = PortableServer::POA::_duplicate(poa);
294 _id = myPoa->activate_object( _thisObj );
296 myIsEmbeddedMode = false;
297 myShapeReader = NULL; // shape reader
299 myIsHistoricalPythonDump = true;
300 myToForgetMeshDataOnHypModif = false;
302 // set it in standalone mode only
303 //OSD::SetSignal( true );
305 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
306 // find out mode (embedded or standalone) here else
307 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
308 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
309 if ( SALOME_NamingService* ns = GetNS() )
311 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
312 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
313 if ( !session->_is_nil() )
315 CORBA::String_var str_host = session->getHostname();
316 CORBA::Long s_pid = session->getPID();
317 string my_host = Kernel_Utils::GetHostname();
319 long my_pid = (long)_getpid();
321 long my_pid = (long) getpid();
323 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
328 //=============================================================================
330 * SMESH_Gen_i::~SMESH_Gen_i
334 //=============================================================================
336 SMESH_Gen_i::~SMESH_Gen_i()
338 MESSAGE( "SMESH_Gen_i::~SMESH_Gen_i" );
340 // delete hypothesis creators
341 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
342 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
344 // same creator can be mapped under different names
345 GenericHypothesisCreator_i* creator = (*itHyp).second;
349 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
350 if ( creator == (*itHyp2).second )
351 (*itHyp2).second = 0;
353 myHypCreatorMap.clear();
355 // Clear study contexts data
356 map<int, StudyContext*>::iterator it;
357 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
360 myStudyContextMap.clear();
361 // delete shape reader
363 delete myShapeReader;
365 //=============================================================================
367 * SMESH_Gen_i::getHypothesisCreator
369 * Get hypothesis creator
371 //=============================================================================
372 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
373 const char* theLibName,
374 std::string& thePlatformLibName)
375 throw (SALOME::SALOME_Exception)
377 std::string aPlatformLibName;
378 /* It's Need to tranlate lib name for WIN32 or X platform */
379 if ( theLibName && theLibName[0] != '\0' )
381 int libNameLen = strlen(theLibName);
382 //check for old format "libXXXXXXX.so"
383 if (libNameLen > 7 &&
384 !strncmp( theLibName, "lib", 3 ) &&
385 !strcmp( theLibName+libNameLen-3, ".so" ))
389 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
391 aPlatformLibName = theLibName;
396 //try to use new format
398 aPlatformLibName = theLibName;
399 aPlatformLibName += ".dll";
401 aPlatformLibName = "lib" + std::string( theLibName ) + ".so";
405 thePlatformLibName = aPlatformLibName;
407 Unexpect aCatch(SALOME_SalomeException);
408 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
410 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
411 GenericHypothesisCreator_i* aCreator;
414 // check, if creator for this hypothesis type already exists
415 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
417 // load plugin library
418 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
419 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
422 // report any error, if occured
424 const char* anError = dlerror();
425 throw(SALOME_Exception(anError));
427 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
431 // get method, returning hypothesis creator
432 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
433 GetHypothesisCreator procHandle =
434 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
437 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
438 UnLoadLib(libHandle);
441 // get hypothesis creator
442 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
443 aCreator = procHandle(theHypName);
446 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
448 // map hypothesis creator to a hypothesis name
449 myHypCreatorMap[string(theHypName)] = aCreator;
454 return myHypCreatorMap[string(theHypName)];
457 catch (SALOME_Exception& S_ex)
459 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
464 //=============================================================================
466 * SMESH_Gen_i::createHypothesis
468 * Create hypothesis of given type
470 //=============================================================================
471 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
472 const char* theLibName)
474 SMESH_Hypothesis_i* myHypothesis_i = 0;
475 SMESH::SMESH_Hypothesis_var hypothesis_i;
476 std::string aPlatformLibName;
477 GenericHypothesisCreator_i* aCreator =
478 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
480 // create a new hypothesis object, store its ref. in studyContext
481 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
484 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
485 CORBA::String_var hypName = myHypothesis_i->GetName();
486 myHypCreatorMap[ hypName.in() ] = aCreator;
488 // activate the CORBA servant of hypothesis
489 hypothesis_i = myHypothesis_i->_this();
490 int nextId = RegisterObject( hypothesis_i );
491 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
492 else { nextId = 0; } // avoid "unused variable" warning in release mode
494 return hypothesis_i._retn();
497 //=============================================================================
499 * SMESH_Gen_i::createMesh
501 * Create empty mesh on shape
503 //=============================================================================
504 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
505 throw ( SALOME::SALOME_Exception )
507 Unexpect aCatch(SALOME_SalomeException);
508 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
510 // Get or create the GEOM_Client instance
512 // create a new mesh object servant, store it in a map in study context
513 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
514 // create a new mesh object
515 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
516 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
518 // activate the CORBA servant of Mesh
519 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
520 int nextId = RegisterObject( mesh );
521 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
522 else { nextId = 0; } // avoid "unused variable" warning in release mode
525 catch (SALOME_Exception& S_ex) {
526 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
528 return SMESH::SMESH_Mesh::_nil();
531 //=============================================================================
533 * SMESH_Gen_i::GetShapeReader
537 //=============================================================================
538 GEOM_Client* SMESH_Gen_i::GetShapeReader()
540 // create shape reader if necessary
541 if ( !myShapeReader )
542 myShapeReader = new GEOM_Client(GetContainerRef());
543 ASSERT( myShapeReader );
544 return myShapeReader;
547 //=============================================================================
549 * SMESH_Gen_i::SetGeomEngine
551 * Set GEOM::GEOM_Gen reference
553 //=============================================================================
554 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
555 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
557 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
558 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
559 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
563 //=============================================================================
565 * SMESH_Gen_i::SetEmbeddedMode
569 //=============================================================================
571 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
573 myIsEmbeddedMode = theMode;
574 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
576 if ( !myIsEmbeddedMode ) {
577 //PAL10867: disable signals catching with "noexcepthandler" option
578 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
579 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
584 char* envDisableFPE = getenv("DISABLE_FPE");
585 if (envDisableFPE && atoi(envDisableFPE))
590 OSD::SetSignal( raiseFPE );
592 // else OSD::SetSignal() is called in GUI
596 //=============================================================================
598 * SMESH_Gen_i::IsEmbeddedMode
602 //=============================================================================
604 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
606 return myIsEmbeddedMode;
609 //=============================================================================
611 * SMESH_Gen_i::SetCurrentStudy
615 //=============================================================================
617 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
619 setCurrentStudy( theStudy );
622 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
623 bool theStudyIsBeingClosed)
625 int curStudyId = GetCurrentStudyID();
626 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
627 // create study context, if it doesn't exist and set current study
628 int studyId = GetCurrentStudyID();
629 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
630 myStudyContextMap[ studyId ] = new StudyContext;
632 // myCurrentStudy may be nil
633 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
634 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
635 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
636 if( !GEOM_var->_is_nil() )
637 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
638 // NPAL16168, issue 0020210
639 // Let meshes update their data depending on GEOM groups that could change
640 if ( curStudyId != studyId )
642 CORBA::String_var compDataType = ComponentDataType();
643 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
644 if ( !me->_is_nil() ) {
645 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
646 for ( ; anIter->More(); anIter->Next() ) {
647 SALOMEDS::SObject_wrap so = anIter->Value();
648 CORBA::Object_var ior = SObjectToObject( so );
649 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
650 mesh->CheckGeomModif();
657 //=============================================================================
659 * SMESH_Gen_i::GetCurrentStudy
663 //=============================================================================
665 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
667 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
668 if ( GetCurrentStudyID() < 0 )
669 return SALOMEDS::Study::_nil();
670 return SALOMEDS::Study::_duplicate( myCurrentStudy );
673 //=============================================================================
675 * SMESH_Gen_i::GetCurrentStudyContext
677 * Get current study context
679 //=============================================================================
680 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
682 if ( !CORBA::is_nil( myCurrentStudy ) &&
683 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
684 return myStudyContextMap[ myCurrentStudy->StudyId() ];
689 //=============================================================================
691 * SMESH_Gen_i::CreateHypothesis
693 * Create hypothesis/algorothm of given type and publish it in the study
695 //=============================================================================
697 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
698 const char* theLibName )
699 throw ( SALOME::SALOME_Exception )
701 Unexpect aCatch(SALOME_SalomeException);
702 // Create hypothesis/algorithm
703 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
705 // Publish hypothesis/algorithm in the study
706 if ( CanPublishInStudy( hyp ) ) {
707 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
708 if ( !aSO->_is_nil() ) {
709 // Update Python script
710 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
711 << theHypName << "', '" << theLibName << "')";
718 //================================================================================
720 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
721 * existing on the given geometry or to size of the geometry.
722 * \param theHypType - hypothesis type name
723 * \param theLibName - plugin library name
724 * \param theMesh - The mesh of interest
725 * \param theGeom - The shape to get parameter values from
726 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
727 * in a study and used to compute the mesh, or a temporary one created just to pass
730 //================================================================================
732 SMESH::SMESH_Hypothesis_ptr
733 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
734 const char* theLibName,
735 SMESH::SMESH_Mesh_ptr theMesh,
736 GEOM::GEOM_Object_ptr theGeom,
737 CORBA::Boolean byMesh)
738 throw ( SALOME::SALOME_Exception )
740 Unexpect aCatch(SALOME_SalomeException);
741 if ( byMesh && CORBA::is_nil( theMesh ) )
742 return SMESH::SMESH_Hypothesis::_nil();
743 if ( byMesh && CORBA::is_nil( theGeom ) )
744 return SMESH::SMESH_Hypothesis::_nil();
746 // -----------------------------------------------
747 // find hypothesis used to mesh theGeom
748 // -----------------------------------------------
750 // get mesh and shape
751 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
752 TopoDS_Shape shape = GeomObjectToShape( theGeom );
753 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
754 return SMESH::SMESH_Hypothesis::_nil();
755 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
757 // create a temporary hypothesis to know its dimension
758 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
759 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
761 return SMESH::SMESH_Hypothesis::_nil();
762 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
765 // look for a hypothesis of theHypType used to mesh the shape
766 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
769 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
770 int nbLocalHyps = aHypList->length();
771 for ( int i = 0; i < nbLocalHyps; i++ ) {
772 CORBA::String_var hypName = aHypList[i]->GetName();
773 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
774 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
776 // check super shapes
777 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
778 while ( nbLocalHyps == 0 && itShape.More() ) {
779 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
780 if ( ! CORBA::is_nil( geomObj )) {
781 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
782 nbLocalHyps = aHypList->length();
783 for ( int i = 0; i < nbLocalHyps; i++ )
784 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
785 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
791 // let the temporary hypothesis find out somehow parameter values by mesh
792 if ( hyp->SetParametersByMesh( mesh, shape ))
793 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
798 diagonal = mesh->GetShapeDiagonalSize();
800 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
801 ::SMESH_Hypothesis::TDefaults dflts;
802 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
803 dflts._nbSegments = myGen.GetDefaultNbSegments();
804 dflts._shape = &shape;
805 // let the temporary hypothesis initialize it's values
806 if ( hyp->SetParametersByDefaults( dflts, mesh ))
807 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
810 return SMESH::SMESH_Hypothesis::_nil();
813 //=============================================================================
815 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
816 * \param [in] theHyp - the hypothesis of interest
817 * \param [out] theMesh - the sole mesh using \a theHyp
818 * \param [out] theShape - the sole geometry \a theHyp is assigned to
819 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
821 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
822 * considered as SAME sub-mesh => result is \c true.
823 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
824 * a shape to which an hyp being edited is assigned.
826 //=============================================================================
828 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
829 SMESH::SMESH_Mesh_out theMesh,
830 GEOM::GEOM_Object_out theShape)
832 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
835 // get Mesh component SO
836 CORBA::String_var compDataType = ComponentDataType();
837 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
838 if ( CORBA::is_nil( comp ))
841 // look for child SO of meshes
842 SMESH::SMESH_Mesh_var foundMesh;
843 TopoDS_Shape foundShape;
845 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
846 for ( ; meshIter->More() && isSole; meshIter->Next() )
848 SALOMEDS::SObject_wrap curSO = meshIter->Value();
849 CORBA::Object_var obj = SObjectToObject( curSO );
850 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
854 // look for a sole shape where theHyp is assigned
855 bool isHypFound = false;
856 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
857 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
858 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
860 const THypList& hyps = s2hypsIt.Value();
861 THypList::const_iterator h = hyps.begin();
862 for ( ; h != hyps.end(); ++h )
863 if ( (*h)->GetID() == theHyp->GetId() )
865 if ( h != hyps.end()) // theHyp found
868 if ( ! foundShape.IsNull() &&
869 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
871 foundShape.Nullify();
875 foundShape = s2hypsIt.Key();
877 } // loop on assigned hyps
879 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
881 if ( !foundMesh->_is_nil() ) // not a sole mesh
883 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
884 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
885 if ( ! ( isSole = s1->IsSame( s2 )))
888 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
894 ! foundMesh->_is_nil() &&
895 ! foundShape.IsNull() )
897 theMesh = foundMesh._retn();
898 theShape = ShapeToGeomObject( foundShape );
899 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
904 //=============================================================================
906 * Sets number of segments per diagonal of boundary box of geometry by which
907 * default segment length of appropriate 1D hypotheses is defined
909 //=============================================================================
911 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
912 throw ( SALOME::SALOME_Exception )
914 if ( theNbSegments > 0 )
915 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
917 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
919 //=============================================================================
921 * \brief Sets default number of segments per edge
923 //=============================================================================
924 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
925 throw ( SALOME::SALOME_Exception )
927 if ( theNbSegments > 0 )
928 myGen.SetDefaultNbSegments( int(theNbSegments) );
930 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
933 //=============================================================================
937 //=============================================================================
939 void SMESH_Gen_i::SetOption(const char* name, const char* value)
941 if ( name && value && strlen( value ) > 0 )
944 if ( strcmp(name, "historical_python_dump") == 0 )
946 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
947 msgToGUI = "preferences/SMESH/historical_python_dump/";
948 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
950 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
952 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
953 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
954 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
957 // update preferences in case if SetOption() is invoked from python console
958 if ( !msgToGUI.empty() )
960 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
961 SALOME::Session_var session = SALOME::Session::_narrow( obj );
962 if ( !CORBA::is_nil( session ) )
963 session->emitMessageOneWay(msgToGUI.c_str());
968 //=============================================================================
970 Return an option value
972 //=============================================================================
974 char* SMESH_Gen_i::GetOption(const char* name)
978 if ( strcmp(name, "historical_python_dump") == 0 )
980 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
982 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
984 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
987 return CORBA::string_dup( "" );
990 //=============================================================================
992 * SMESH_Gen_i::CreateMesh
994 * Create empty mesh on a shape and publish it in the study
996 //=============================================================================
998 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
999 throw ( SALOME::SALOME_Exception )
1001 Unexpect aCatch(SALOME_SalomeException);
1002 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1004 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1006 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1007 ASSERT( meshServant );
1008 meshServant->SetShape( theShapeObject );
1010 // publish mesh in the study
1011 if ( CanPublishInStudy( mesh ) ) {
1012 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1013 aStudyBuilder->NewCommand(); // There is a transaction
1014 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1015 aStudyBuilder->CommitCommand();
1016 if ( !aSO->_is_nil() ) {
1017 // Update Python script
1018 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1022 return mesh._retn();
1025 //=============================================================================
1027 * SMESH_Gen_i::CreateEmptyMesh
1031 //=============================================================================
1033 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1034 throw ( SALOME::SALOME_Exception )
1036 Unexpect aCatch(SALOME_SalomeException);
1037 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1039 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1041 // publish mesh in the study
1042 if ( CanPublishInStudy( mesh ) ) {
1043 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1044 aStudyBuilder->NewCommand(); // There is a transaction
1045 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1046 aStudyBuilder->CommitCommand();
1047 if ( !aSO->_is_nil() ) {
1048 // Update Python script
1049 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1053 return mesh._retn();
1058 //================================================================================
1060 * \brief Throws an exception in case if the file can't be read
1062 //================================================================================
1064 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1066 SMESH_File f ( theFileName );
1069 if ( !f.error().empty() )
1070 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1072 THROW_SALOME_CORBA_EXCEPTION
1073 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1074 SALOME::BAD_PARAM );
1079 //=============================================================================
1081 * SMESH_Gen_i::CreateMeshFromUNV
1083 * Create mesh and import data from UNV file
1085 //=============================================================================
1087 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1088 throw ( SALOME::SALOME_Exception )
1090 Unexpect aCatch(SALOME_SalomeException);
1092 checkFileReadable( theFileName );
1094 SMESH::SMESH_Mesh_var aMesh = createMesh();
1096 // publish mesh in the study
1097 if ( CanPublishInStudy( aMesh ) ) {
1098 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1099 aStudyBuilder->NewCommand(); // There is a transaction
1100 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1101 aStudyBuilder->CommitCommand();
1102 if ( !aSO->_is_nil() ) {
1103 // Update Python script
1104 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1108 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1110 aServant->ImportUNVFile( theFileName );
1112 // Dump creation of groups
1113 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1115 aServant->GetImpl().GetMeshDS()->Modified();
1116 return aMesh._retn();
1119 //=============================================================================
1121 * SMESH_Gen_i::CreateMeshFromMED
1123 * Create mesh and import data from MED file
1125 //=============================================================================
1127 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1128 SMESH::DriverMED_ReadStatus& theStatus,
1129 const char* theCommandNameForPython,
1130 const char* theFileNameForPython)
1133 char bname[ _MAX_FNAME ];
1134 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1135 string aFileName = bname;
1137 string aFileName = basename( theFileNameForPython );
1139 // Retrieve mesh names from the file
1140 DriverMED_R_SMESHDS_Mesh myReader;
1141 myReader.SetFile( theFileName );
1142 myReader.SetMeshId( -1 );
1143 Driver_Mesh::Status aStatus;
1144 list<string> aNames = myReader.GetMeshNames(aStatus);
1145 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1146 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1148 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1151 TPythonDump aPythonDump;
1152 aPythonDump << "([";
1154 if (theStatus == SMESH::DRS_OK) {
1155 SALOMEDS::StudyBuilder_var aStudyBuilder;
1156 if ( GetCurrentStudyID() > -1 )
1158 aStudyBuilder = myCurrentStudy->NewBuilder();
1159 aStudyBuilder->NewCommand(); // There is a transaction
1161 aResult->length( aNames.size() );
1164 // Iterate through all meshes and create mesh objects
1165 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1168 if (i > 0) aPythonDump << ", ";
1171 SMESH::SMESH_Mesh_var mesh = createMesh();
1173 // publish mesh in the study
1174 SALOMEDS::SObject_wrap aSO;
1175 if ( CanPublishInStudy( mesh ) )
1176 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1177 // - as names of meshes are stored in MED file, we use them for data publishing
1178 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1179 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1180 if ( !aSO->_is_nil() ) {
1185 aPythonDump << "mesh_" << i;
1188 // Read mesh data (groups are published automatically by ImportMEDFile())
1189 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1190 ASSERT( meshServant );
1191 SMESH::DriverMED_ReadStatus status1 =
1192 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1193 if (status1 > theStatus)
1194 theStatus = status1;
1196 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1197 meshServant->GetImpl().GetMeshDS()->Modified();
1199 if ( !aStudyBuilder->_is_nil() )
1200 aStudyBuilder->CommitCommand();
1203 // Update Python script
1204 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1206 // Dump creation of groups
1207 for ( int i = 0; i < aResult->length(); ++i )
1208 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1210 return aResult._retn();
1213 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1214 SMESH::DriverMED_ReadStatus& theStatus)
1215 throw ( SALOME::SALOME_Exception )
1217 Unexpect aCatch(SALOME_SalomeException);
1218 checkFileReadable( theFileName );
1220 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1224 //=============================================================================
1226 * SMESH_Gen_i::CreateMeshFromSAUV
1228 * Create mesh and import data from SAUV file
1230 //=============================================================================
1232 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1233 SMESH::DriverMED_ReadStatus& theStatus)
1234 throw ( SALOME::SALOME_Exception )
1236 Unexpect aCatch(SALOME_SalomeException);
1237 checkFileReadable( theFileName );
1239 std::string sauvfilename(theFileName);
1240 std::string medfilename(theFileName);
1241 medfilename += ".med";
1244 cmd = "%PYTHONBIN% ";
1249 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1251 system(cmd.c_str());
1252 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1254 cmd = "%PYTHONBIN% ";
1259 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1261 system(cmd.c_str());
1265 //=============================================================================
1267 * SMESH_Gen_i::CreateMeshFromSTL
1269 * Create mesh and import data from STL file
1271 //=============================================================================
1273 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1274 throw ( SALOME::SALOME_Exception )
1276 Unexpect aCatch(SALOME_SalomeException);
1277 checkFileReadable( theFileName );
1279 SMESH::SMESH_Mesh_var aMesh = createMesh();
1282 char bname[ _MAX_FNAME ];
1283 _splitpath( theFileName, NULL, NULL, bname, NULL );
1284 string aFileName = bname;
1286 string aFileName = basename( theFileName );
1288 // publish mesh in the study
1289 if ( CanPublishInStudy( aMesh ) ) {
1290 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1291 aStudyBuilder->NewCommand(); // There is a transaction
1292 SALOMEDS::SObject_wrap aSO = PublishInStudy
1293 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1294 aStudyBuilder->CommitCommand();
1295 if ( !aSO->_is_nil() ) {
1296 // Update Python script
1297 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1301 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1303 aServant->ImportSTLFile( theFileName );
1304 aServant->GetImpl().GetMeshDS()->Modified();
1305 return aMesh._retn();
1308 //================================================================================
1310 * \brief Create meshes and import data from the CGSN file
1312 //================================================================================
1314 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1315 SMESH::DriverMED_ReadStatus& theStatus)
1316 throw ( SALOME::SALOME_Exception )
1318 Unexpect aCatch(SALOME_SalomeException);
1319 checkFileReadable( theFileName );
1321 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1324 // Retrieve nb meshes from the file
1325 DriverCGNS_Read myReader;
1326 myReader.SetFile( theFileName );
1327 Driver_Mesh::Status aStatus;
1328 int nbMeshes = myReader.GetNbMeshes(aStatus);
1329 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1331 aResult->length( nbMeshes );
1333 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1336 TPythonDump aPythonDump;
1337 aPythonDump << "([";
1339 if (theStatus == SMESH::DRS_OK)
1341 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1342 aStudyBuilder->NewCommand(); // There is a transaction
1346 // Iterate through all meshes and create mesh objects
1347 for ( ; i < nbMeshes; ++i )
1350 if (i > 0) aPythonDump << ", ";
1353 SMESH::SMESH_Mesh_var mesh = createMesh();
1354 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1356 // Read mesh data (groups are published automatically by ImportMEDFile())
1357 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1358 ASSERT( meshServant );
1360 SMESH::DriverMED_ReadStatus status1 =
1361 meshServant->ImportCGNSFile( theFileName, i, meshName );
1362 if (status1 > theStatus)
1363 theStatus = status1;
1365 meshServant->GetImpl().GetMeshDS()->Modified();
1366 // publish mesh in the study
1367 SALOMEDS::SObject_wrap aSO;
1368 if ( CanPublishInStudy( mesh ) )
1369 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1372 if ( !aSO->_is_nil() ) {
1376 aPythonDump << "mesh_" << i;
1379 aStudyBuilder->CommitCommand();
1382 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1384 // Dump creation of groups
1385 for ( int i = 0; i < aResult->length(); ++i )
1386 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1388 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1391 return aResult._retn();
1394 //================================================================================
1396 * \brief Create a mesh and import data from a GMF file
1398 //================================================================================
1400 SMESH::SMESH_Mesh_ptr
1401 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1402 CORBA::Boolean theMakeRequiredGroups,
1403 SMESH::ComputeError_out theError)
1404 throw ( SALOME::SALOME_Exception )
1406 Unexpect aCatch(SALOME_SalomeException);
1407 checkFileReadable( theFileName );
1409 SMESH::SMESH_Mesh_var aMesh = createMesh();
1411 char bname[ _MAX_FNAME ];
1412 _splitpath( theFileName, NULL, NULL, bname, NULL );
1413 string aFileName = bname;
1415 string aFileName = basename( theFileName );
1417 // publish mesh in the study
1418 if ( CanPublishInStudy( aMesh ) ) {
1419 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1420 aStudyBuilder->NewCommand(); // There is a transaction
1421 SALOMEDS::SObject_wrap aSO = PublishInStudy
1422 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1423 aStudyBuilder->CommitCommand();
1424 if ( !aSO->_is_nil() ) {
1425 // Update Python script
1426 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1427 << theFileName << "', "
1428 << theMakeRequiredGroups << " )";
1431 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1433 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1434 aServant->GetImpl().GetMeshDS()->Modified();
1435 return aMesh._retn();
1439 //=============================================================================
1441 * SMESH_Gen_i::IsReadyToCompute
1443 * Returns true if mesh contains enough data to be computed
1445 //=============================================================================
1447 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1448 GEOM::GEOM_Object_ptr theShapeObject )
1449 throw ( SALOME::SALOME_Exception )
1451 Unexpect aCatch(SALOME_SalomeException);
1452 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1454 if ( CORBA::is_nil( theShapeObject ) )
1455 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1456 SALOME::BAD_PARAM );
1458 if ( CORBA::is_nil( theMesh ) )
1459 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1460 SALOME::BAD_PARAM );
1464 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1465 ASSERT( meshServant );
1466 if ( meshServant ) {
1467 // get local TopoDS_Shape
1468 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1469 // call implementation
1470 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1471 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1474 catch ( SALOME_Exception& S_ex ) {
1475 INFOS( "catch exception "<< S_ex.what() );
1480 //================================================================================
1482 * \brief Find SObject for an algo
1484 //================================================================================
1486 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1489 if ( !myCurrentStudy->_is_nil() ) {
1490 // find algo in the study
1491 CORBA::String_var compDataType = ComponentDataType();
1492 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1493 if ( !father->_is_nil() ) {
1494 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1495 for ( ; itBig->More(); itBig->Next() ) {
1496 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1497 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1498 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1499 for ( ; algoIt->More(); algoIt->Next() ) {
1500 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1501 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1502 if ( !CORBA::is_nil( algoIOR )) {
1503 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1504 if ( impl && impl->GetImpl() == algo )
1505 return algoSO._retn();
1507 } // loop on algo SO's
1510 } // SMESH component iterator
1514 return SALOMEDS::SObject::_nil();
1517 //================================================================================
1519 * \brief Return errors of mesh computation
1521 //================================================================================
1523 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1524 GEOM::GEOM_Object_ptr theSubObject )
1525 throw ( SALOME::SALOME_Exception )
1527 Unexpect aCatch(SALOME_SalomeException);
1528 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1530 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1531 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1533 if ( CORBA::is_nil( theMesh ) )
1534 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1536 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1538 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1541 if(theMesh->HasShapeToMesh())
1542 shape = GeomObjectToShape( theSubObject );
1544 shape = SMESH_Mesh::PseudoShape();
1546 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1548 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1551 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1552 const bool includeSelf = true, complexShapeFirst = true;
1553 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1555 while ( smIt->more() )
1558 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1560 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1561 if ( error && !error->IsOK() )
1563 if ( !( error->myAlgo ) &&
1564 !( error->myAlgo = sm->GetAlgo() ))
1566 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1567 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1568 errStruct.comment = error->myComment.c_str();
1569 errStruct.subShapeID = sm->GetId();
1570 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1571 if ( !algoSO->_is_nil() ) {
1572 CORBA::String_var algoName = algoSO->GetName();
1573 errStruct.algoName = algoName;
1576 errStruct.algoName = error->myAlgo->GetName();
1578 errStruct.hasBadMesh = !error->myBadElements.empty();
1581 error_array->length( nbErr );
1584 catch ( SALOME_Exception& S_ex ) {
1585 INFOS( "catch exception "<< S_ex.what() );
1588 return error_array._retn();
1591 //================================================================================
1593 * \brief Return mesh elements preventing computation of a subshape
1595 //================================================================================
1597 SMESH::MeshPreviewStruct*
1598 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1599 CORBA::Short theSubShapeID )
1600 throw ( SALOME::SALOME_Exception )
1602 Unexpect aCatch(SALOME_SalomeException);
1603 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1605 if ( CORBA::is_nil( theMesh ) )
1606 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1608 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1611 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1613 // mesh implementation
1614 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1615 // submesh by subshape id
1616 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1619 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1620 if ( error && !error->myBadElements.empty())
1622 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1623 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1625 // get nodes of elements and count elements
1626 TNode2LocalIDMap mapNode2LocalID;
1627 list< TNodeLocalID > connectivity;
1628 int i, nbElements = 0, nbConnNodes = 0;
1630 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1631 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1632 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1634 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1635 while ( nIt->more() )
1636 connectivity.push_back
1637 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1639 // fill node coords and assign local ids to the nodes
1640 int nbNodes = mapNode2LocalID.size();
1641 result->nodesXYZ.length( nbNodes );
1642 TNodeLocalID node2ID = mapNode2LocalID.begin();
1643 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1644 node2ID->second = i;
1645 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1646 result->nodesXYZ[i].x = node->X();
1647 result->nodesXYZ[i].y = node->Y();
1648 result->nodesXYZ[i].z = node->Z();
1650 // fill connectivity
1651 result->elementConnectivities.length( nbConnNodes );
1652 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1653 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1654 result->elementConnectivities[i] = (*connIt)->second;
1656 // fill element types
1657 result->elementTypes.length( nbElements );
1658 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1660 const SMDS_MeshElement* elem = *elemIt;
1661 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1662 result->elementTypes[i].isPoly = elem->IsPoly();
1663 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1669 catch ( SALOME_Exception& S_ex ) {
1670 INFOS( "catch exception "<< S_ex.what() );
1673 return result._retn();
1676 //================================================================================
1678 * \brief Create a group of elements preventing computation of a sub-shape
1680 //================================================================================
1682 SMESH::ListOfGroups*
1683 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1684 CORBA::Short theSubShapeID,
1685 const char* theGroupName )
1686 throw ( SALOME::SALOME_Exception )
1688 Unexpect aCatch(SALOME_SalomeException);
1690 SMESH::ListOfGroups_var groups;
1692 if ( CORBA::is_nil( theMesh ) )
1693 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1696 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1698 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1699 TPythonDump() << groups << " = " << this
1700 << ".MakeGroupsOfBadInputElements( "
1701 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1704 catch ( SALOME_Exception& S_ex ) {
1705 INFOS( "catch exception "<< S_ex.what() );
1707 return groups._retn();
1710 //================================================================================
1712 * \brief Returns errors of hypotheses definintion
1713 * \param theMesh - the mesh
1714 * \param theSubObject - the main or sub- shape
1715 * \retval SMESH::algo_error_array* - sequence of errors
1717 //================================================================================
1719 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1720 GEOM::GEOM_Object_ptr theSubObject )
1721 throw ( SALOME::SALOME_Exception )
1723 Unexpect aCatch(SALOME_SalomeException);
1724 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1726 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1727 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1729 if ( CORBA::is_nil( theMesh ) )
1730 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1732 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1734 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1735 ASSERT( meshServant );
1736 if ( meshServant ) {
1737 TopoDS_Shape myLocShape;
1738 if(theMesh->HasShapeToMesh())
1739 myLocShape = GeomObjectToShape( theSubObject );
1741 myLocShape = SMESH_Mesh::PseudoShape();
1743 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1744 list< ::SMESH_Gen::TAlgoStateError > error_list;
1745 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1746 // call ::SMESH_Gen::GetAlgoState()
1747 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1748 error_array->length( error_list.size() );
1750 for ( error = error_list.begin(); error != error_list.end(); ++error )
1752 // fill AlgoStateError structure
1753 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1754 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1755 errStruct.algoDim = error->_algoDim;
1756 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1757 errStruct.algoName = "";
1758 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1759 if ( !algoSO->_is_nil() ) {
1760 CORBA::String_var algoName = algoSO->GetName();
1761 errStruct.algoName = algoName.in();
1766 catch ( SALOME_Exception& S_ex ) {
1767 INFOS( "catch exception "<< S_ex.what() );
1769 return error_array._retn();
1772 //=============================================================================
1774 * SMESH_Gen_i::GetSubShapesId
1776 * Get sub-shapes unique ID's list
1778 //=============================================================================
1780 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1781 const SMESH::object_array& theListOfSubShapeObject )
1782 throw ( SALOME::SALOME_Exception )
1784 Unexpect aCatch(SALOME_SalomeException);
1785 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1787 SMESH::long_array_var shapesId = new SMESH::long_array;
1790 if ( CORBA::is_nil( theMainShapeObject ) )
1791 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1792 SALOME::BAD_PARAM );
1796 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1797 TopTools_IndexedMapOfShape myIndexToShape;
1798 TopExp::MapShapes(myMainShape,myIndexToShape);
1800 for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1802 GEOM::GEOM_Object_var aShapeObject
1803 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1804 if ( CORBA::is_nil( aShapeObject ) )
1805 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1806 SALOME::BAD_PARAM );
1808 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1809 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1811 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1812 setId.insert(myIndexToShape.FindIndex(F));
1813 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1815 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1817 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1818 setId.insert(myIndexToShape.FindIndex(E));
1819 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1821 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1823 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1824 setId.insert(myIndexToShape.FindIndex(V));
1825 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1828 shapesId->length(setId.size());
1829 set<int>::iterator iind;
1831 for (iind = setId.begin(); iind != setId.end(); iind++)
1833 if(MYDEBUG) SCRUTE((*iind));
1834 shapesId[i] = (*iind);
1835 if(MYDEBUG) SCRUTE(shapesId[i]);
1839 catch (SALOME_Exception& S_ex)
1841 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1844 return shapesId._retn();
1847 //=============================================================================
1849 * SMESH_Gen_i::Compute
1851 * Compute mesh on a shape
1853 //=============================================================================
1855 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1856 GEOM::GEOM_Object_ptr theShapeObject )
1857 throw ( SALOME::SALOME_Exception )
1860 Unexpect aCatch(SALOME_SalomeException);
1861 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1863 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1864 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1865 SALOME::BAD_PARAM );
1867 if ( CORBA::is_nil( theMesh ) )
1868 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1869 SALOME::BAD_PARAM );
1871 // Update Python script
1872 TPythonDump() << "isDone = " << this << ".Compute( "
1873 << theMesh << ", " << theShapeObject << ")";
1877 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1878 ASSERT( meshServant );
1879 if ( meshServant ) {
1880 meshServant->Load();
1881 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1882 meshServant->CheckGeomModif();
1883 // get local TopoDS_Shape
1884 TopoDS_Shape myLocShape;
1885 if(theMesh->HasShapeToMesh())
1886 myLocShape = GeomObjectToShape( theShapeObject );
1888 myLocShape = SMESH_Mesh::PseudoShape();
1889 // call implementation compute
1890 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1891 myGen.PrepareCompute( myLocMesh, myLocShape);
1892 bool ok = myGen.Compute( myLocMesh, myLocShape);
1893 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1894 myLocMesh.GetMeshDS()->Modified();
1898 catch ( std::bad_alloc ) {
1899 INFOS( "Compute(): lack of memory" );
1901 catch ( SALOME_Exception& S_ex ) {
1902 INFOS( "Compute(): catch exception "<< S_ex.what() );
1905 INFOS( "Compute(): unknown exception " );
1910 //=============================================================================
1912 * SMESH_Gen_i::CancelCompute
1914 * Cancel Compute mesh on a shape
1916 //=============================================================================
1918 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1919 GEOM::GEOM_Object_ptr theShapeObject )
1921 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1922 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1923 TopoDS_Shape myLocShape;
1924 if(theMesh->HasShapeToMesh())
1925 myLocShape = GeomObjectToShape( theShapeObject );
1927 myLocShape = SMESH_Mesh::PseudoShape();
1928 myGen.CancelCompute( myLocMesh, myLocShape);
1931 //=============================================================================
1933 * SMESH_Gen_i::Precompute
1935 * Compute mesh as preview till indicated dimension on shape
1937 //=============================================================================
1939 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1940 GEOM::GEOM_Object_ptr theShapeObject,
1941 SMESH::Dimension theDimension,
1942 SMESH::long_array& theShapesId)
1943 throw ( SALOME::SALOME_Exception )
1945 Unexpect aCatch(SALOME_SalomeException);
1946 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1948 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1949 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1950 SALOME::BAD_PARAM );
1952 if ( CORBA::is_nil( theMesh ) )
1953 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1954 SALOME::BAD_PARAM );
1956 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1959 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1960 meshServant->Load();
1961 ASSERT( meshServant );
1962 if ( meshServant ) {
1963 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1964 meshServant->CheckGeomModif();
1965 // get local TopoDS_Shape
1966 TopoDS_Shape myLocShape;
1967 if(theMesh->HasShapeToMesh())
1968 myLocShape = GeomObjectToShape( theShapeObject );
1970 return result._retn();;
1972 // call implementation compute
1973 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1975 ::MeshDimension aDim = (MeshDimension)theDimension;
1976 if ( myGen.Compute( myLocMesh, myLocShape, false, false, aDim, &shapeIds ) )
1978 int nbShapeId = shapeIds.size();
1979 theShapesId.length( nbShapeId );
1980 // iterates on shapes and collect mesh entities into mesh preview
1981 TSetOfInt::const_iterator idIt = shapeIds.begin();
1982 TSetOfInt::const_iterator idEnd = shapeIds.end();
1983 std::map< int, int > mapOfShIdNb;
1984 std::set< SMESH_TLink > setOfEdge;
1985 std::list< SMDSAbs_ElementType > listOfElemType;
1986 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1987 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1988 TNode2LocalIDMap mapNode2LocalID;
1989 list< TNodeLocalID > connectivity;
1990 int i, nbConnNodes = 0;
1991 std::set< const SMESH_subMesh* > setOfVSubMesh;
1992 // iterates on shapes
1993 for ( ; idIt != idEnd; idIt++ )
1995 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
1997 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
1998 if ( !sm || !sm->IsMeshComputed() )
2001 const TopoDS_Shape& aSh = sm->GetSubShape();
2002 const int shDim = myGen.GetShapeDim( aSh );
2003 if ( shDim < 1 || shDim > theDimension )
2006 mapOfShIdNb[ *idIt ] = 0;
2007 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2009 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2010 if ( !smDS ) continue;
2012 if ( theDimension == SMESH::DIM_2D )
2014 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2015 while ( faceIt->more() )
2017 const SMDS_MeshElement* face = faceIt->next();
2018 int aNbNode = face->NbNodes();
2020 aNbNode /= 2; // do not take into account additional middle nodes
2022 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2023 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2025 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2026 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2028 listOfElemType.push_back( SMDSAbs_Edge );
2029 connectivity.push_back
2030 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2031 connectivity.push_back
2032 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2038 else if ( theDimension == SMESH::DIM_1D )
2040 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2041 while ( nodeIt->more() )
2043 listOfElemType.push_back( SMDSAbs_Node );
2044 connectivity.push_back
2045 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2047 // add corner nodes by first vertex from edge
2048 SMESH_subMeshIteratorPtr edgeSmIt =
2049 sm->getDependsOnIterator(/*includeSelf*/false,
2050 /*complexShapeFirst*/false);
2051 while ( edgeSmIt->more() )
2053 SMESH_subMesh* vertexSM = edgeSmIt->next();
2054 // check that vertex is not already treated
2055 if ( !setOfVSubMesh.insert( vertexSM ).second )
2057 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2060 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2061 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2062 while ( nodeIt->more() )
2064 listOfElemType.push_back( SMDSAbs_Node );
2065 connectivity.push_back
2066 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2072 // fill node coords and assign local ids to the nodes
2073 int nbNodes = mapNode2LocalID.size();
2074 result->nodesXYZ.length( nbNodes );
2075 TNodeLocalID node2ID = mapNode2LocalID.begin();
2076 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2077 node2ID->second = i;
2078 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2079 result->nodesXYZ[i].x = node->X();
2080 result->nodesXYZ[i].y = node->Y();
2081 result->nodesXYZ[i].z = node->Z();
2083 // fill connectivity
2084 result->elementConnectivities.length( nbConnNodes );
2085 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2086 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2087 result->elementConnectivities[i] = (*connIt)->second;
2090 // fill element types
2091 result->elementTypes.length( listOfElemType.size() );
2092 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2093 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2094 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2096 SMDSAbs_ElementType elemType = *typeIt;
2097 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2098 result->elementTypes[i].isPoly = false;
2099 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2102 // correct number of shapes
2103 theShapesId.length( mapOfShIdNb.size() );
2107 catch ( std::bad_alloc ) {
2108 INFOS( "Precompute(): lack of memory" );
2110 catch ( SALOME_Exception& S_ex ) {
2111 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2114 INFOS( "Precompute(): unknown exception " );
2116 return result._retn();
2120 //=============================================================================
2122 * SMESH_Gen_i::Evaluate
2124 * Evaluate mesh on a shape
2126 //=============================================================================
2128 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2129 GEOM::GEOM_Object_ptr theShapeObject)
2130 // SMESH::long_array& theNbElems)
2131 throw ( SALOME::SALOME_Exception )
2133 Unexpect aCatch(SALOME_SalomeException);
2134 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2136 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2137 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2138 SALOME::BAD_PARAM );
2140 if ( CORBA::is_nil( theMesh ) )
2141 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2142 SALOME::BAD_PARAM );
2144 SMESH::long_array_var nbels = new SMESH::long_array;
2145 nbels->length(SMESH::Entity_Last);
2146 int i = SMESH::Entity_Node;
2147 for (; i < SMESH::Entity_Last; i++)
2150 // Update Python script
2151 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2152 << theMesh << ", " << theShapeObject << ")";
2156 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2157 ASSERT( meshServant );
2158 if ( meshServant ) {
2159 meshServant->Load();
2160 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2161 meshServant->CheckGeomModif();
2162 // get local TopoDS_Shape
2163 TopoDS_Shape myLocShape;
2164 if(theMesh->HasShapeToMesh())
2165 myLocShape = GeomObjectToShape( theShapeObject );
2167 myLocShape = SMESH_Mesh::PseudoShape();
2168 // call implementation compute
2169 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2170 MapShapeNbElems aResMap;
2171 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2172 MapShapeNbElemsItr anIt = aResMap.begin();
2173 for(; anIt!=aResMap.end(); anIt++) {
2174 const vector<int>& aVec = (*anIt).second;
2175 for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
2176 int nbElem = aVec[i];
2177 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2179 SMESH_subMesh* sm = anIt->first;
2180 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2181 const SMESH_Algo* algo = sm->GetAlgo();
2182 if ( (algo && !error.get()) || error->IsOK() )
2183 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2187 nbels[i] += aVec[i];
2191 return nbels._retn();
2194 catch ( std::bad_alloc ) {
2195 INFOS( "Evaluate(): lack of memory" );
2197 catch ( SALOME_Exception& S_ex ) {
2198 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2201 INFOS( "Evaluate(): unknown exception " );
2204 return nbels._retn();
2207 //================================================================================
2209 * \brief Return geometrical object the given element is built on
2210 * \param theMesh - the mesh the element is in
2211 * \param theElementID - the element ID
2212 * \param theGeomName - the name of the result geom object if it is not yet published
2213 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2215 //================================================================================
2217 GEOM::GEOM_Object_ptr
2218 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2219 CORBA::Long theElementID,
2220 const char* theGeomName)
2221 throw ( SALOME::SALOME_Exception )
2223 Unexpect aCatch(SALOME_SalomeException);
2225 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2226 if ( !geom->_is_nil() ) {
2227 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2228 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2230 // try to find the corresponding SObject
2231 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2232 if ( SObj->_is_nil() ) // submesh can be not found even if published
2234 // try to find published submesh
2235 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2236 if ( !geom->IsMainShape() && list->length() == 1 ) {
2237 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2238 SALOMEDS::ChildIterator_wrap it;
2239 if ( !mainSO->_is_nil() ) {
2240 it = myCurrentStudy->NewChildIterator( mainSO );
2242 if ( !it->_is_nil() ) {
2243 for ( it->InitEx(true); it->More(); it->Next() ) {
2244 SALOMEDS::SObject_wrap so = it->Value();
2245 CORBA::Object_var obj = SObjectToObject( so );
2246 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2247 if ( !subGeom->_is_nil() ) {
2248 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2249 if ( subList->length() == 1 && list[0] == subList[0] ) {
2259 if ( SObj->_is_nil() ) // publish a new subshape
2260 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2262 // return only published geometry
2263 if ( !SObj->_is_nil() ) {
2264 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2265 CORBA::Object_var obj = SObjectToObject( SObj );
2266 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2270 return GEOM::GEOM_Object::_nil();
2273 //================================================================================
2275 * \brief Return geometrical object the given element is built on.
2276 * \param theMesh - the mesh the element is in
2277 * \param theElementID - the element ID
2278 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2280 //================================================================================
2282 GEOM::GEOM_Object_ptr
2283 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2284 CORBA::Long theElementID)
2285 throw ( SALOME::SALOME_Exception )
2287 Unexpect aCatch(SALOME_SalomeException);
2288 if ( CORBA::is_nil( theMesh ) )
2289 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2291 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2292 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2294 // get a core mesh DS
2295 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2296 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2298 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2299 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2300 // find the element in mesh
2301 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2302 // find a shape id by the element
2303 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2304 // get a geom object by the shape id
2305 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2306 if ( geom->_is_nil() ) {
2307 // try to find a published sub-shape
2308 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2309 SALOMEDS::ChildIterator_wrap it;
2310 if ( !mainSO->_is_nil() ) {
2311 it = myCurrentStudy->NewChildIterator( mainSO );
2313 if ( !it->_is_nil() ) {
2314 for ( it->InitEx(true); it->More(); it->Next() ) {
2315 SALOMEDS::SObject_wrap so = it->Value();
2316 CORBA::Object_var obj = SObjectToObject( so );
2317 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2318 if ( !subGeom->_is_nil() ) {
2319 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2320 if ( subList->length() == 1 && shapeID == subList[0] ) {
2328 if ( geom->_is_nil() ) {
2330 GEOM::GEOM_IShapesOperations_wrap op =
2331 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2332 if ( !op->_is_nil() )
2333 geom = op->GetSubShape( mainShape, shapeID );
2338 if ( !geom->_is_nil() ) {
2339 GeomObjectToShape( geom ); // let geom client remember the found shape
2340 return geom._retn();
2345 return GEOM::GEOM_Object::_nil();
2348 //================================================================================
2350 * SMESH_Gen_i::Concatenate
2352 * Concatenate the given meshes into one mesh
2354 //================================================================================
2356 SMESH::SMESH_Mesh_ptr
2357 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2358 CORBA::Boolean theUniteIdenticalGroups,
2359 CORBA::Boolean theMergeNodesAndElements,
2360 CORBA::Double theMergeTolerance)
2361 throw ( SALOME::SALOME_Exception )
2363 return ConcatenateCommon(theMeshesArray,
2364 theUniteIdenticalGroups,
2365 theMergeNodesAndElements,
2370 //================================================================================
2372 * SMESH_Gen_i::ConcatenateWithGroups
2374 * Concatenate the given meshes into one mesh
2375 * Create the groups of all elements from initial meshes
2377 //================================================================================
2379 SMESH::SMESH_Mesh_ptr
2380 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2381 CORBA::Boolean theUniteIdenticalGroups,
2382 CORBA::Boolean theMergeNodesAndElements,
2383 CORBA::Double theMergeTolerance)
2384 throw ( SALOME::SALOME_Exception )
2386 return ConcatenateCommon(theMeshesArray,
2387 theUniteIdenticalGroups,
2388 theMergeNodesAndElements,
2393 //================================================================================
2395 * SMESH_Gen_i::ConcatenateCommon
2397 * Concatenate the given meshes into one mesh
2399 //================================================================================
2401 SMESH::SMESH_Mesh_ptr
2402 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2403 CORBA::Boolean theUniteIdenticalGroups,
2404 CORBA::Boolean theMergeNodesAndElements,
2405 CORBA::Double theMergeTolerance,
2406 CORBA::Boolean theCommonGroups)
2407 throw ( SALOME::SALOME_Exception )
2409 typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2410 typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2412 TPythonDump* pPythonDump = new TPythonDump;
2413 TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2416 SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2418 if ( aNewMesh->_is_nil() )
2419 return aNewMesh._retn();
2421 SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2423 return aNewMesh._retn();
2425 ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2426 SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2428 TGroupsMap aGroupsMap;
2429 TListOfNewGroups aListOfNewGroups;
2430 ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2431 SMESH::ListOfGroups_var aListOfGroups;
2433 ::SMESH_MeshEditor::ElemFeatures elemType;
2434 std::vector<const SMDS_MeshNode*> aNodesArray;
2436 // loop on sub-meshes
2437 for ( int i = 0; i < theMeshesArray.length(); i++)
2439 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2440 SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2441 if ( anInitMesh->_is_nil() ) continue;
2442 SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2443 if ( !anInitImpl ) continue;
2446 ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2447 SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2449 // remember nb of elements before filling in
2450 SMESH::long_array_var prevState = aNewMesh->GetNbElementsByType();
2452 typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2453 TEEMap elemsMap, nodesMap;
2455 // loop on elements of a sub-mesh
2456 SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2457 const SMDS_MeshElement* anElem;
2458 const SMDS_MeshElement* aNewElem;
2459 const SMDS_MeshNode* aNode;
2460 const SMDS_MeshNode* aNewNode;
2463 while ( itElems->more() )
2465 anElem = itElems->next();
2466 anElemNbNodes = anElem->NbNodes();
2467 aNodesArray.resize( anElemNbNodes );
2469 // loop on nodes of an element
2470 SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2471 for ( int k = 0; itNodes->more(); k++)
2473 aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2474 TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2475 if ( n2nnIt == nodesMap.end() )
2477 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2478 nodesMap.insert( make_pair( aNode, aNewNode ));
2482 aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2484 aNodesArray[k] = aNewNode;
2487 // creates a corresponding element on existent nodes in new mesh
2488 if ( anElem->GetType() == SMDSAbs_Node )
2492 aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2495 elemsMap.insert( make_pair( anElem, aNewElem ));
2499 aNewEditor.ClearLastCreated(); // forget the history
2502 // create groups of just added elements
2503 SMESH::SMESH_Group_var aNewGroup;
2504 SMESH::ElementType aGroupType;
2505 if ( theCommonGroups )
2507 SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2509 for( aGroupType = SMESH::NODE;
2510 aGroupType < SMESH::NB_ELEMENT_TYPES;
2511 aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2513 if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2516 // make a group name
2517 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2518 { // check of typeNames, compilation failure mains that NB_ELEMENT_TYPES changed:
2519 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2520 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 1 : -1 ];
2522 string groupName = "Gr";
2523 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2525 CORBA::String_var name = aMeshSObj->GetName();
2529 groupName += typeNames[ aGroupType ];
2531 // make and fill a group
2532 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2533 aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2534 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2536 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2538 TEEMap::iterator e2neIt = e2neMap.begin();
2539 for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2541 aNewElem = e2neIt->second;
2542 if ( aNewElem->GetType() == grpDS->GetType() )
2544 grpDS->Add( aNewElem );
2546 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2552 aListOfNewGroups.clear();
2553 aListOfNewGroups.push_back(aNewGroup);
2554 aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2558 if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2560 // copy orphan nodes
2561 if ( anSrcImpl->NbNodes() > nodesMap.size() )
2563 SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2564 while ( itNodes->more() )
2566 const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2567 if ( aNode->NbInverseElements() == 0 )
2569 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2570 nodesMap.insert( make_pair( aNode, aNewNode ));
2577 SMESH::SMESH_GroupBase_ptr aGroup;
2578 CORBA::String_var aGroupName;
2579 SMESH::long_array_var anNewIDs = new SMESH::long_array();
2581 // loop on groups of a source mesh
2582 aListOfGroups = anSrcImpl->GetGroups();
2583 for (int iG = 0; iG < aListOfGroups->length(); iG++)
2585 aGroup = aListOfGroups[iG];
2586 aGroupType = aGroup->GetType();
2587 aGroupName = aGroup->GetName();
2588 string aName = aGroupName.in();
2590 // convert a list of IDs
2591 anNewIDs->length( aGroup->Size() );
2592 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2593 SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2595 while ( itGrElems->more() )
2597 anElem = itGrElems->next();
2598 TEEMap::iterator e2neIt = e2neMap.find( anElem );
2599 if ( e2neIt != e2neMap.end() )
2600 anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2602 anNewIDs->length( iElem );
2604 // check a current group name and type don't have identical ones in final mesh
2605 aListOfNewGroups.clear();
2606 TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aName, aGroupType ));
2607 if ( anIter == aGroupsMap.end() ) {
2608 // add a new group in the mesh
2609 aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName.in() );
2610 // add elements into new group
2611 aNewGroup->Add( anNewIDs );
2613 aListOfNewGroups.push_back(aNewGroup);
2614 aGroupsMap.insert(make_pair( make_pair(aName, aGroupType), aListOfNewGroups ));
2617 else if ( theUniteIdenticalGroups ) {
2618 // unite identical groups
2619 TListOfNewGroups& aNewGroups = anIter->second;
2620 aNewGroups.front()->Add( anNewIDs );
2624 // rename identical groups
2625 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName.in());
2626 aNewGroup->Add( anNewIDs );
2628 TListOfNewGroups& aNewGroups = anIter->second;
2629 string aNewGroupName;
2630 if (aNewGroups.size() == 1) {
2631 aNewGroupName = aName + "_1";
2632 aNewGroups.front()->SetName(aNewGroupName.c_str());
2634 char aGroupNum[128];
2635 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2636 aNewGroupName = aName + "_" + string(aGroupNum);
2637 aNewGroup->SetName(aNewGroupName.c_str());
2638 aNewGroups.push_back(aNewGroup);
2641 } // if an IDSource is a mesh
2644 if (theMergeNodesAndElements) // merge nodes
2646 TIDSortedNodeSet aMeshNodes; // no input nodes
2647 SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2648 aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2649 /*SeparateCornersAndMedium=*/ false );
2650 aNewEditor.MergeNodes( aGroupsOfNodes );
2652 aNewEditor.MergeEqualElements();
2655 // Update Python script
2656 aPythonDump << aNewMesh << " = " << this << "."
2657 << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2659 for ( int i = 0; i < theMeshesArray.length(); i++) {
2660 if (i > 0) aPythonDump << ", ";
2661 aPythonDump << theMeshesArray[i];
2663 aPythonDump << "], ";
2664 aPythonDump << theUniteIdenticalGroups << ", "
2665 << theMergeNodesAndElements << ", "
2666 << TVar( theMergeTolerance ) << ")";
2668 delete pPythonDump; // enable python dump from GetGroups()
2670 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2671 if ( !aNewMesh->_is_nil() )
2673 SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2676 // IPAL21468 Change icon of compound because it need not be computed.
2677 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2678 SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2681 aNewMeshDS->Modified();
2683 return aNewMesh._retn();
2686 //================================================================================
2688 * \brief Create a mesh by copying a part of another mesh
2689 * \param meshPart - a part of mesh to copy
2690 * \param toCopyGroups - to create in the new mesh groups
2691 * the copied elements belongs to
2692 * \param toKeepIDs - to preserve IDs of the copied elements or not
2693 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2695 //================================================================================
2697 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2698 const char* meshName,
2699 CORBA::Boolean toCopyGroups,
2700 CORBA::Boolean toKeepIDs)
2702 Unexpect aCatch(SALOME_SalomeException);
2704 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2706 // 1. Get source mesh
2708 if ( CORBA::is_nil( meshPart ))
2709 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2711 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2712 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2714 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2716 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2718 // 2. Make a new mesh
2720 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2721 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2723 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2724 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2725 if ( !meshSO->_is_nil() )
2727 SetName( meshSO, meshName, "Mesh" );
2728 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2730 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2731 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2732 ::SMESH_MeshEditor::ElemFeatures elemType;
2734 // 3. Get elements to copy
2736 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2737 TIDSortedElemSet srcElems;
2738 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2739 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2742 srcElemIt = srcMeshDS->elementsIterator();
2743 srcNodeIt = srcMeshDS->nodesIterator();
2747 SMESH::long_array_var ids = meshPart->GetIDs();
2748 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2750 for (int i=0; i < ids->length(); i++)
2751 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2752 srcElems.insert( elem );
2756 for (int i=0; i < ids->length(); i++)
2757 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2758 srcElems.insert( elem );
2760 if ( srcElems.empty() )
2761 return newMesh._retn();
2763 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2764 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2769 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2770 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2771 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2773 const SMDS_MeshNode *nSrc, *nTgt;
2774 vector< const SMDS_MeshNode* > nodes;
2775 while ( srcElemIt->more() )
2777 const SMDS_MeshElement * elem = srcElemIt->next();
2779 nodes.resize( elem->NbNodes());
2780 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2782 for ( iN = 0; nIt->more(); ++iN )
2784 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2785 nTgt = newMeshDS->FindNode( nSrc->GetID());
2787 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2792 for ( iN = 0; nIt->more(); ++iN )
2794 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2795 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2797 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2798 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2802 if ( elem->GetType() != SMDSAbs_Node )
2804 elemType.Init( elem, /*basicOnly=*/false );
2805 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2807 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2808 if ( toCopyGroups && !toKeepIDs )
2809 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2811 } // while ( srcElemIt->more() )
2813 // 4(b). Copy free nodes
2815 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2817 while ( srcNodeIt->more() )
2819 nSrc = srcNodeIt->next();
2820 if ( nSrc->NbInverseElements() == 0 )
2823 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2825 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2832 int nbNewGroups = 0;
2835 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2836 while ( gIt->more() )
2838 SMESH_Group* group = gIt->next();
2839 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2841 // Check group type. We copy nodal groups containing nodes of copied element
2842 SMDSAbs_ElementType groupType = groupDS->GetType();
2843 if ( groupType != SMDSAbs_Node &&
2844 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2845 continue; // group type differs from types of meshPart
2847 // Find copied elements in the group
2848 vector< const SMDS_MeshElement* > groupElems;
2849 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2852 const SMDS_MeshElement* foundElem;
2853 if ( groupType == SMDSAbs_Node )
2855 while ( eIt->more() )
2856 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2857 groupElems.push_back( foundElem );
2861 while ( eIt->more() )
2862 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2863 groupElems.push_back( foundElem );
2868 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2869 if ( e2eMap.empty() ) continue;
2870 int minID = e2eMap.begin()->first->GetID();
2871 int maxID = e2eMap.rbegin()->first->GetID();
2872 TE2EMap::iterator e2e;
2873 while ( eIt->more() && groupElems.size() < e2eMap.size())
2875 const SMDS_MeshElement* e = eIt->next();
2876 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2877 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2878 groupElems.push_back( e2e->second );
2882 if ( !groupElems.empty() )
2884 SMESH::SMESH_Group_var newGroupObj =
2885 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2886 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2888 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2889 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2890 for ( unsigned i = 0; i < groupElems.size(); ++i )
2891 smdsGroup.Add( groupElems[i] );
2899 newMeshDS->Modified();
2901 *pyDump << newMesh << " = " << this
2902 << ".CopyMesh( " << meshPart << ", "
2903 << "'" << meshName << "', "
2904 << toCopyGroups << ", "
2905 << toKeepIDs << ")";
2907 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2909 if ( nbNewGroups > 0 ) // dump created groups
2910 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2912 return newMesh._retn();
2915 //================================================================================
2917 * SMESH_Gen_i::GetMEDVersion
2919 * Get MED version of the file by its name
2921 //================================================================================
2922 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2923 SMESH::MED_VERSION& theVersion)
2925 theVersion = SMESH::MED_V2_1;
2926 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2927 switch( aVersion ) {
2928 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2929 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2930 case MED::eVUnknown : return false;
2935 //================================================================================
2937 * SMESH_Gen_i::GetMeshNames
2939 * Get names of meshes defined in file with the specified name
2941 //================================================================================
2942 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2944 SMESH::string_array_var aResult = new SMESH::string_array();
2945 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2947 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2949 aResult->length( aNbMeshes );
2950 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2951 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2952 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2955 return aResult._retn();
2958 //=============================================================================
2962 * Save SMESH module's data
2964 //=============================================================================
2965 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2969 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2970 // san -- in case <myCurrentStudy> differs from theComponent's study,
2971 // use that of the component
2972 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
2973 SetCurrentStudy( theComponent->GetStudy() );
2975 // Store study contents as a set of python commands
2976 SavePython(myCurrentStudy);
2978 StudyContext* myStudyContext = GetCurrentStudyContext();
2980 // Declare a byte stream
2981 SALOMEDS::TMPFile_var aStreamFile;
2983 // Obtain a temporary dir
2984 TCollection_AsciiString tmpDir =
2985 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2987 // Create a sequence of files processed
2988 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2989 aFileSeq->length( NUM_TMP_FILES );
2991 TCollection_AsciiString aStudyName( "" );
2993 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2995 // Set names of temporary files
2996 TCollection_AsciiString filename =
2997 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
2998 TCollection_AsciiString meshfile =
2999 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3000 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
3001 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
3002 filename = tmpDir + filename;
3003 meshfile = tmpDir + meshfile;
3006 HDFdataset* aDataset;
3007 HDFgroup* aTopGroup;
3009 HDFgroup* aSubGroup;
3010 HDFgroup* aSubSubGroup;
3011 hdf_size aSize[ 1 ];
3014 //Remove the files if they exist: BugID: 11225
3015 #ifndef WIN32 /* unix functionality */
3016 TCollection_AsciiString cmd("rm -f \"");
3018 TCollection_AsciiString cmd("del /F \"");
3025 system(cmd.ToCString());
3027 // MED writer to be used by storage process
3028 DriverMED_W_SMESHDS_Mesh myWriter;
3029 myWriter.SetFile( meshfile.ToCString() );
3032 // SetStoreName() to groups before storing hypotheses to let them refer to
3033 // groups using "store name", which is "Group <group_persistent_id>"
3035 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3036 for ( ; itBig->More(); itBig->Next() ) {
3037 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3038 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3039 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3040 if ( !CORBA::is_nil( anObject ) ) {
3041 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3042 if ( !myMesh->_is_nil() ) {
3043 myMesh->Load(); // load from study file if not yet done
3044 TPythonDump pd; // not to dump GetGroups()
3045 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3046 pd << ""; // to avoid optimizing pd out
3047 for ( int i = 0; i < groups->length(); ++i )
3049 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3052 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3053 int anId = myStudyContext->findId( string( objStr.in() ) );
3055 sprintf( grpName, "Group %d", anId );
3056 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3057 aGrpBaseDS->SetStoreName( grpName );
3067 // ---> create HDF file
3068 aFile = new HDFfile( (char*) filename.ToCString() );
3069 aFile->CreateOnDisk();
3071 // --> iterator for top-level objects
3072 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3073 for ( ; itBig->More(); itBig->Next() ) {
3074 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3076 // --> hypotheses root branch (only one for the study)
3077 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3078 // create hypotheses root HDF group
3079 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3080 aTopGroup->CreateOnDisk();
3082 // iterator for all hypotheses
3083 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3084 for ( ; it->More(); it->Next() ) {
3085 SALOMEDS::SObject_wrap mySObject = it->Value();
3086 CORBA::Object_var anObject = SObjectToObject( mySObject );
3087 if ( !CORBA::is_nil( anObject ) ) {
3088 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3089 if ( !myHyp->_is_nil() ) {
3090 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3092 string hypname = string( myHyp->GetName() );
3093 string libname = string( myHyp->GetLibName() );
3095 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3096 // WIN32 and ".so" for X-system) must be deleted
3097 int libname_len = libname.length();
3099 if( libname_len > 4 )
3100 libname.resize( libname_len - 4 );
3102 // PAL17753 (Regresion: missing hypothesis in restored study)
3103 // "lib" also should be removed from the beginning
3104 //if( libname_len > 3 )
3105 //libname.resize( libname_len - 3 );
3106 if( libname_len > 6 )
3107 libname = libname.substr( 3, libname_len - 3 - 3 );
3109 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3110 int id = myStudyContext->findId( string( objStr.in() ) );
3111 string hypdata = string( myImpl->SaveTo() );
3113 // for each hypothesis create HDF group basing on its id
3114 char hypGrpName[30];
3115 sprintf( hypGrpName, "Hypothesis %d", id );
3116 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3117 aGroup->CreateOnDisk();
3118 // --> type name of hypothesis
3119 aSize[ 0 ] = hypname.length() + 1;
3120 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3121 aDataset->CreateOnDisk();
3122 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3123 aDataset->CloseOnDisk();
3124 // --> server plugin library name of hypothesis
3125 aSize[ 0 ] = libname.length() + 1;
3126 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );