1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
161 CORBA::ORB_var SMESH_Gen_i::myOrb;
162 PortableServer::POA_var SMESH_Gen_i::myPoa;
163 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
164 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
165 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
168 const int nbElemPerDiagonal = 10;
170 //=============================================================================
172 * GetServant [ static ]
174 * Get servant of the CORBA object
176 //=============================================================================
178 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
180 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
183 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
186 catch (PortableServer::POA::ObjectNotActive &ex)
188 INFOS("GetServant: ObjectNotActive");
191 catch (PortableServer::POA::WrongAdapter &ex)
193 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
196 catch (PortableServer::POA::WrongPolicy &ex)
198 INFOS("GetServant: WrongPolicy");
203 INFOS( "GetServant - Unknown exception was caught!!!" );
208 //=============================================================================
210 * SObjectToObject [ static ]
212 * Get CORBA object corresponding to the SALOMEDS::SObject
214 //=============================================================================
216 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
218 SALOMEDS::GenericAttribute_wrap anAttr;
219 CORBA::Object_var anObj;
220 if ( !theSObject->_is_nil() ) {
222 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
223 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
224 CORBA::String_var aValue = anIOR->Value();
225 if( strcmp( aValue, "" ) != 0 )
226 anObj = GetORB()->string_to_object( aValue );
230 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
236 //=============================================================================
240 * Get SALOME_NamingService object
242 //=============================================================================
244 SALOME_NamingService* SMESH_Gen_i::GetNS()
246 if ( myNS == NULL ) {
247 myNS = SINGLETON_<SALOME_NamingService>::Instance();
248 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
249 myNS->init_orb( GetORB() );
254 //=============================================================================
258 * Get SALOME_LifeCycleCORBA object
260 //=============================================================================
261 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
262 if ( myLCC == NULL ) {
263 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
269 //=============================================================================
271 * GetGeomEngine [ static ]
273 * Get GEOM::GEOM_Gen reference
275 //=============================================================================
276 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
277 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
278 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
279 //CCRT return aGeomEngine._retn();
280 if(CORBA::is_nil(myGeomGen))
282 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
283 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
288 //=============================================================================
290 * SMESH_Gen_i::SMESH_Gen_i
292 * Default constructor: not for use
294 //=============================================================================
296 SMESH_Gen_i::SMESH_Gen_i()
300 //=============================================================================
302 * SMESH_Gen_i::SMESH_Gen_i
304 * Standard constructor, used with Container
306 //=============================================================================
308 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
309 PortableServer::POA_ptr poa,
310 PortableServer::ObjectId* contId,
311 const char* instanceName,
312 const char* interfaceName )
313 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
316 myOrb = CORBA::ORB::_duplicate(orb);
317 myPoa = PortableServer::POA::_duplicate(poa);
320 _id = myPoa->activate_object( _thisObj );
322 myStudyContext = new StudyContext;
324 myIsEmbeddedMode = false;
325 myIsEnablePublish = true;
326 myShapeReader = NULL; // shape reader
328 myIsHistoricalPythonDump = true;
329 myToForgetMeshDataOnHypModif = false;
331 // set it in standalone mode only
332 //OSD::SetSignal( true );
334 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
335 // find out mode (embedded or standalone) here else
336 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
337 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
338 if ( SALOME_NamingService* ns = GetNS() )
340 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
341 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
342 if ( !session->_is_nil() )
344 CORBA::String_var str_host = session->getHostname();
345 CORBA::Long s_pid = session->getPID();
346 string my_host = Kernel_Utils::GetHostname();
348 long my_pid = (long)_getpid();
350 long my_pid = (long) getpid();
352 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
357 //=============================================================================
359 * SMESH_Gen_i::~SMESH_Gen_i
363 //=============================================================================
365 SMESH_Gen_i::~SMESH_Gen_i()
367 // delete hypothesis creators
368 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
369 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
371 // same creator can be mapped under different names
372 GenericHypothesisCreator_i* creator = (*itHyp).second;
376 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
377 if ( creator == (*itHyp2).second )
378 (*itHyp2).second = 0;
380 myHypCreatorMap.clear();
382 // Clear study contexts data
383 delete myStudyContext;
385 // delete shape reader
387 delete myShapeReader;
389 //=============================================================================
391 * SMESH_Gen_i::getHypothesisCreator
393 * Get hypothesis creator
395 //=============================================================================
396 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
397 const char* theLibName,
398 std::string& thePlatformLibName)
399 throw (SALOME::SALOME_Exception)
401 std::string aPlatformLibName;
402 /* It's Need to translate lib name for WIN32 or X platform */
403 if ( theLibName && theLibName[0] != '\0' )
405 int libNameLen = strlen(theLibName);
406 //check for old format "libXXXXXXX.so"
407 if (libNameLen > 7 &&
408 !strncmp( theLibName, "lib", 3 ) &&
409 !strcmp( theLibName+libNameLen-3, ".so" ))
413 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
414 #elif defined(__APPLE__)
415 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
417 aPlatformLibName = theLibName;
422 //try to use new format
424 aPlatformLibName = theLibName;
425 aPlatformLibName += ".dll";
426 #elif defined(__APPLE__)
427 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
429 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
433 thePlatformLibName = aPlatformLibName;
435 Unexpect aCatch(SALOME_SalomeException);
436 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
438 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
439 GenericHypothesisCreator_i* aCreator;
442 // check, if creator for this hypothesis type already exists
443 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
445 // load plugin library
446 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
449 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
451 const char* path = aPlatformLibName.c_str();
454 const char* path = aPlatformLibName.c_str();
456 LibHandle libHandle = LoadLib( path );
457 #if defined(WIN32) && defined(UNICODE)
462 // report any error, if occurred
464 const char* anError = dlerror();
465 throw(SALOME_Exception( anError ));
467 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
468 << aPlatformLibName));
472 // get method, returning hypothesis creator
473 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
474 GetHypothesisCreator procHandle =
475 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
478 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
479 << aPlatformLibName ));
480 UnLoadLib(libHandle);
483 // get hypothesis creator
484 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
485 aCreator = procHandle(theHypName);
488 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
489 << aPlatformLibName));
491 // map hypothesis creator to a hypothesis name
492 myHypCreatorMap[string(theHypName)] = aCreator;
497 return myHypCreatorMap[string(theHypName)];
500 catch (SALOME_Exception& S_ex)
502 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
507 //=============================================================================
509 * SMESH_Gen_i::createHypothesis
511 * Create hypothesis of given type
513 //=============================================================================
514 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
515 const char* theLibName)
517 SMESH_Hypothesis_i* myHypothesis_i = 0;
518 SMESH::SMESH_Hypothesis_var hypothesis_i;
519 std::string aPlatformLibName;
520 GenericHypothesisCreator_i* aCreator =
521 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
523 // create a new hypothesis object, store its ref. in studyContext
524 myHypothesis_i = aCreator->Create(myPoa, &myGen);
527 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
528 CORBA::String_var hypName = myHypothesis_i->GetName();
529 myHypCreatorMap[ hypName.in() ] = aCreator;
531 // activate the CORBA servant of hypothesis
532 hypothesis_i = myHypothesis_i->_this();
533 int nextId = RegisterObject( hypothesis_i );
534 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
535 else { nextId = 0; } // avoid "unused variable" warning in release mode
537 return hypothesis_i._retn();
540 //=============================================================================
542 * SMESH_Gen_i::createMesh
544 * Create empty mesh on shape
546 //=============================================================================
547 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
548 throw ( SALOME::SALOME_Exception )
550 Unexpect aCatch(SALOME_SalomeException);
551 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
553 // Get or create the GEOM_Client instance
555 // create a new mesh object servant, store it in a map in study context
556 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
557 // create a new mesh object
558 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
559 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
561 // activate the CORBA servant of Mesh
562 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
563 int nextId = RegisterObject( mesh );
564 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
565 else { nextId = 0; } // avoid "unused variable" warning in release mode
568 catch (SALOME_Exception& S_ex) {
569 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
571 return SMESH::SMESH_Mesh::_nil();
574 //=============================================================================
576 * SMESH_Gen_i::GetShapeReader
580 //=============================================================================
581 GEOM_Client* SMESH_Gen_i::GetShapeReader()
583 // create shape reader if necessary
584 if ( !myShapeReader )
585 myShapeReader = new GEOM_Client(GetContainerRef());
586 ASSERT( myShapeReader );
587 return myShapeReader;
590 //=============================================================================
592 * SMESH_Gen_i::SetGeomEngine
594 * Set GEOM::GEOM_Gen reference
596 //=============================================================================
597 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
598 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
600 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
601 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
602 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
606 //=============================================================================
608 * SMESH_Gen_i::SetEmbeddedMode
612 //=============================================================================
614 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
616 myIsEmbeddedMode = theMode;
618 if ( !myIsEmbeddedMode ) {
619 //PAL10867: disable signals catching with "noexcepthandler" option
620 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
621 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
626 char* envDisableFPE = getenv("DISABLE_FPE");
627 if (envDisableFPE && atoi(envDisableFPE))
632 OSD::SetSignal( raiseFPE );
634 // else OSD::SetSignal() is called in GUI
638 //=============================================================================
640 * SMESH_Gen_i::IsEmbeddedMode
644 //=============================================================================
646 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
648 return myIsEmbeddedMode;
651 //=============================================================================
653 * SMESH_Gen_i::SetEnablePublish
655 * Set enable publishing in the study
657 //=============================================================================
658 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
660 myIsEnablePublish = theIsEnablePublish;
663 //=============================================================================
665 * SMESH_Gen_i::IsEnablePublish
667 * Check enable publishing
669 //=============================================================================
671 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
673 return myIsEnablePublish;
676 //=============================================================================
678 * SMESH_Gen_i::UpdateStudy
680 * Update study (needed at switching GEOM->SMESH)
682 //=============================================================================
684 void SMESH_Gen_i::UpdateStudy()
686 if ( !myStudyContext )
687 myStudyContext = new StudyContext;
689 SALOMEDS::Study_var aStudy = getStudyServant();
690 if ( !CORBA::is_nil( aStudy ) ) {
691 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
692 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
693 if( !GEOM_var->_is_nil() )
694 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
695 // NPAL16168, issue 0020210
696 // Let meshes update their data depending on GEOM groups that could change
697 CORBA::String_var compDataType = ComponentDataType();
698 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
699 if ( !me->_is_nil() ) {
700 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
701 for ( ; anIter->More(); anIter->Next() ) {
702 SALOMEDS::SObject_wrap so = anIter->Value();
703 CORBA::Object_var ior = SObjectToObject( so );
704 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
705 mesh->CheckGeomModif();
711 //=============================================================================
713 * SMESH_Gen_i::GetStudyContext
717 //=============================================================================
718 StudyContext* SMESH_Gen_i::GetStudyContext()
720 return myStudyContext;
723 //=============================================================================
725 * SMESH_Gen_i::CreateHypothesis
727 * Create hypothesis/algorithm of given type and publish it in the study
729 //=============================================================================
731 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
732 const char* theLibName )
733 throw ( SALOME::SALOME_Exception )
735 Unexpect aCatch(SALOME_SalomeException);
736 // Create hypothesis/algorithm
737 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
739 // Publish hypothesis/algorithm in the study
740 if ( CanPublishInStudy( hyp ) ) {
741 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
742 if ( !aSO->_is_nil() ) {
743 // Update Python script
744 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
745 << theHypName << "', '" << theLibName << "')";
752 //================================================================================
754 * \brief Return a hypothesis initialized by given average length.
755 * \param theHypType - hypothesis type name
756 * \param theLibName - plugin library name
757 * \param theAverageLength - average length
758 * \param theQuadDominated - is quad-dominated flag
759 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
761 //================================================================================
763 SMESH::SMESH_Hypothesis_ptr
764 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
765 const char* theLibName,
766 CORBA::Double theAverageLength,
767 CORBA::Boolean theQuadDominated)
768 throw ( SALOME::SALOME_Exception )
770 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
771 theAverageLength, theQuadDominated };
773 SMESH::SMESH_Hypothesis_var hyp =
774 GetHypothesisParameterValues( theHypType, theLibName,
775 SMESH::SMESH_Mesh::_nil(),
776 GEOM::GEOM_Object::_nil(),
778 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
780 TPythonDump() << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
781 << theHypType << "', '"
782 << theLibName << "', "
783 << theAverageLength << ", "
784 << theQuadDominated << " )";
789 //================================================================================
791 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
792 * existing on the given geometry or to size of the geometry.
793 * \param theHypType - hypothesis type name
794 * \param theLibName - plugin library name
795 * \param theMesh - The mesh of interest
796 * \param theGeom - The shape to get parameter values from
797 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
798 * in a study and used to compute the mesh, or a temporary one created just to pass
801 //================================================================================
803 SMESH::SMESH_Hypothesis_ptr
804 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
805 const char* theLibName,
806 SMESH::SMESH_Mesh_ptr theMesh,
807 GEOM::GEOM_Object_ptr theGeom,
808 const SMESH::HypInitParams& theParams)
809 throw ( SALOME::SALOME_Exception )
811 Unexpect aCatch(SALOME_SalomeException);
813 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
814 if ( byMesh && CORBA::is_nil( theMesh ) )
815 return SMESH::SMESH_Hypothesis::_nil();
816 if ( byMesh && CORBA::is_nil( theGeom ) )
817 return SMESH::SMESH_Hypothesis::_nil();
819 // -----------------------------------------------
820 // find hypothesis used to mesh theGeom
821 // -----------------------------------------------
823 // get mesh and shape
824 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
825 TopoDS_Shape shape = GeomObjectToShape( theGeom );
826 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
827 return SMESH::SMESH_Hypothesis::_nil();
828 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
830 // create a temporary hypothesis to know its dimension
831 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
832 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
834 return SMESH::SMESH_Hypothesis::_nil();
835 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
838 // look for a hypothesis of theHypType used to mesh the shape
839 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
842 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
843 int nbLocalHyps = aHypList->length();
844 for ( int i = 0; i < nbLocalHyps; i++ ) {
845 CORBA::String_var hypName = aHypList[i]->GetName();
846 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
847 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
849 // check super shapes
850 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
851 while ( nbLocalHyps == 0 && itShape.More() ) {
852 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
853 if ( ! CORBA::is_nil( geomObj )) {
854 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
855 nbLocalHyps = aHypList->length();
856 for ( int i = 0; i < nbLocalHyps; i++ )
857 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
858 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
864 // let the temporary hypothesis find out somehow parameter values by mesh
865 if ( hyp->SetParametersByMesh( mesh, shape ))
866 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
870 ::SMESH_Hypothesis::TDefaults dflts;
871 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
872 dflts._nbSegments = myGen.GetDefaultNbSegments();
873 dflts._elemLength = theParams.averageLength;
874 dflts._quadDominated = theParams.quadDominated;
875 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
878 dflts._diagonal = mesh->GetShapeDiagonalSize();
880 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
881 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
882 dflts._shape = &shape;
885 // let the hypothesis initialize it's values
886 if ( hyp->SetParametersByDefaults( dflts, mesh ))
887 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
890 return SMESH::SMESH_Hypothesis::_nil();
893 //=============================================================================
895 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
896 * \param [in] theHyp - the hypothesis of interest
897 * \param [out] theMesh - the sole mesh using \a theHyp
898 * \param [out] theShape - the sole geometry \a theHyp is assigned to
899 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
901 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
902 * considered as SAME sub-mesh => result is \c true.
903 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
904 * a shape to which an hyp being edited is assigned.
906 //=============================================================================
908 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
909 SMESH::SMESH_Mesh_out theMesh,
910 GEOM::GEOM_Object_out theShape)
912 if ( CORBA::is_nil( theHyp ))
915 // get Mesh component SO
916 CORBA::String_var compDataType = ComponentDataType();
917 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
918 if ( CORBA::is_nil( comp ))
921 // look for child SO of meshes
922 SMESH::SMESH_Mesh_var foundMesh;
923 TopoDS_Shape foundShape;
925 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
926 for ( ; meshIter->More() && isSole; meshIter->Next() )
928 SALOMEDS::SObject_wrap curSO = meshIter->Value();
929 CORBA::Object_var obj = SObjectToObject( curSO );
930 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
934 // look for a sole shape where theHyp is assigned
935 bool isHypFound = false;
936 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
937 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
938 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
940 const THypList& hyps = s2hypsIt.Value();
941 THypList::const_iterator h = hyps.begin();
942 for ( ; h != hyps.end(); ++h )
943 if ( (*h)->GetID() == theHyp->GetId() )
945 if ( h != hyps.end()) // theHyp found
948 if ( ! foundShape.IsNull() &&
949 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
951 foundShape.Nullify();
955 foundShape = s2hypsIt.Key();
957 } // loop on assigned hyps
959 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
961 if ( !foundMesh->_is_nil() ) // not a sole mesh
963 if ( !foundMesh->HasShapeToMesh() ||
964 !mesh_i ->HasShapeToMesh() )
966 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
970 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
971 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
972 isSole = s1->IsSame( s2 );
975 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
981 ! foundMesh->_is_nil() &&
982 ! foundShape.IsNull() )
984 theMesh = foundMesh._retn();
985 theShape = ShapeToGeomObject( foundShape );
986 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
991 //=============================================================================
993 * Sets number of segments per diagonal of boundary box of geometry by which
994 * default segment length of appropriate 1D hypotheses is defined
996 //=============================================================================
998 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
999 throw ( SALOME::SALOME_Exception )
1001 if ( theNbSegments > 0 )
1002 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1004 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1006 //=============================================================================
1008 * \brief Sets default number of segments per edge
1010 //=============================================================================
1011 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1012 throw ( SALOME::SALOME_Exception )
1014 if ( theNbSegments > 0 )
1015 myGen.SetDefaultNbSegments( int(theNbSegments) );
1017 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1020 //=============================================================================
1024 //=============================================================================
1026 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1028 if ( name && value && strlen( value ) > 0 )
1031 if ( strcmp(name, "historical_python_dump") == 0 )
1033 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1034 msgToGUI = "preferences/SMESH/historical_python_dump/";
1035 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1037 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1039 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1040 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1041 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1043 else if ( strcmp(name, "default_grp_color") == 0 )
1047 // color must be presented as a string of following form:
1048 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1049 str = str.substr(1);
1050 for ( size_t i = 0; i < str.length()/2; i++ )
1051 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1052 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1054 else if ( value ) { // rgb color ("255,170,0", for example)
1055 string tempValue( value );
1056 char* colorValue = strtok( &tempValue[0], "," );
1057 while ( colorValue != NULL ) {
1058 int c_value = atoi( colorValue );
1059 if ( c_value >= 0 && c_value <= 255 )
1060 color.push_back( c_value );
1061 colorValue = strtok( NULL, "," );
1064 if ( color.size() == 3 ) { // color must have three valid component
1065 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1066 myDefaultGroupColor = value;
1067 msgToGUI = "preferences/SMESH/default_grp_color/";
1072 // update preferences in case if SetOption() is invoked from python console
1073 if ( !msgToGUI.empty() )
1075 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1076 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1077 if ( !CORBA::is_nil( session ) )
1078 session->emitMessageOneWay(msgToGUI.c_str());
1083 //=============================================================================
1085 Return an option value
1087 //=============================================================================
1089 char* SMESH_Gen_i::GetOption(const char* name)
1093 if ( strcmp(name, "historical_python_dump") == 0 )
1095 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1097 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1099 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1101 if ( strcmp(name, "default_grp_color") == 0 )
1103 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1106 return CORBA::string_dup( "" );
1109 //=============================================================================
1111 * SMESH_Gen_i::CreateMesh
1113 * Create empty mesh on a shape and publish it in the study
1115 //=============================================================================
1117 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1118 throw ( SALOME::SALOME_Exception )
1120 Unexpect aCatch(SALOME_SalomeException);
1121 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1123 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1125 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1126 ASSERT( meshServant );
1127 meshServant->SetShape( theShapeObject );
1129 // publish mesh in the study
1130 if ( CanPublishInStudy( mesh ) ) {
1131 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1132 aStudyBuilder->NewCommand(); // There is a transaction
1133 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1134 aStudyBuilder->CommitCommand();
1135 if ( !aSO->_is_nil() ) {
1136 // Update Python script
1137 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1141 return mesh._retn();
1144 //=============================================================================
1146 * SMESH_Gen_i::CreateEmptyMesh
1150 //=============================================================================
1152 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1153 throw ( SALOME::SALOME_Exception )
1155 Unexpect aCatch(SALOME_SalomeException);
1156 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1158 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1160 // publish mesh in the study
1161 if ( CanPublishInStudy( mesh ) ) {
1162 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1163 aStudyBuilder->NewCommand(); // There is a transaction
1164 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1165 aStudyBuilder->CommitCommand();
1166 if ( !aSO->_is_nil() ) {
1167 // Update Python script
1168 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1172 return mesh._retn();
1177 //================================================================================
1179 * \brief Throws an exception in case if the file can't be read
1181 //================================================================================
1183 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1185 SMESH_File f ( theFileName );
1188 if ( !f.error().empty() )
1189 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1191 THROW_SALOME_CORBA_EXCEPTION
1192 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1193 SALOME::BAD_PARAM );
1198 //=============================================================================
1200 * SMESH_Gen_i::CreateMeshFromUNV
1202 * Create mesh and import data from UNV file
1204 //=============================================================================
1206 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1207 throw ( SALOME::SALOME_Exception )
1209 Unexpect aCatch(SALOME_SalomeException);
1211 checkFileReadable( theFileName );
1213 SMESH::SMESH_Mesh_var aMesh = createMesh();
1215 // publish mesh in the study
1216 if ( CanPublishInStudy( aMesh ) ) {
1217 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1218 aStudyBuilder->NewCommand(); // There is a transaction
1219 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1220 aStudyBuilder->CommitCommand();
1221 if ( !aSO->_is_nil() ) {
1222 // Update Python script
1223 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1227 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1229 aServant->ImportUNVFile( theFileName );
1231 // Dump creation of groups
1232 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1234 aServant->GetImpl().GetMeshDS()->Modified();
1235 return aMesh._retn();
1238 //=============================================================================
1240 * SMESH_Gen_i::CreateMeshFromMED
1242 * Create mesh and import data from MED file
1244 //=============================================================================
1246 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1247 SMESH::DriverMED_ReadStatus& theStatus,
1248 const char* theCommandNameForPython,
1249 const char* theFileNameForPython)
1252 char bname[ _MAX_FNAME ];
1253 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1254 string aFileName = bname;
1256 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1258 // Retrieve mesh names from the file
1259 DriverMED_R_SMESHDS_Mesh myReader;
1260 myReader.SetFile( theFileName );
1261 myReader.SetMeshId( -1 );
1262 Driver_Mesh::Status aStatus;
1263 list<string> aNames = myReader.GetMeshNames(aStatus);
1264 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1265 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1267 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1270 TPythonDump aPythonDump;
1271 aPythonDump << "([";
1273 if (theStatus == SMESH::DRS_OK) {
1274 SALOMEDS::StudyBuilder_var aStudyBuilder;
1275 aStudyBuilder = getStudyServant()->NewBuilder();
1276 aStudyBuilder->NewCommand(); // There is a transaction
1278 aResult->length( aNames.size() );
1281 // Iterate through all meshes and create mesh objects
1282 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1285 if (i > 0) aPythonDump << ", ";
1288 SMESH::SMESH_Mesh_var mesh = createMesh();
1290 // publish mesh in the study
1291 SALOMEDS::SObject_wrap aSO;
1292 if ( CanPublishInStudy( mesh ) )
1293 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1294 // - as names of meshes are stored in MED file, we use them for data publishing
1295 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1296 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1299 if ( !aSO->_is_nil() ) {
1302 aPythonDump << "mesh_" << i;
1305 // Read mesh data (groups are published automatically by ImportMEDFile())
1306 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1307 ASSERT( meshServant );
1308 SMESH::DriverMED_ReadStatus status1 =
1309 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1310 if (status1 > theStatus)
1311 theStatus = status1;
1313 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1314 meshServant->GetImpl().GetMeshDS()->Modified();
1316 if ( !aStudyBuilder->_is_nil() )
1317 aStudyBuilder->CommitCommand();
1320 // Update Python script
1321 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1323 // Dump creation of groups
1324 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1325 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1327 return aResult._retn();
1330 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1331 SMESH::DriverMED_ReadStatus& theStatus)
1332 throw ( SALOME::SALOME_Exception )
1334 Unexpect aCatch(SALOME_SalomeException);
1335 checkFileReadable( theFileName );
1337 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1341 //=============================================================================
1343 * SMESH_Gen_i::CreateMeshFromSAUV
1345 * Create mesh and import data from SAUV file
1347 //=============================================================================
1349 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1350 SMESH::DriverMED_ReadStatus& theStatus)
1351 throw ( SALOME::SALOME_Exception )
1353 Unexpect aCatch(SALOME_SalomeException);
1354 checkFileReadable( theFileName );
1356 std::string sauvfilename(theFileName);
1357 std::string medfilename(theFileName);
1358 medfilename += ".med";
1361 cmd = "%PYTHONBIN% ";
1366 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1368 system(cmd.c_str());
1369 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1371 cmd = "%PYTHONBIN% ";
1376 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1378 system(cmd.c_str());
1382 //=============================================================================
1384 * SMESH_Gen_i::CreateMeshFromSTL
1386 * Create mesh and import data from STL file
1388 //=============================================================================
1390 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1391 throw ( SALOME::SALOME_Exception )
1393 Unexpect aCatch(SALOME_SalomeException);
1394 checkFileReadable( theFileName );
1396 SMESH::SMESH_Mesh_var aMesh = createMesh();
1399 char bname[ _MAX_FNAME ];
1400 _splitpath( theFileName, NULL, NULL, bname, NULL );
1401 string aFileName = bname;
1403 string aFileName = basename( const_cast<char *>(theFileName) );
1405 // publish mesh in the study
1406 if ( CanPublishInStudy( aMesh ) ) {
1407 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1408 aStudyBuilder->NewCommand(); // There is a transaction
1409 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1410 aStudyBuilder->CommitCommand();
1411 if ( !aSO->_is_nil() ) {
1412 // Update Python script
1413 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1417 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1419 aServant->ImportSTLFile( theFileName );
1420 aServant->GetImpl().GetMeshDS()->Modified();
1421 return aMesh._retn();
1424 //================================================================================
1426 * \brief Create meshes and import data from the CGSN file
1428 //================================================================================
1430 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1431 SMESH::DriverMED_ReadStatus& theStatus)
1432 throw ( SALOME::SALOME_Exception )
1434 Unexpect aCatch(SALOME_SalomeException);
1435 checkFileReadable( theFileName );
1437 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1440 // Retrieve nb meshes from the file
1441 DriverCGNS_Read myReader;
1442 myReader.SetFile( theFileName );
1443 Driver_Mesh::Status aStatus;
1444 int nbMeshes = myReader.GetNbMeshes(aStatus);
1445 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1447 aResult->length( nbMeshes );
1449 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1452 TPythonDump aPythonDump;
1453 aPythonDump << "([";
1455 if (theStatus == SMESH::DRS_OK)
1457 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1458 aStudyBuilder->NewCommand(); // There is a transaction
1462 // Iterate through all meshes and create mesh objects
1463 for ( ; i < nbMeshes; ++i )
1466 if (i > 0) aPythonDump << ", ";
1469 SMESH::SMESH_Mesh_var mesh = createMesh();
1470 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1472 // Read mesh data (groups are published automatically by ImportMEDFile())
1473 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1474 ASSERT( meshServant );
1476 SMESH::DriverMED_ReadStatus status1 =
1477 meshServant->ImportCGNSFile( theFileName, i, meshName );
1478 if (status1 > theStatus)
1479 theStatus = status1;
1481 meshServant->GetImpl().GetMeshDS()->Modified();
1482 // publish mesh in the study
1483 SALOMEDS::SObject_wrap aSO;
1484 if ( CanPublishInStudy( mesh ) )
1485 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1488 if ( !aSO->_is_nil() ) {
1492 aPythonDump << "mesh_" << i;
1495 aStudyBuilder->CommitCommand();
1498 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1500 // Dump creation of groups
1501 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1502 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1504 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1507 return aResult._retn();
1510 //================================================================================
1512 * \brief Create a mesh and import data from a GMF file
1514 //================================================================================
1516 SMESH::SMESH_Mesh_ptr
1517 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1518 CORBA::Boolean theMakeRequiredGroups,
1519 SMESH::ComputeError_out theError)
1520 throw ( SALOME::SALOME_Exception )
1522 Unexpect aCatch(SALOME_SalomeException);
1523 checkFileReadable( theFileName );
1525 SMESH::SMESH_Mesh_var aMesh = createMesh();
1527 char bname[ _MAX_FNAME ];
1528 _splitpath( theFileName, NULL, NULL, bname, NULL );
1529 string aFileName = bname;
1531 string aFileName = basename( const_cast<char *>(theFileName) );
1533 // publish mesh in the study
1534 if ( CanPublishInStudy( aMesh ) ) {
1535 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1536 aStudyBuilder->NewCommand(); // There is a transaction
1537 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1538 aStudyBuilder->CommitCommand();
1539 if ( !aSO->_is_nil() ) {
1540 // Update Python script
1541 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1542 << theFileName << "', "
1543 << theMakeRequiredGroups << " )";
1546 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1548 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1549 aServant->GetImpl().GetMeshDS()->Modified();
1550 return aMesh._retn();
1554 //=============================================================================
1556 * SMESH_Gen_i::IsReadyToCompute
1558 * Returns true if mesh contains enough data to be computed
1560 //=============================================================================
1562 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1563 GEOM::GEOM_Object_ptr theShapeObject )
1564 throw ( SALOME::SALOME_Exception )
1566 Unexpect aCatch(SALOME_SalomeException);
1567 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1569 if ( CORBA::is_nil( theShapeObject ) )
1570 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1571 SALOME::BAD_PARAM );
1573 if ( CORBA::is_nil( theMesh ) )
1574 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1575 SALOME::BAD_PARAM );
1579 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1580 ASSERT( meshServant );
1581 if ( meshServant ) {
1582 // get local TopoDS_Shape
1583 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1584 // call implementation
1585 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1586 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1589 catch ( SALOME_Exception& S_ex ) {
1590 INFOS( "catch exception "<< S_ex.what() );
1595 //================================================================================
1597 * \brief Find SObject for an algo
1599 //================================================================================
1601 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1604 SALOMEDS::Study_var aStudy = getStudyServant();
1605 if ( !aStudy->_is_nil() ) {
1606 // find algo in the study
1607 CORBA::String_var compDataType = ComponentDataType();
1608 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1609 if ( !father->_is_nil() ) {
1610 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1611 for ( ; itBig->More(); itBig->Next() ) {
1612 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1613 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1614 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1615 for ( ; algoIt->More(); algoIt->Next() ) {
1616 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1617 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1618 if ( !CORBA::is_nil( algoIOR )) {
1619 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1620 if ( impl && impl->GetImpl() == algo )
1621 return algoSO._retn();
1623 } // loop on algo SO's
1626 } // SMESH component iterator
1630 return SALOMEDS::SObject::_nil();
1633 //================================================================================
1635 * \brief Return errors of mesh computation
1637 //================================================================================
1639 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1640 GEOM::GEOM_Object_ptr theSubObject )
1641 throw ( SALOME::SALOME_Exception )
1643 Unexpect aCatch(SALOME_SalomeException);
1644 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1646 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1647 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1649 if ( CORBA::is_nil( theMesh ) )
1650 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1652 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1654 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1657 if(theMesh->HasShapeToMesh())
1658 shape = GeomObjectToShape( theSubObject );
1660 shape = SMESH_Mesh::PseudoShape();
1662 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1664 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1667 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1668 const bool includeSelf = true, complexShapeFirst = true;
1669 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1671 while ( smIt->more() )
1674 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1676 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1677 if ( error && !error->IsOK() )
1679 if ( !( error->myAlgo ) &&
1680 !( error->myAlgo = sm->GetAlgo() ))
1682 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1683 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1684 errStruct.comment = error->myComment.c_str();
1685 errStruct.subShapeID = sm->GetId();
1686 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1687 if ( !algoSO->_is_nil() ) {
1688 CORBA::String_var algoName = algoSO->GetName();
1689 errStruct.algoName = algoName;
1692 errStruct.algoName = error->myAlgo->GetName();
1694 errStruct.hasBadMesh = error->HasBadElems();
1697 error_array->length( nbErr );
1700 catch ( SALOME_Exception& S_ex ) {
1701 INFOS( "catch exception "<< S_ex.what() );
1704 return error_array._retn();
1707 //================================================================================
1709 * \brief Return mesh elements preventing computation of a subshape
1711 //================================================================================
1713 SMESH::MeshPreviewStruct*
1714 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1715 CORBA::Short theSubShapeID )
1716 throw ( SALOME::SALOME_Exception )
1718 Unexpect aCatch(SALOME_SalomeException);
1719 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1721 if ( CORBA::is_nil( theMesh ) )
1722 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1724 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1727 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1729 // mesh implementation
1730 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1731 // submesh by subshape id
1732 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1735 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1736 if ( error && error->HasBadElems() )
1738 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1739 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1741 // get nodes of elements and count elements
1742 TNode2LocalIDMap mapNode2LocalID;
1743 list< TNodeLocalID > connectivity;
1744 int i, nbElements = 0, nbConnNodes = 0;
1746 const list<const SMDS_MeshElement*>& badElems =
1747 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1748 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1749 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1750 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1752 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1753 while ( nIt->more() )
1754 connectivity.push_back
1755 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1757 // fill node coords and assign local ids to the nodes
1758 int nbNodes = mapNode2LocalID.size();
1759 result->nodesXYZ.length( nbNodes );
1760 TNodeLocalID node2ID = mapNode2LocalID.begin();
1761 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1762 node2ID->second = i;
1763 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1764 result->nodesXYZ[i].x = node->X();
1765 result->nodesXYZ[i].y = node->Y();
1766 result->nodesXYZ[i].z = node->Z();
1768 // fill connectivity
1769 result->elementConnectivities.length( nbConnNodes );
1770 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1771 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1772 result->elementConnectivities[i] = (*connIt)->second;
1774 // fill element types
1775 result->elementTypes.length( nbElements );
1776 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1778 const SMDS_MeshElement* elem = *elemIt;
1779 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1780 result->elementTypes[i].isPoly = elem->IsPoly();
1781 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1787 catch ( SALOME_Exception& S_ex ) {
1788 INFOS( "catch exception "<< S_ex.what() );
1791 return result._retn();
1794 //================================================================================
1796 * \brief Create a group of elements preventing computation of a sub-shape
1798 //================================================================================
1800 SMESH::ListOfGroups*
1801 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1802 CORBA::Short theSubShapeID,
1803 const char* theGroupName )
1804 throw ( SALOME::SALOME_Exception )
1806 Unexpect aCatch(SALOME_SalomeException);
1808 SMESH::ListOfGroups_var groups;
1810 if ( CORBA::is_nil( theMesh ) )
1811 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1814 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1816 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1817 TPythonDump() << groups << " = " << this
1818 << ".MakeGroupsOfBadInputElements( "
1819 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1822 catch ( SALOME_Exception& S_ex ) {
1823 INFOS( "catch exception "<< S_ex.what() );
1825 return groups._retn();
1828 //================================================================================
1830 * \brief Returns errors of hypotheses definition
1831 * \param theMesh - the mesh
1832 * \param theSubObject - the main or sub- shape
1833 * \retval SMESH::algo_error_array* - sequence of errors
1835 //================================================================================
1837 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1838 GEOM::GEOM_Object_ptr theSubObject )
1839 throw ( SALOME::SALOME_Exception )
1841 Unexpect aCatch(SALOME_SalomeException);
1842 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1844 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1845 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1847 if ( CORBA::is_nil( theMesh ) )
1848 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1850 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1852 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1853 ASSERT( meshServant );
1854 if ( meshServant ) {
1855 TopoDS_Shape myLocShape;
1856 if(theMesh->HasShapeToMesh())
1857 myLocShape = GeomObjectToShape( theSubObject );
1859 myLocShape = SMESH_Mesh::PseudoShape();
1861 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1862 list< ::SMESH_Gen::TAlgoStateError > error_list;
1863 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1864 // call ::SMESH_Gen::GetAlgoState()
1865 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1866 error_array->length( error_list.size() );
1868 for ( error = error_list.begin(); error != error_list.end(); ++error )
1870 // fill AlgoStateError structure
1871 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1872 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1873 errStruct.algoDim = error->_algoDim;
1874 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1875 errStruct.algoName = "";
1876 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1877 if ( !algoSO->_is_nil() ) {
1878 CORBA::String_var algoName = algoSO->GetName();
1879 errStruct.algoName = algoName.in();
1884 catch ( SALOME_Exception& S_ex ) {
1885 INFOS( "catch exception "<< S_ex.what() );
1887 return error_array._retn();
1890 //=============================================================================
1892 * SMESH_Gen_i::GetSubShapesId
1894 * Get sub-shapes unique ID's list
1896 //=============================================================================
1899 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1900 const SMESH::object_array& theListOfSubShapeObject )
1901 throw ( SALOME::SALOME_Exception )
1903 Unexpect aCatch(SALOME_SalomeException);
1904 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1906 SMESH::long_array_var shapesId = new SMESH::long_array;
1909 if ( CORBA::is_nil( theMainShapeObject ) )
1910 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1914 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1915 TopTools_IndexedMapOfShape myIndexToShape;
1916 TopExp::MapShapes(myMainShape,myIndexToShape);
1918 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1920 GEOM::GEOM_Object_var aShapeObject
1921 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1922 if ( CORBA::is_nil( aShapeObject ) )
1923 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1924 SALOME::BAD_PARAM );
1926 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1927 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1929 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1930 setId.insert(myIndexToShape.FindIndex(F));
1931 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1933 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1935 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1936 setId.insert(myIndexToShape.FindIndex(E));
1937 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1939 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1941 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1942 setId.insert(myIndexToShape.FindIndex(V));
1943 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1946 shapesId->length(setId.size());
1947 set<int>::iterator iind;
1949 for (iind = setId.begin(); iind != setId.end(); iind++)
1951 if(MYDEBUG) SCRUTE((*iind));
1952 shapesId[i] = (*iind);
1953 if(MYDEBUG) SCRUTE(shapesId[i]);
1957 catch (SALOME_Exception& S_ex)
1959 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1962 return shapesId._retn();
1965 //=============================================================================
1967 * SMESH_Gen_i::Compute
1969 * Compute mesh on a shape
1971 //=============================================================================
1973 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1974 GEOM::GEOM_Object_ptr theShapeObject )
1975 throw ( SALOME::SALOME_Exception )
1978 Unexpect aCatch(SALOME_SalomeException);
1979 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1981 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1982 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1983 SALOME::BAD_PARAM );
1985 if ( CORBA::is_nil( theMesh ) )
1986 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1987 SALOME::BAD_PARAM );
1989 // Update Python script
1990 TPythonDump() << "isDone = " << this << ".Compute( "
1991 << theMesh << ", " << theShapeObject << ")";
1995 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1996 ASSERT( meshServant );
1997 if ( meshServant ) {
1998 meshServant->Load();
1999 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2000 meshServant->CheckGeomModif();
2001 // get local TopoDS_Shape
2002 TopoDS_Shape myLocShape;
2003 if(theMesh->HasShapeToMesh())
2004 myLocShape = GeomObjectToShape( theShapeObject );
2006 myLocShape = SMESH_Mesh::PseudoShape();
2007 // call implementation compute
2008 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2009 myGen.PrepareCompute( myLocMesh, myLocShape );
2010 int how = ::SMESH_Gen::COMPACT_MESH;
2011 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2012 how |= ::SMESH_Gen::SHAPE_ONLY;
2013 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2014 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2015 myLocMesh.GetMeshDS()->Modified();
2016 UpdateIcons( theMesh );
2018 HighLightInvalid( theMesh, /*isInvalid=*/false );
2022 catch ( std::bad_alloc ) {
2023 INFOS( "Compute(): lack of memory" );
2025 catch ( SALOME_Exception& S_ex ) {
2026 INFOS( "Compute(): catch exception "<< S_ex.what() );
2029 INFOS( "Compute(): unknown exception " );
2034 //=============================================================================
2036 * SMESH_Gen_i::CancelCompute
2038 * Cancel Compute mesh on a shape
2040 //=============================================================================
2042 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2043 GEOM::GEOM_Object_ptr theShapeObject )
2045 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2047 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2048 TopoDS_Shape myLocShape;
2049 if(theMesh->HasShapeToMesh())
2050 myLocShape = GeomObjectToShape( theShapeObject );
2052 myLocShape = SMESH_Mesh::PseudoShape();
2053 myGen.CancelCompute( myLocMesh, myLocShape);
2057 //=============================================================================
2059 * SMESH_Gen_i::Precompute
2061 * Compute mesh as preview till indicated dimension on shape
2063 //=============================================================================
2065 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2066 GEOM::GEOM_Object_ptr theShapeObject,
2067 SMESH::Dimension theDimension,
2068 SMESH::long_array& theShapesId)
2069 throw ( SALOME::SALOME_Exception )
2071 Unexpect aCatch(SALOME_SalomeException);
2072 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2074 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2075 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2076 SALOME::BAD_PARAM );
2078 if ( CORBA::is_nil( theMesh ) )
2079 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2080 SALOME::BAD_PARAM );
2082 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2085 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2086 meshServant->Load();
2087 ASSERT( meshServant );
2088 if ( meshServant ) {
2089 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2090 meshServant->CheckGeomModif();
2091 // get local TopoDS_Shape
2092 TopoDS_Shape myLocShape;
2093 if(theMesh->HasShapeToMesh())
2094 myLocShape = GeomObjectToShape( theShapeObject );
2096 return result._retn();;
2098 // call implementation compute
2099 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2101 ::MeshDimension aDim = (MeshDimension)theDimension;
2102 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2104 int nbShapeId = shapeIds.size();
2105 theShapesId.length( nbShapeId );
2106 // iterates on shapes and collect mesh entities into mesh preview
2107 TSetOfInt::const_iterator idIt = shapeIds.begin();
2108 TSetOfInt::const_iterator idEnd = shapeIds.end();
2109 std::map< int, int > mapOfShIdNb;
2110 std::set< SMESH_TLink > setOfEdge;
2111 std::list< SMDSAbs_ElementType > listOfElemType;
2112 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2113 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2114 TNode2LocalIDMap mapNode2LocalID;
2115 list< TNodeLocalID > connectivity;
2116 int i, nbConnNodes = 0;
2117 std::set< const SMESH_subMesh* > setOfVSubMesh;
2118 // iterates on shapes
2119 for ( ; idIt != idEnd; idIt++ )
2121 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2123 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2124 if ( !sm || !sm->IsMeshComputed() )
2127 const TopoDS_Shape& aSh = sm->GetSubShape();
2128 const int shDim = myGen.GetShapeDim( aSh );
2129 if ( shDim < 1 || shDim > theDimension )
2132 mapOfShIdNb[ *idIt ] = 0;
2133 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2135 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2136 if ( !smDS ) continue;
2138 if ( theDimension == SMESH::DIM_2D )
2140 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2141 while ( faceIt->more() )
2143 const SMDS_MeshElement* face = faceIt->next();
2144 int aNbNode = face->NbNodes();
2146 aNbNode /= 2; // do not take into account additional middle nodes
2148 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2149 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2151 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2152 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2154 listOfElemType.push_back( SMDSAbs_Edge );
2155 connectivity.push_back
2156 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2157 connectivity.push_back
2158 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2164 else if ( theDimension == SMESH::DIM_1D )
2166 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2167 while ( nodeIt->more() )
2169 listOfElemType.push_back( SMDSAbs_Node );
2170 connectivity.push_back
2171 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2173 // add corner nodes by first vertex from edge
2174 SMESH_subMeshIteratorPtr edgeSmIt =
2175 sm->getDependsOnIterator(/*includeSelf*/false,
2176 /*complexShapeFirst*/false);
2177 while ( edgeSmIt->more() )
2179 SMESH_subMesh* vertexSM = edgeSmIt->next();
2180 // check that vertex is not already treated
2181 if ( !setOfVSubMesh.insert( vertexSM ).second )
2183 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2186 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2187 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2188 while ( nodeIt->more() )
2190 listOfElemType.push_back( SMDSAbs_Node );
2191 connectivity.push_back
2192 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2198 // fill node coords and assign local ids to the nodes
2199 int nbNodes = mapNode2LocalID.size();
2200 result->nodesXYZ.length( nbNodes );
2201 TNodeLocalID node2ID = mapNode2LocalID.begin();
2202 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2203 node2ID->second = i;
2204 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2205 result->nodesXYZ[i].x = node->X();
2206 result->nodesXYZ[i].y = node->Y();
2207 result->nodesXYZ[i].z = node->Z();
2209 // fill connectivity
2210 result->elementConnectivities.length( nbConnNodes );
2211 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2212 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2213 result->elementConnectivities[i] = (*connIt)->second;
2216 // fill element types
2217 result->elementTypes.length( listOfElemType.size() );
2218 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2219 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2220 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2222 SMDSAbs_ElementType elemType = *typeIt;
2223 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2224 result->elementTypes[i].isPoly = false;
2225 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2228 // correct number of shapes
2229 theShapesId.length( mapOfShIdNb.size() );
2233 catch ( std::bad_alloc ) {
2234 INFOS( "Precompute(): lack of memory" );
2236 catch ( SALOME_Exception& S_ex ) {
2237 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2240 INFOS( "Precompute(): unknown exception " );
2242 return result._retn();
2246 //=============================================================================
2248 * SMESH_Gen_i::Evaluate
2250 * Evaluate mesh on a shape
2252 //=============================================================================
2254 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2255 GEOM::GEOM_Object_ptr theShapeObject)
2256 // SMESH::long_array& theNbElems)
2257 throw ( SALOME::SALOME_Exception )
2259 Unexpect aCatch(SALOME_SalomeException);
2260 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2262 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2263 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2264 SALOME::BAD_PARAM );
2266 if ( CORBA::is_nil( theMesh ) )
2267 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2268 SALOME::BAD_PARAM );
2270 SMESH::long_array_var nbels = new SMESH::long_array;
2271 nbels->length(SMESH::Entity_Last);
2272 int i = SMESH::Entity_Node;
2273 for (; i < SMESH::Entity_Last; i++)
2276 // Update Python script
2277 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2278 << theMesh << ", " << theShapeObject << ")";
2282 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2283 ASSERT( meshServant );
2284 if ( meshServant ) {
2285 meshServant->Load();
2286 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2287 meshServant->CheckGeomModif();
2288 // get local TopoDS_Shape
2289 TopoDS_Shape myLocShape;
2290 if(theMesh->HasShapeToMesh())
2291 myLocShape = GeomObjectToShape( theShapeObject );
2293 myLocShape = SMESH_Mesh::PseudoShape();
2294 // call implementation compute
2295 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2296 MapShapeNbElems aResMap;
2297 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2298 MapShapeNbElemsItr anIt = aResMap.begin();
2299 for(; anIt!=aResMap.end(); anIt++) {
2300 const vector<int>& aVec = (*anIt).second;
2301 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2302 int nbElem = aVec[i];
2303 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2305 SMESH_subMesh* sm = anIt->first;
2306 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2307 const SMESH_Algo* algo = sm->GetAlgo();
2308 if ( (algo && !error.get()) || error->IsOK() )
2309 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2313 nbels[i] += aVec[i];
2317 return nbels._retn();
2320 catch ( std::bad_alloc ) {
2321 INFOS( "Evaluate(): lack of memory" );
2323 catch ( SALOME_Exception& S_ex ) {
2324 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2327 INFOS( "Evaluate(): unknown exception " );
2330 return nbels._retn();
2333 //================================================================================
2335 * \brief Return geometrical object the given element is built on
2336 * \param theMesh - the mesh the element is in
2337 * \param theElementID - the element ID
2338 * \param theGeomName - the name of the result geom object if it is not yet published
2339 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2341 //================================================================================
2343 GEOM::GEOM_Object_ptr
2344 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2345 CORBA::Long theElementID,
2346 const char* theGeomName)
2347 throw ( SALOME::SALOME_Exception )
2349 Unexpect aCatch(SALOME_SalomeException);
2351 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2352 if ( !geom->_is_nil() ) {
2353 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2354 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2356 // try to find the corresponding SObject
2357 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2358 if ( SObj->_is_nil() ) // submesh can be not found even if published
2360 // try to find published submesh
2361 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2362 if ( !geom->IsMainShape() && list->length() == 1 ) {
2363 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2364 SALOMEDS::ChildIterator_wrap it;
2365 if ( !mainSO->_is_nil() ) {
2366 it = getStudyServant()->NewChildIterator( mainSO );
2368 if ( !it->_is_nil() ) {
2369 for ( it->InitEx(true); it->More(); it->Next() ) {
2370 SALOMEDS::SObject_wrap so = it->Value();
2371 CORBA::Object_var obj = SObjectToObject( so );
2372 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2373 if ( !subGeom->_is_nil() ) {
2374 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2375 if ( subList->length() == 1 && list[0] == subList[0] ) {
2385 if ( SObj->_is_nil() ) // publish a new subshape
2386 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2388 // return only published geometry
2389 if ( !SObj->_is_nil() ) {
2390 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2391 CORBA::Object_var obj = SObjectToObject( SObj );
2392 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2396 return GEOM::GEOM_Object::_nil();
2399 //================================================================================
2401 * \brief Return geometrical object the given element is built on.
2402 * \param theMesh - the mesh the element is in
2403 * \param theElementID - the element ID
2404 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2406 //================================================================================
2408 GEOM::GEOM_Object_ptr
2409 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2410 CORBA::Long theElementID)
2411 throw ( SALOME::SALOME_Exception )
2413 Unexpect aCatch(SALOME_SalomeException);
2414 if ( CORBA::is_nil( theMesh ) )
2415 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2417 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2418 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2420 // get a core mesh DS
2421 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2422 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2424 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2425 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2426 // find the element in mesh
2427 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2428 // find a shape id by the element
2429 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2430 // get a geom object by the shape id
2431 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2432 if ( geom->_is_nil() ) {
2433 // try to find a published sub-shape
2434 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2435 SALOMEDS::ChildIterator_wrap it;
2436 if ( !mainSO->_is_nil() ) {
2437 it = getStudyServant()->NewChildIterator( mainSO );
2439 if ( !it->_is_nil() ) {
2440 for ( it->InitEx(true); it->More(); it->Next() ) {
2441 SALOMEDS::SObject_wrap so = it->Value();
2442 CORBA::Object_var obj = SObjectToObject( so );
2443 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2444 if ( !subGeom->_is_nil() ) {
2445 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2446 if ( subList->length() == 1 && shapeID == subList[0] ) {
2454 if ( geom->_is_nil() ) {
2456 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2457 if ( !op->_is_nil() )
2458 geom = op->GetSubShape( mainShape, shapeID );
2463 if ( !geom->_is_nil() ) {
2464 GeomObjectToShape( geom ); // let geom client remember the found shape
2465 return geom._retn();
2470 return GEOM::GEOM_Object::_nil();
2473 //================================================================================
2475 * SMESH_Gen_i::Concatenate
2477 * Concatenate the given meshes into one mesh
2479 //================================================================================
2481 SMESH::SMESH_Mesh_ptr
2482 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2483 CORBA::Boolean theUniteIdenticalGroups,
2484 CORBA::Boolean theMergeNodesAndElements,
2485 CORBA::Double theMergeTolerance,
2486 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2487 throw ( SALOME::SALOME_Exception )
2489 return ConcatenateCommon(theMeshesArray,
2490 theUniteIdenticalGroups,
2491 theMergeNodesAndElements,
2497 //================================================================================
2499 * SMESH_Gen_i::ConcatenateWithGroups
2501 * Concatenate the given meshes into one mesh
2502 * Create the groups of all elements from initial meshes
2504 //================================================================================
2506 SMESH::SMESH_Mesh_ptr
2507 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2508 CORBA::Boolean theUniteIdenticalGroups,
2509 CORBA::Boolean theMergeNodesAndElements,
2510 CORBA::Double theMergeTolerance,
2511 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2512 throw ( SALOME::SALOME_Exception )
2514 return ConcatenateCommon(theMeshesArray,
2515 theUniteIdenticalGroups,
2516 theMergeNodesAndElements,
2522 //================================================================================
2524 * SMESH_Gen_i::ConcatenateCommon
2526 * Concatenate the given meshes into one mesh
2528 //================================================================================
2530 SMESH::SMESH_Mesh_ptr
2531 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2532 CORBA::Boolean theUniteIdenticalGroups,
2533 CORBA::Boolean theMergeNodesAndElements,
2534 CORBA::Double theMergeTolerance,
2535 CORBA::Boolean theCommonGroups,
2536 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2537 throw ( SALOME::SALOME_Exception )
2539 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2540 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2542 // create mesh if theMeshToAppendTo not provided
2543 SMESH::SMESH_Mesh_var newMesh;
2544 if ( CORBA::is_nil( theMeshToAppendTo ))
2545 newMesh = CreateEmptyMesh();
2547 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2548 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2549 if ( !newImpl ) return newMesh._retn();
2552 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2553 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2555 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2556 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2557 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2558 TGroupsMap groupsMap;
2559 TListOfNewGroups listOfNewGroups;
2561 if ( !CORBA::is_nil( theMeshToAppendTo ))
2563 // fill groupsMap with existing groups
2564 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2565 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2567 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2568 if ( !group->_is_nil() )
2570 CORBA::String_var name = group->GetName();
2571 SMESH::ElementType type = group->GetType();
2572 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2577 ::SMESH_MeshEditor newEditor( &locMesh );
2578 ::SMESH_MeshEditor::ElemFeatures elemType;
2580 // loop on sub-meshes
2581 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2583 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2584 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2585 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2586 if ( !initImpl ) continue;
2587 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2591 // assure that IDs increments by one during iteration
2592 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2593 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2594 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2595 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2597 initMeshDS->Modified();
2598 initMeshDS->CompactMesh();
2601 // remember nb of elements before filling in
2602 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2606 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2607 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2608 while ( elemIt->more() )
2610 SMESH_NodeXYZ node = elemIt->next();
2611 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2616 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2617 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2618 while ( elemIt->more() )
2620 const SMDS_MeshElement* elem = elemIt->next();
2621 elemType.myNodes.resize( elem->NbNodes() );
2623 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2624 for ( int k = 0; itNodes->more(); k++)
2626 const SMDS_MeshNode* node = itNodes->next();
2627 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2630 // creates a corresponding element on existent nodes in new mesh
2631 newElems[ elem->GetID() ] =
2632 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2634 newEditor.ClearLastCreated(); // forget the history
2637 // create groups of just added elements
2638 SMESH::SMESH_Group_var newGroup;
2639 SMESH::ElementType groupType;
2640 if ( theCommonGroups )
2643 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2644 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2645 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2646 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2649 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2651 for( groupType = SMESH::NODE;
2652 groupType < SMESH::NB_ELEMENT_TYPES;
2653 groupType = (SMESH::ElementType)( groupType + 1 ))
2655 if ( curState[ groupType ] <= prevState[ groupType ])
2656 continue; // no elements of groupType added from the i-th mesh
2658 // make a group name
2659 std::string groupName = "Gr";
2660 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2662 CORBA::String_var name = meshSO->GetName();
2666 groupName += typeNames[ groupType ];
2668 // make and fill a group
2669 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2670 std::vector< const SMDS_MeshElement* > & elemVec =
2671 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2672 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2674 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2676 for ( size_t j = 0; j < elemVec.size(); ++j )
2678 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2679 grpDS->Add( elemVec[j] );
2683 listOfNewGroups.clear();
2684 listOfNewGroups.push_back( newGroup );
2685 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2690 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2694 SMESH::SMESH_GroupBase_ptr group;
2695 CORBA::String_var groupName;
2696 SMESH::long_array_var newIDs = new SMESH::long_array();
2698 // loop on groups of a source mesh
2699 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2700 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2702 group = listOfGroups[iG];
2703 groupType = group->GetType();
2704 groupName = group->GetName();
2705 std::string name = groupName.in();
2707 // convert a list of IDs
2708 newIDs->length( group->Size() );
2709 std::vector< const SMDS_MeshElement* > & elemVec =
2710 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2711 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2713 while ( itGrElems->more() )
2715 const SMDS_MeshElement* elem = itGrElems->next();
2716 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2718 newIDs[ nbElems++ ] = newElem->GetID();
2720 newIDs->length( nbElems );
2722 // check that a current group name and type don't have identical ones in final mesh
2723 listOfNewGroups.clear();
2724 TNameAndType nameAndType( name, groupType );
2725 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2726 if ( anIter == groupsMap.end() )
2728 // add a new group in the mesh
2729 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2730 newGroup->Add( newIDs );
2732 listOfNewGroups.push_back( newGroup );
2733 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2735 else if ( theUniteIdenticalGroups )
2737 // unite identical groups
2738 TListOfNewGroups& aNewGroups = anIter->second;
2739 aNewGroups.front()->Add( newIDs );
2743 // rename identical groups
2744 newGroup = newImpl->CreateGroup( groupType, groupName );
2745 newGroup->Add( newIDs );
2747 TListOfNewGroups& newGroups = anIter->second;
2748 std::string newGroupName;
2749 if ( newGroups.size() == 1 )
2751 newGroupName = name + "_1";
2752 newGroups.front()->SetName( newGroupName.c_str() );
2754 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2755 newGroup->SetName( newGroupName.c_str() );
2756 newGroups.push_back( newGroup );
2759 } // if an IDSource is a mesh
2762 if ( theMergeNodesAndElements ) // merge nodes
2764 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2765 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2766 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2767 /*SeparateCornersAndMedium=*/ false );
2768 newEditor.MergeNodes( groupsOfNodes );
2770 newEditor.MergeEqualElements();
2773 // Update Python script
2774 pythonDump << newMesh << " = " << this
2775 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2776 << theMeshesArray << ", "
2777 << theUniteIdenticalGroups << ", "
2778 << theMergeNodesAndElements << ", "
2779 << TVar( theMergeTolerance ) << ", "
2780 << theMeshToAppendTo << " )";
2782 pPythonDump.reset(); // enable python dump from GetGroups()
2784 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2785 if ( !newMesh->_is_nil() )
2787 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2790 // IPAL21468 Change icon of compound because it need not be computed.
2791 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2792 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2794 newMeshDS->Modified();
2796 return newMesh._retn();
2799 //================================================================================
2801 * \brief Create a mesh by copying a part of another mesh
2802 * \param meshPart - a part of mesh to copy
2803 * \param toCopyGroups - to create in the new mesh groups
2804 * the copied elements belongs to
2805 * \param toKeepIDs - to preserve IDs of the copied elements or not
2806 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2808 //================================================================================
2810 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2811 const char* meshName,
2812 CORBA::Boolean toCopyGroups,
2813 CORBA::Boolean toKeepIDs)
2814 throw ( SALOME::SALOME_Exception )
2816 Unexpect aCatch(SALOME_SalomeException);
2818 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2819 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2821 // 1. Get source mesh
2823 if ( CORBA::is_nil( meshPart ))
2824 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2826 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2827 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2829 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2831 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2833 // 2. Make a new mesh
2835 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2836 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2838 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2839 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2840 if ( !meshSO->_is_nil() )
2842 SetName( meshSO, meshName, "Mesh" );
2843 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2845 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2846 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2847 ::SMESH_MeshEditor::ElemFeatures elemType;
2849 // 3. Get elements to copy
2851 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2852 TIDSortedElemSet srcElems;
2853 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2854 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2857 srcElemIt = srcMeshDS->elementsIterator();
2858 srcNodeIt = srcMeshDS->nodesIterator();
2862 SMESH::long_array_var ids = meshPart->GetIDs();
2863 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2865 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2866 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2867 srcElems.insert( elem );
2871 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2872 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2873 srcElems.insert( elem );
2875 if ( srcElems.empty() )
2876 return newMesh._retn();
2878 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2879 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2884 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2885 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2886 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2888 const SMDS_MeshNode *nSrc, *nTgt;
2889 vector< const SMDS_MeshNode* > nodes;
2890 while ( srcElemIt->more() )
2892 const SMDS_MeshElement * elem = srcElemIt->next();
2894 nodes.resize( elem->NbNodes());
2895 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2897 for ( iN = 0; nIt->more(); ++iN )
2899 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2900 nTgt = newMeshDS->FindNode( nSrc->GetID());
2902 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2907 for ( iN = 0; nIt->more(); ++iN )
2909 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2910 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2912 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2913 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2917 if ( elem->GetType() != SMDSAbs_Node )
2919 elemType.Init( elem, /*basicOnly=*/false );
2920 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2922 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2923 if ( toCopyGroups && !toKeepIDs )
2924 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2926 } // while ( srcElemIt->more() )
2928 // 4(b). Copy free nodes
2930 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2932 while ( srcNodeIt->more() )
2934 nSrc = srcNodeIt->next();
2935 if ( nSrc->NbInverseElements() == 0 )
2938 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2940 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2947 int nbNewGroups = 0;
2950 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2951 while ( gIt->more() )
2953 SMESH_Group* group = gIt->next();
2954 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2956 // Check group type. We copy nodal groups containing nodes of copied element
2957 SMDSAbs_ElementType groupType = groupDS->GetType();
2958 if ( groupType != SMDSAbs_Node &&
2959 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2960 continue; // group type differs from types of meshPart
2962 // Find copied elements in the group
2963 vector< const SMDS_MeshElement* > groupElems;
2964 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2967 const SMDS_MeshElement* foundElem;
2968 if ( groupType == SMDSAbs_Node )
2970 while ( eIt->more() )
2971 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2972 groupElems.push_back( foundElem );
2976 while ( eIt->more() )
2977 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2978 groupElems.push_back( foundElem );
2983 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2984 if ( e2eMap.empty() ) continue;
2985 int minID = e2eMap.begin()->first->GetID();
2986 int maxID = e2eMap.rbegin()->first->GetID();
2987 TE2EMap::iterator e2e;
2988 while ( eIt->more() && groupElems.size() < e2eMap.size())
2990 const SMDS_MeshElement* e = eIt->next();
2991 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2992 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2993 groupElems.push_back( e2e->second );
2997 if ( !groupElems.empty() )
2999 SMESH::SMESH_Group_var newGroupObj =
3000 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3001 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3003 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3004 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3005 for ( unsigned i = 0; i < groupElems.size(); ++i )
3006 smdsGroup.Add( groupElems[i] );
3014 newMeshDS->Modified();
3016 *pyDump << newMesh << " = " << this
3017 << ".CopyMesh( " << meshPart << ", "
3018 << "'" << meshName << "', "
3019 << toCopyGroups << ", "
3020 << toKeepIDs << ")";
3022 pyDumpDeleter.reset(); // allow dump in GetGroups()
3024 if ( nbNewGroups > 0 ) // dump created groups
3025 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3027 return newMesh._retn();
3031 namespace // utils for CopyMeshWithGeom()
3033 typedef std::map< std::string, std::string > TStr2StrMap;
3034 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3035 //typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3037 //================================================================================
3039 * \brief Return a new sub-shape corresponding to an old one
3041 //================================================================================
3045 SMESH_Mesh_i* mySrcMesh_i;
3046 SMESH_Mesh_i* myNewMesh_i;
3047 SMESH_Gen_i* myGen_i;
3051 TStr2StrMap myOld2NewEntryMap; // map of study entries
3053 //GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3054 //TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3057 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3059 // not directly relating to shape search
3060 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3062 //================================================================================
3064 * \brief Constructor
3066 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3067 SMESH_Mesh_i* newMesh_i,
3068 SMESH_Gen_i* smeshGen_i )
3069 : mySrcMesh_i( srcMesh_i ),
3070 myNewMesh_i( newMesh_i ),
3071 myGen_i ( smeshGen_i ),
3072 myToPublish( smeshGen_i->IsEnablePublish() ),
3073 myGIPMapDone( false )
3075 // retrieve from the study shape mapping made thanks to
3076 // "Set presentation parameters and sub-shapes from arguments" option
3078 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3079 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3080 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3081 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3082 if ( newSO->_is_nil() )
3084 myToPublish = false;
3087 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3089 CORBA::String_var oldEntry = oldSO->GetID();
3090 CORBA::String_var newEntry = newSO->GetID();
3091 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3092 std::string( newEntry.in() )));
3094 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3095 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3096 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3097 GEOM::ListOfGO_var subShapes = op->GetExistingSubObjects( mainShapeNew,
3098 /*groupsOnly=*/false );
3099 for ( CORBA::ULong i = 0; i < subShapes->length(); ++i )
3101 newSO = myGen_i->ObjectToSObject( subShapes[ i ]);
3102 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3103 for ( ; anIter->More(); anIter->Next() )
3105 SALOMEDS::SObject_wrap so = anIter->Value();
3106 if ( so->ReferencedObject( oldSO.inout() ))
3108 oldEntry = oldSO->GetID();
3109 newEntry = newSO->GetID();
3110 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3111 std::string( newEntry.in() )));
3117 //================================================================================
3119 * \brief Find a new sub-shape corresponding to an old one
3121 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3124 return GEOM::GEOM_Object::_duplicate( oldShape );
3126 GEOM::GEOM_Object_var newShape;
3128 if ( CORBA::is_nil( oldShape ))
3129 return newShape._retn();
3131 if ( !isChildOfOld( oldShape ))
3132 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3134 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3135 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3137 // try to find by entry
3140 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3141 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3142 if ( o2nID != myOld2NewEntryMap.end() )
3144 newShape = getShapeByEntry( o2nID->second );
3148 if ( newShape->_is_nil() )
3150 // try to construct a new sub-shape using myGIPMap
3152 std::vector< int > newIndices;
3153 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3154 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3156 findNewIDs( oldIndices[i], newIndices );
3158 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3161 newShape = getInPlace( oldShape );
3163 if ( !newIndices.empty() )
3167 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3169 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3171 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3172 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3174 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3175 newIndicesList->length( newIndices.size() );
3176 for ( size_t i = 0; i < newIndices.size(); ++i )
3177 newIndicesList[ i ] = newIndices[ i ];
3178 grOp->UnionIDs( newShape, newIndicesList );
3182 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3183 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3192 if ( !newShape->_is_nil() && myToPublish )
3194 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3195 if ( !newEntry.in() || !newEntry.in()[0] )
3197 CORBA::String_var name = oldShape->GetName();
3198 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3199 newEntry = newShape->GetStudyEntry();
3200 oldEntry = oldShape->GetStudyEntry();
3201 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3202 std::string( newEntry.in() )));
3206 return newShape._retn();
3209 //================================================================================
3211 * \brief Return a study entry of a new shape by study entry of the old one
3213 std::string FindNew( const std::string & oldEntry )
3218 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3219 if ( o2nID != myOld2NewEntryMap.end() )
3220 return o2nID->second;
3222 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3223 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3226 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3227 if ( newShape->_is_nil() )
3228 return std::string();
3230 CORBA::String_var newEntry = newShape->GetStudyEntry();
3231 return newEntry.in();
3234 //================================================================================
3236 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3237 * Return zero if not found or there are more than one new ID
3239 int FindNew( int oldID )
3248 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3250 if ( myGIPMap[ oldID ].length() == 1 )
3252 newID = myGIPMap[ oldID ][ 0 ];
3254 else if ( myGIPMap[ oldID ].length() > 1 &&
3255 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3257 // select a meshed VERTEX
3258 SMESH_subMesh* newSM;
3259 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3260 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3261 ( !newSM->IsEmpty() ))
3262 newID = myGIPMap[ oldID ][ i ];
3268 //================================================================================
3270 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3271 * Return zero if the old shape is not kept as is in the new shape.
3273 int FindNewNotChanged( SMESH_subMesh* oldSM )
3276 return oldSM->GetId();
3278 int newID = FindNew( oldSM->GetId() );
3282 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3286 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3287 // one new sub-shape of the same type.
3289 if ( oldSM->DependsOn().size() !=
3290 newSM->DependsOn().size() )
3293 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3294 while ( srcSMIt->more() )
3296 oldSM = srcSMIt->next();
3297 int newSubID = FindNew( oldSM->GetId() );
3298 if ( getShapeType( myNewMesh_i, newSubID ) !=
3299 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3305 //================================================================================
3307 * \brief Return shape by study entry
3309 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3311 GEOM::GEOM_Object_var shape;
3312 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3313 if ( !so->_is_nil() )
3315 CORBA::Object_var obj = so->GetObject();
3316 shape = GEOM::GEOM_Object::_narrow( obj );
3318 return shape._retn();
3321 //================================================================================
3323 * \brief Fill myGIPMap by calling GetInPlaceMap()
3327 if ( !myGIPMapDone )
3329 myGIPMapDone = true;
3331 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3332 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3333 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3334 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3337 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3341 myGIPMap = new GEOM::ListOfListOfLong();
3346 //================================================================================
3348 * \brief Get new sub-shape by calling GetInPlace()
3350 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3352 GEOM::GEOM_Object_var newShape;
3354 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3355 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3356 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3359 newShape = op->GetInPlace( mainShapeNew, oldShape );
3364 return newShape._retn();
3367 //================================================================================
3369 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3370 * number of found IDs
3372 int findNewIDs( int oldID, std::vector< int >& newIDs )
3374 size_t prevNbIDs = newIDs.size();
3376 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3378 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3379 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3381 return newIDs.size() - prevNbIDs;
3384 //================================================================================
3386 * \brief Check if an object relates to the old shape
3388 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3390 if ( CORBA::is_nil( oldShape ))
3392 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3393 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3394 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3395 mainShapeOld1->_is_equivalent( oldShape ));
3398 //================================================================================
3400 * \brief Return shape type by shape ID
3402 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3404 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3405 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3406 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3409 //================================================================================
3411 * \brief Store a source sub-shape for which a counterpart not found and
3412 * a smesh object invalid due to that
3414 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3415 SALOMEDS::SObject_wrap smeshSO )
3417 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3418 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3420 CORBA::String_var smeshEntry = smeshSO->GetID();
3421 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3425 //================================================================================
3427 * \brief Store a source sub-shape for which a counterpart not found and
3428 * a smesh object invalid due to that
3430 void AddInvalid( std::string geomEntry,
3431 SALOMEDS::SObject_wrap smeshSO )
3433 if ( !geomEntry.empty() )
3435 CORBA::String_var smeshEntry = smeshSO->GetID();
3436 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3440 //================================================================================
3442 * \brief Store a source sub-shape for which a counterpart not found and
3443 * a smesh object invalid due to that
3445 void AddInvalid( int oldGeomID,
3446 SALOMEDS::SObject_wrap smeshSO )
3448 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3449 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3452 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3453 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3455 SMESH_Comment geomName( typeName[ shapeType ]);
3456 geomName << " #" << oldGeomID;
3458 CORBA::String_var smeshEntry = smeshSO->GetID();
3459 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3462 //================================================================================
3464 * \brief Return entries of a source sub-shape for which a counterpart not found and
3465 * of smesh objects invalid due to that
3467 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3468 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3471 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3472 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3474 nbSO += 1 + entry2entrySet->second.size();
3476 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3477 theInvalidEntries->length ( nbSO );
3478 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3480 entry2entrySet = myInvalidMap.begin();
3481 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3483 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3485 std::set< std::string > & entrySet = entry2entrySet->second;
3486 std::set< std::string >::iterator entry = entrySet.begin();
3487 for ( ; entry != entrySet.end(); ++entry )
3489 theInvalidEntries[ iEntry++ ] = entry->c_str();
3491 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3492 if ( !so->_is_nil() )
3493 theInvalidMeshSObjects[ iSO++ ] = so;
3498 }; // struct ShapeMapper
3500 //================================================================================
3502 * \brief Append an item to a CORBA sequence
3504 template < class CORBA_seq, class ITEM >
3505 void append( CORBA_seq& seq, ITEM item )
3507 if ( !CORBA::is_nil( item ))
3509 seq->length( 1 + seq->length() );
3510 seq[ seq->length() - 1 ] = item;
3513 } // namespace // utils for CopyMeshWithGeom()
3515 //================================================================================
3517 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3518 * \param [in] sourceMesh - a mesh to copy
3519 * \param [in] newGeometry - a new geometry
3520 * \param [in] toCopyGroups - to create groups in the new mesh
3521 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3522 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3523 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3524 * \param [out] newMesh - return a new mesh
3525 * \param [out] newGroups - return new groups
3526 * \param [out] newSubmeshes - return new sub-meshes
3527 * \param [out] newHypotheses - return new algorithms and hypotheses
3528 * \param [out] invalidEntries - return study entries of objects whose
3529 * counterparts are not found in the newGeometry, followed by entries
3530 * of mesh sub-objects that are invalid because they depend on a not found
3531 * preceding sub-shape
3532 * \return CORBA::Boolean - is a success
3534 //================================================================================
3536 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3537 GEOM::GEOM_Object_ptr theNewGeometry,
3538 const char* theMeshName,
3539 CORBA::Boolean theToCopyGroups,
3540 CORBA::Boolean theToReuseHypotheses,
3541 CORBA::Boolean theToCopyElements,
3542 SMESH::SMESH_Mesh_out theNewMesh,
3543 SMESH::ListOfGroups_out theNewGroups,
3544 SMESH::submesh_array_out theNewSubmeshes,
3545 SMESH::ListOfHypothesis_out theNewHypotheses,
3546 SMESH::string_array_out theInvalidEntries)
3547 throw ( SALOME::SALOME_Exception )
3549 if ( CORBA::is_nil( theSourceMesh ) ||
3550 CORBA::is_nil( theNewGeometry ))
3551 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3553 if ( !theSourceMesh->HasShapeToMesh() )
3554 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3559 TPythonDump pyDump; // prevent dump from CreateMesh()
3561 theNewMesh = CreateMesh( theNewGeometry );
3562 theNewGroups = new SMESH::ListOfGroups();
3563 theNewSubmeshes = new SMESH::submesh_array();
3564 theNewHypotheses = new SMESH::ListOfHypothesis();
3565 theInvalidEntries = new SMESH::string_array();
3567 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3569 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3570 GEOM::GEOM_Object_var geom, newGeom;
3571 SALOMEDS::SObject_wrap so;
3573 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3574 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3577 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3579 // treat hypotheses of mesh and sub-meshes
3580 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3581 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3583 bool isSubMesh = ( iSM < smList->length() );
3586 // create a new sub-mesh
3587 SMESH::SMESH_subMesh_var newSM;
3588 geom = smList[iSM]->GetSubShape();
3589 so = ObjectToSObject( smList[iSM] );
3590 CORBA::String_var name;
3591 if ( !so->_is_nil() )
3592 name = so->GetName();
3593 newGeom = shapeMapper.FindNew( geom );
3594 if ( newGeom->_is_nil() )
3596 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3597 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3602 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3604 append( theNewSubmeshes, newSM );
3606 if ( newGeom->_is_nil() )
3607 continue; // don't assign hypotheses
3611 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3613 so = ObjectToSObject( theNewMesh );
3614 SetName( so, theMeshName, "Mesh" );
3617 // assign hypotheses
3618 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3619 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3621 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3622 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3624 // get geometry hyp depends on
3625 std::vector< std::string > entryArray;
3626 std::vector< int > subIDArray;
3627 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3629 if ( !theToReuseHypotheses || dependsOnGeom )
3631 // create a new hypothesis
3632 CORBA::String_var type = hyp->GetName();
3633 CORBA::String_var lib = hyp->GetLibName();
3634 CORBA::String_var data = hyp_i->SaveTo();
3637 hyp = CreateHypothesis( type, lib );
3638 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3639 hyp_i->LoadFrom( data.in() );
3640 append( theNewHypotheses, hyp );
3644 // update geometry hyp depends on
3645 if ( dependsOnGeom )
3647 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3649 if ( !entryArray[ iGeo ].empty() )
3651 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3652 if ( newEntry.empty() )
3655 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3656 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3658 entryArray[ iGeo ] = newEntry;
3661 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3663 if ( subIDArray[ iGeo ] > 0 )
3665 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3669 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3670 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3672 subIDArray[ iGeo ] = newID;
3675 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3679 CORBA::String_var errorText;
3680 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3681 if ( errorText.in()[0] )
3684 } // loop on hypotheses
3685 } // loop on sub-meshes and mesh
3688 // copy mesh elements, keeping IDs
3689 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3690 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3692 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3693 ::SMESH_MeshEditor::ElemFeatures elemData;
3695 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3696 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3697 /*vertexLast=*/false);
3698 while ( srcSMIt->more() )
3700 SMESH_subMesh* srcSM = srcSMIt->next();
3701 if ( srcSM->IsEmpty() )
3702 continue; // not yet computed
3703 int newID = shapeMapper.FindNewNotChanged( srcSM );
3707 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3708 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3709 while ( nIt->more() )
3711 SMESH_NodeXYZ node( nIt->next() );
3712 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3714 const SMDS_PositionPtr pos = node->GetPosition();
3715 const double* uv = pos->GetParameters();
3716 switch ( pos->GetTypeOfPosition() )
3718 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3719 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3720 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3721 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3725 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3726 while( eIt->more() )
3728 const SMDS_MeshElement* e = eIt->next();
3729 elemData.Init( e, /*basicOnly=*/false );
3730 elemData.SetID( e->GetID() );
3731 elemData.myNodes.resize( e->NbNodes() );
3732 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3734 for ( iN = 0; nnIt->more(); ++iN )
3736 const SMDS_MeshNode* srcNode = nnIt->next();
3737 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3738 if ( !elemData.myNodes[ iN ])
3741 if ( iN == elemData.myNodes.size() )
3742 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3743 newMeshDS->SetMeshElementOnShape( newElem, newID );
3745 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3746 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3749 newMeshDS->Modified();
3755 TStr2StrMap old2newGroupMap;
3757 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3759 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3760 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3761 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3763 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3764 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3765 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3767 CORBA::String_var name = groups[ i ]->GetName();
3768 SMESH::ElementType elemType = groups[ i ]->GetType();
3770 SMESH::SMESH_GroupBase_var newGroup;
3772 if ( !stdlGroup->_is_nil() )
3774 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3776 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3777 const bool isElem = ( elemType != SMESH::NODE );
3778 CORBA::ULong iE = 0;
3779 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3780 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3782 if ( iE < elemIDs->length() )
3784 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3785 stdlGroup->Add( elemIDs );
3786 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3790 else if ( !geomGroup->_is_nil() )
3792 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3793 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3794 if ( newGeom->_is_nil() )
3796 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3797 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3802 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3805 else if ( !fltrGroup->_is_nil() )
3807 // replace geometry in a filter
3808 SMESH::Filter_var filter = fltrGroup->GetFilter();
3809 SMESH::Filter::Criteria_var criteria;
3810 filter->GetCriteria( criteria.out() );
3812 bool isMissingGroup = false;
3813 std::vector< std::string > badEntries;
3815 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3817 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3818 switch ( criteria[ iCr ].Type )
3820 case SMESH::FT_BelongToMeshGroup:
3822 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3823 btgg->SetGroupID( thresholdID );
3824 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3825 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3826 if ( refGroupSO->_is_nil() )
3828 CORBA::String_var refID = refGroupSO->GetID();
3829 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3830 if ( o2nID == old2newGroupMap.end() )
3832 isMissingGroup = true; // corresponding new group not yet created
3835 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3837 if ( o2nID->second.empty() ) // new referred group is invalid
3838 badEntries.push_back( refID.in() );
3841 case SMESH::FT_BelongToGeom:
3842 case SMESH::FT_BelongToPlane:
3843 case SMESH::FT_BelongToCylinder:
3844 case SMESH::FT_BelongToGenSurface:
3845 case SMESH::FT_LyingOnGeom:
3847 std::string newID = shapeMapper.FindNew( thresholdID );
3848 criteria[ iCr ].ThresholdID = newID.c_str();
3849 if ( newID.empty() )
3850 badEntries.push_back( thresholdID );
3853 case SMESH::FT_ConnectedElements:
3855 if ( thresholdID && thresholdID[0] )
3857 std::string newID = shapeMapper.FindNew( thresholdID );
3858 criteria[ iCr ].ThresholdID = newID.c_str();
3859 if ( newID.empty() )
3860 badEntries.push_back( thresholdID );
3866 } // loop on criteria
3868 if ( isMissingGroup && i < nbGroups )
3870 // to treat the group again
3871 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3875 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3876 newFilter->SetCriteria( criteria );
3878 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3879 newFilter->UnRegister();
3881 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3882 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3883 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3885 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3887 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3890 if ( !badEntries.empty() )
3893 } // treat a group on filter
3895 append( theNewGroups, newGroup );
3897 // fill old2newGroupMap
3898 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3899 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3900 if ( !srcSO->_is_nil() )
3902 CORBA::String_var srcID, newID("");
3903 srcID = srcSO->GetID();
3904 if ( !newSO->_is_nil() )
3905 newID = newSO->GetID();
3906 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3907 std::string( newID.in() )));
3910 if ( newGroup->_is_nil() )
3915 newMeshDS->CompactMesh();
3918 if ( !theMeshName || !theMeshName[0] )
3920 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3921 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3922 CORBA::String_var oldName = soOld->GetName();
3923 SetName( soNew, oldName.in(), "Mesh" );
3925 // mark invalid objects
3926 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3928 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3929 highLightInvalid( invalidSObjects[i].in(), true );
3932 << theNewMesh << ", "
3933 << theNewGroups << ", "
3934 << *theNewSubmeshes.ptr() << ", "
3935 << *theNewHypotheses.ptr() << ", "
3936 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3937 << theSourceMesh << ", "
3938 << theNewGeometry << ", "
3939 << "'" << theMeshName << "', "
3940 << theToCopyGroups << ", "
3941 << theToReuseHypotheses << ", "
3942 << theToCopyElements << " )";
3944 SMESH_CATCH( SMESH::throwCorbaException );
3949 //================================================================================
3951 * \brief Get version of MED format being used.
3953 //================================================================================
3955 char* SMESH_Gen_i::GetMEDFileVersion()
3957 MED::TInt majeur, mineur, release;
3958 majeur = mineur = release = 0;
3959 MED::GetVersionRelease(majeur, mineur, release);
3960 std::ostringstream version;
3961 version << majeur << "." << mineur << "." << release;
3962 return CORBA::string_dup( version.str().c_str() );
3965 //================================================================================
3967 * SMESH_Gen_i::GetMEDVersion
3969 * Get MED version of the file by its name
3971 //================================================================================
3972 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
3974 std::string version = MED::GetMEDVersion( theFileName );
3975 return CORBA::string_dup( version.c_str() );
3978 //================================================================================
3980 * SMESH_Gen_i::CheckCompatibility
3982 * Check compatibility of file with MED format being used, read only.
3984 //================================================================================
3985 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
3987 return MED::CheckCompatibility( theFileName );
3990 //================================================================================
3992 * SMESH_Gen_i::CheckWriteCompatibility
3994 * Check compatibility of file with MED format being used, for append on write.
3996 //================================================================================
3997 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
3999 return MED::CheckCompatibility( theFileName, true );
4002 //================================================================================
4004 * SMESH_Gen_i::GetMeshNames
4006 * Get names of meshes defined in file with the specified name
4008 //================================================================================
4009 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4011 //MESSAGE("GetMeshNames " << theFileName);
4012 SMESH::string_array_var aResult = new SMESH::string_array();
4013 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4015 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4016 //MESSAGE("---" << aNbMeshes);
4018 aResult->length( aNbMeshes );
4019 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4020 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4021 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4024 return aResult._retn();
4027 //=============================================================================
4031 * Save SMESH module's data
4033 //=============================================================================
4034 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4038 if (!myStudyContext)
4041 // Store study contents as a set of python commands
4044 SALOMEDS::Study_var aStudy = getStudyServant();
4046 // Declare a byte stream
4047 SALOMEDS::TMPFile_var aStreamFile;
4049 // Obtain a temporary dir
4050 TCollection_AsciiString tmpDir =
4051 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4053 // Create a sequence of files processed
4054 SALOMEDS_Tool::ListOfFiles aFileSeq;
4055 aFileSeq.reserve( NUM_TMP_FILES );
4057 TCollection_AsciiString aStudyName( "" );
4059 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4061 // Set names of temporary files
4062 TCollection_AsciiString filename =
4063 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4064 TCollection_AsciiString meshfile =
4065 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4066 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4067 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4068 filename = tmpDir + filename;
4069 meshfile = tmpDir + meshfile;
4072 HDFdataset* aDataset;
4073 HDFgroup* aTopGroup;
4075 HDFgroup* aSubGroup;
4076 HDFgroup* aSubSubGroup;
4077 hdf_size aSize[ 1 ];
4080 //Remove the files if they exist: BugID: 11225
4081 #ifndef WIN32 /* unix functionality */
4082 TCollection_AsciiString cmd("rm -f \"");
4084 TCollection_AsciiString cmd("del /F \"");
4094 system(cmd.ToCString());
4096 // MED writer to be used by storage process
4097 DriverMED_W_SMESHDS_Mesh myWriter;
4098 myWriter.SetFile( meshfile.ToCString() );
4101 // SetStoreName() to groups before storing hypotheses to let them refer to
4102 // groups using "store name", which is "Group <group_persistent_id>"
4104 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4105 for ( ; itBig->More(); itBig->Next() ) {
4106 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4107 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4108 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4109 if ( !CORBA::is_nil( anObject ) ) {
4110 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4111 if ( !myMesh->_is_nil() ) {
4112 myMesh->Load(); // load from study file if not yet done
4113 TPythonDump pd; // not to dump GetGroups()
4114 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4115 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4117 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4120 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4121 int anId = myStudyContext->findId( string( objStr.in() ) );
4123 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4124 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4125 aGrpBaseDS->SetStoreName( grpName );
4135 // ---> create HDF file
4136 aFile = new HDFfile( (char*) filename.ToCString() );
4137 aFile->CreateOnDisk();
4139 // --> iterator for top-level objects
4140 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4141 for ( ; itBig->More(); itBig->Next() ) {
4142 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4144 // --> hypotheses root branch (only one for the study)
4145 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4146 // create hypotheses root HDF group
4147 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4148 aTopGroup->CreateOnDisk();
4150 // iterator for all hypotheses
4151 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4152 for ( ; it->More(); it->Next() ) {
4153 SALOMEDS::SObject_wrap mySObject = it->Value();
4154 CORBA::Object_var anObject = SObjectToObject( mySObject );
4155 if ( !CORBA::is_nil( anObject ) ) {
4156 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4157 if ( !myHyp->_is_nil() ) {
4158 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4160 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4161 std::string hypname = hn.in();
4162 std::string libname = ln.in();
4164 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4165 // WIN32 and ".so" for X-system) must be deleted
4166 int libname_len = libname.length();
4168 if( libname_len > 4 )
4169 libname.resize( libname_len - 4 );
4171 // PAL17753 (Regression: missing hypothesis in restored study)
4172 // "lib" also should be removed from the beginning
4173 //if( libname_len > 3 )
4174 //libname.resize( libname_len - 3 );
4175 if( libname_len > 6 )
4176 libname = libname.substr( 3, libname_len - 3 - 3 );
4178 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4179 CORBA::String_var hypdata = myImpl->SaveTo();
4180 int id = myStudyContext->findId( string( objStr.in() ));
4182 // for each hypothesis create HDF group basing on its id
4183 char hypGrpName[30];
4184 sprintf( hypGrpName, "Hypothesis %d", id );
4185 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4186 aGroup->CreateOnDisk();
4187 // --> type name of hypothesis
4188 aSize[ 0 ] = hypname.length() + 1;
4189 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4190 aDataset->CreateOnDisk();
4191 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4192 aDataset->CloseOnDisk();
4193 // --> server plugin library name of hypothesis
4194 aSize[ 0 ] = libname.length() + 1;
4195 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4196 aDataset->CreateOnDisk();
4197 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4198 aDataset->CloseOnDisk();
4199 // --> persistent data of hypothesis
4200 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4201 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4202 aDataset->CreateOnDisk();
4203 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4204 aDataset->CloseOnDisk();
4205 // close hypothesis HDF group
4206 aGroup->CloseOnDisk();
4211 // close hypotheses root HDF group
4212 aTopGroup->CloseOnDisk();
4214 // --> algorithms root branch (only one for the study)
4215 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4216 // create algorithms root HDF group
4217 aTopGroup = new HDFgroup( "Algorithms", aFile );
4218 aTopGroup->CreateOnDisk();
4220 // iterator for all algorithms
4221 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4222 for ( ; it->More(); it->Next() ) {
4223 SALOMEDS::SObject_wrap mySObject = it->Value();
4224 CORBA::Object_var anObject = SObjectToObject( mySObject );
4225 if ( !CORBA::is_nil( anObject ) ) {
4226 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4227 if ( !myHyp->_is_nil() ) {
4228 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4230 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4231 std::string hypname = hn.in();
4232 std::string libname = ln.in();
4234 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4235 // WIN32 and ".so" for X-system) must be deleted
4236 int libname_len = libname.length();
4238 if( libname_len > 4 )
4239 libname.resize( libname_len - 4 );
4241 // PAL17753 (Regression: missing hypothesis in restored study)
4242 // "lib" also should be removed from the beginning
4243 //if( libname_len > 3 )
4244 //libname.resize( libname_len - 3 );
4245 if( libname_len > 6 )
4246 libname = libname.substr( 3, libname_len - 3 - 3 );
4248 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4249 CORBA::String_var hypdata = myImpl->SaveTo();
4250 int id = myStudyContext->findId( string( objStr.in() ) );
4252 // for each algorithm create HDF group basing on its id
4253 char hypGrpName[30];
4254 sprintf( hypGrpName, "Algorithm %d", id );
4255 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4256 aGroup->CreateOnDisk();
4257 // --> type name of algorithm
4258 aSize[0] = hypname.length() + 1;
4259 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4260 aDataset->CreateOnDisk();
4261 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4262 aDataset->CloseOnDisk();
4263 // --> server plugin library name of hypothesis
4264 aSize[0] = libname.length() + 1;
4265 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4266 aDataset->CreateOnDisk();
4267 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4268 aDataset->CloseOnDisk();
4269 // --> persistent data of algorithm
4270 aSize[0] = strlen( hypdata.in() ) + 1;
4271 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4272 aDataset->CreateOnDisk();
4273 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4274 aDataset->CloseOnDisk();
4275 // close algorithm HDF group
4276 aGroup->CloseOnDisk();
4281 // close algorithms root HDF group
4282 aTopGroup->CloseOnDisk();
4284 // --> mesh objects roots branches
4285 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4286 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4287 if ( !CORBA::is_nil( anObject ) ) {
4288 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4289 if ( !myMesh->_is_nil() ) {
4290 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4292 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4293 int id = myStudyContext->findId( string( objStr.in() ) );
4294 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4295 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4296 bool hasShape = myLocMesh.HasShapeToMesh();
4298 // for each mesh open the HDF group basing on its id
4299 char meshGrpName[ 30 ];
4300 sprintf( meshGrpName, "Mesh %d", id );
4301 aTopGroup = new HDFgroup( meshGrpName, aFile );
4302 aTopGroup->CreateOnDisk();
4304 // --> put dataset to hdf file which is a flag that mesh has data
4305 string strHasData = "0";
4306 // check if the mesh is not empty
4307 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4308 // write mesh data to med file
4309 myWriter.SetMesh( mySMESHDSMesh );
4310 myWriter.SetMeshId( id );
4313 aSize[ 0 ] = strHasData.length() + 1;
4314 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4315 aDataset->CreateOnDisk();
4316 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4317 aDataset->CloseOnDisk();
4320 // for each mesh open the HDF group basing on its auto color parameter
4321 char meshAutoColorName[ 30 ];
4322 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4324 anAutoColor[0] = myImpl->GetAutoColor();
4326 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4327 aDataset->CreateOnDisk();
4328 aDataset->WriteOnDisk( anAutoColor );
4329 aDataset->CloseOnDisk();
4331 // issue 0020693. Store _isModified flag
4332 int isModified = myLocMesh.GetIsModified();
4334 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4335 aDataset->CreateOnDisk();
4336 aDataset->WriteOnDisk( &isModified );
4337 aDataset->CloseOnDisk();
4339 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4340 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4342 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4343 aDataset->CreateOnDisk();
4344 aDataset->WriteOnDisk( &meshPersistentId );
4345 aDataset->CloseOnDisk();
4347 // write reference on a shape if exists
4348 SALOMEDS::SObject_wrap myRef;
4349 bool shapeRefFound = false;
4350 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4352 SALOMEDS::SObject_wrap myShape;
4353 bool ok = myRef->ReferencedObject( myShape.inout() );
4355 CORBA::Object_var shapeObj = myShape->GetObject();
4356 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4357 CORBA::String_var myRefOnObject = myShape->GetID();
4358 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4359 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4360 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4361 aDataset->CreateOnDisk();
4362 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4363 aDataset->CloseOnDisk();
4369 std::string info = myImpl->FileInfoToString();
4370 if ( !info.empty() )
4372 aSize[ 0 ] = info.size();
4373 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4374 aDataset->CreateOnDisk();
4375 aDataset->WriteOnDisk( (char*) info.data() );
4376 aDataset->CloseOnDisk();
4379 // write applied hypotheses if exist
4380 SALOMEDS::SObject_wrap myHypBranch;
4381 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4382 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4383 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4385 if ( found && (shapeRefFound || !hasShape) ) {
4386 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4387 aGroup->CreateOnDisk();
4389 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4391 for ( ; it->More(); it->Next() ) {
4392 SALOMEDS::SObject_wrap mySObject = it->Value();
4393 SALOMEDS::SObject_wrap myRefOnHyp;
4394 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4396 // san - it is impossible to recover applied hypotheses
4397 // using their entries within Load() method,
4398 // for there are no AttributeIORs in the study when Load() is working.
4399 // Hence, it is better to store persistent IDs of hypotheses as references to them
4401 //string myRefOnObject = myRefOnHyp->GetID();
4402 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4403 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4404 int id = myStudyContext->findId( string( objStr.in() ) );
4405 //if ( myRefOnObject.length() > 0 ) {
4406 //aSize[ 0 ] = myRefOnObject.length() + 1;
4407 char hypName[ 30 ], hypId[ 30 ];
4408 sprintf( hypName, "Hyp %d", ++hypNb );
4409 sprintf( hypId, "%d", id );
4410 aSize[ 0 ] = strlen( hypId ) + 1;
4411 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4412 aDataset->CreateOnDisk();
4413 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4414 aDataset->WriteOnDisk( hypId );
4415 aDataset->CloseOnDisk();
4419 aGroup->CloseOnDisk();
4422 // write applied algorithms if exist
4423 SALOMEDS::SObject_wrap myAlgoBranch;
4424 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4425 myAlgoBranch.inout() );
4426 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4427 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4429 if ( found && (shapeRefFound || !hasShape)) {
4430 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4431 aGroup->CreateOnDisk();
4433 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4435 for ( ; it->More(); it->Next() ) {
4436 SALOMEDS::SObject_wrap mySObject = it->Value();
4437 SALOMEDS::SObject_wrap myRefOnAlgo;
4438 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4440 // san - it is impossible to recover applied algorithms
4441 // using their entries within Load() method,
4442 // for there are no AttributeIORs in the study when Load() is working.
4443 // Hence, it is better to store persistent IDs of algorithms as references to them
4445 //string myRefOnObject = myRefOnAlgo->GetID();
4446 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4447 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4448 int id = myStudyContext->findId( string( objStr.in() ) );
4449 //if ( myRefOnObject.length() > 0 ) {
4450 //aSize[ 0 ] = myRefOnObject.length() + 1;
4451 char algoName[ 30 ], algoId[ 30 ];
4452 sprintf( algoName, "Algo %d", ++algoNb );
4453 sprintf( algoId, "%d", id );
4454 aSize[ 0 ] = strlen( algoId ) + 1;
4455 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4456 aDataset->CreateOnDisk();
4457 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4458 aDataset->WriteOnDisk( algoId );
4459 aDataset->CloseOnDisk();
4463 aGroup->CloseOnDisk();
4466 // --> submesh objects sub-branches
4468 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4469 SALOMEDS::SObject_wrap mySubmeshBranch;
4470 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4472 if ( found ) // check if there is shape reference in submeshes
4474 bool hasShapeRef = false;
4475 SALOMEDS::ChildIterator_wrap itSM =
4476 aStudy->NewChildIterator( mySubmeshBranch );
4477 for ( ; itSM->More(); itSM->Next() ) {
4478 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4479 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4480 mySubRef->ReferencedObject( myShape.inout() );
4481 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4484 { // remove one submesh
4485 if ( shapeRefFound )
4486 { // unassign hypothesis
4487 SMESH::SMESH_subMesh_var mySubMesh =
4488 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4489 if ( !mySubMesh->_is_nil() ) {
4490 int shapeID = mySubMesh->GetId();
4491 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4492 const list<const SMESHDS_Hypothesis*>& hypList =
4493 mySMESHDSMesh->GetHypothesis( S );
4494 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4495 while ( hyp != hypList.end() ) {
4496 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4497 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4501 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4503 } // loop on submeshes of a type
4504 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4505 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4508 } // end check if there is shape reference in submeshes
4510 char name_meshgroup[ 30 ];
4511 if ( i == GetSubMeshOnVertexTag() )
4512 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4513 else if ( i == GetSubMeshOnEdgeTag() )
4514 strcpy( name_meshgroup, "SubMeshes On Edge" );
4515 else if ( i == GetSubMeshOnWireTag() )
4516 strcpy( name_meshgroup, "SubMeshes On Wire" );
4517 else if ( i == GetSubMeshOnFaceTag() )
4518 strcpy( name_meshgroup, "SubMeshes On Face" );
4519 else if ( i == GetSubMeshOnShellTag() )
4520 strcpy( name_meshgroup, "SubMeshes On Shell" );
4521 else if ( i == GetSubMeshOnSolidTag() )
4522 strcpy( name_meshgroup, "SubMeshes On Solid" );
4523 else if ( i == GetSubMeshOnCompoundTag() )
4524 strcpy( name_meshgroup, "SubMeshes On Compound" );
4526 // for each type of submeshes create container HDF group
4527 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4528 aGroup->CreateOnDisk();
4530 // iterator for all submeshes of given type
4531 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4532 for ( ; itSM->More(); itSM->Next() ) {
4533 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4534 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4535 if ( !CORBA::is_nil( anSubObject ))
4537 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4538 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4539 int subid = myStudyContext->findId( string( objStr.in() ) );
4541 // for each mesh open the HDF group basing on its id
4542 char submeshGrpName[ 30 ];
4543 sprintf( submeshGrpName, "SubMesh %d", subid );
4544 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4545 aSubGroup->CreateOnDisk();
4547 // write reference on a shape, already checked if it exists
4548 SALOMEDS::SObject_wrap mySubRef, myShape;
4549 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4550 mySubRef->ReferencedObject( myShape.inout() );
4551 string myRefOnObject = myShape->GetID();
4552 if ( myRefOnObject.length() > 0 ) {
4553 aSize[ 0 ] = myRefOnObject.length() + 1;
4554 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4555 aDataset->CreateOnDisk();
4556 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4557 aDataset->CloseOnDisk();
4560 // write applied hypotheses if exist
4561 SALOMEDS::SObject_wrap mySubHypBranch;
4562 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4563 mySubHypBranch.inout() );
4565 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4566 aSubSubGroup->CreateOnDisk();
4568 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4570 for ( ; it->More(); it->Next() ) {
4571 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4572 SALOMEDS::SObject_wrap myRefOnHyp;
4573 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4575 //string myRefOnObject = myRefOnHyp->GetID();
4576 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4577 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4578 int id = myStudyContext->findId( string( objStr.in() ) );
4579 //if ( myRefOnObject.length() > 0 ) {
4580 //aSize[ 0 ] = myRefOnObject.length() + 1;
4581 char hypName[ 30 ], hypId[ 30 ];
4582 sprintf( hypName, "Hyp %d", ++hypNb );
4583 sprintf( hypId, "%d", id );
4584 aSize[ 0 ] = strlen( hypId ) + 1;
4585 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4586 aDataset->CreateOnDisk();
4587 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4588 aDataset->WriteOnDisk( hypId );
4589 aDataset->CloseOnDisk();
4593 aSubSubGroup->CloseOnDisk();
4596 // write applied algorithms if exist
4597 SALOMEDS::SObject_wrap mySubAlgoBranch;
4598 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4599 mySubAlgoBranch.inout() );
4601 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4602 aSubSubGroup->CreateOnDisk();
4604 SALOMEDS::ChildIterator_wrap it =
4605 aStudy->NewChildIterator( mySubAlgoBranch );
4607 for ( ; it->More(); it->Next() ) {
4608 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4609 SALOMEDS::SObject_wrap myRefOnAlgo;
4610 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4612 //string myRefOnObject = myRefOnAlgo->GetID();
4613 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4614 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4615 int id = myStudyContext->findId( string( objStr.in() ) );
4616 //if ( myRefOnObject.length() > 0 ) {
4617 //aSize[ 0 ] = myRefOnObject.length() + 1;
4618 char algoName[ 30 ], algoId[ 30 ];
4619 sprintf( algoName, "Algo %d", ++algoNb );
4620 sprintf( algoId, "%d", id );
4621 aSize[ 0 ] = strlen( algoId ) + 1;
4622 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4623 aDataset->CreateOnDisk();
4624 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4625 aDataset->WriteOnDisk( algoId );
4626 aDataset->CloseOnDisk();
4630 aSubSubGroup->CloseOnDisk();
4632 // close submesh HDF group
4633 aSubGroup->CloseOnDisk();
4636 // close container of submeshes by type HDF group
4637 aGroup->CloseOnDisk();
4640 // All sub-meshes will be stored in MED file
4641 // .. will NOT (PAL 12992)
4642 //if ( shapeRefFound )
4643 //myWriter.AddAllSubMeshes();
4645 // store submesh order if any
4646 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4647 if ( theOrderIds.size() ) {
4648 char order_list[ 30 ];
4649 strcpy( order_list, "Mesh Order" );
4650 // count number of submesh ids
4652 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4653 for ( ; idIt != theOrderIds.end(); idIt++ )
4654 nbIDs += (*idIt).size();
4655 // number of values = number of IDs +
4656 // number of lists (for separators) - 1
4657 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4658 idIt = theOrderIds.begin();
4659 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4660 const TListOfInt& idList = *idIt;
4661 if (idIt != theOrderIds.begin()) // not first list
4662 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4663 // dump submesh ids from current list
4664 TListOfInt::const_iterator id_smId = idList.begin();
4665 for( ; id_smId != idList.end(); id_smId++ )
4666 smIDs[ i++ ] = *id_smId;
4669 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4671 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4672 aDataset->CreateOnDisk();
4673 aDataset->WriteOnDisk( smIDs );
4674 aDataset->CloseOnDisk();
4679 // groups root sub-branch
4680 SALOMEDS::SObject_wrap myGroupsBranch;
4681 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4682 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4684 char name_group[ 30 ];
4685 if ( i == GetNodeGroupsTag() )
4686 strcpy( name_group, "Groups of Nodes" );
4687 else if ( i == GetEdgeGroupsTag() )
4688 strcpy( name_group, "Groups of Edges" );
4689 else if ( i == GetFaceGroupsTag() )
4690 strcpy( name_group, "Groups of Faces" );
4691 else if ( i == GetVolumeGroupsTag() )
4692 strcpy( name_group, "Groups of Volumes" );
4693 else if ( i == Get0DElementsGroupsTag() )
4694 strcpy( name_group, "Groups of 0D Elements" );
4695 else if ( i == GetBallElementsGroupsTag() )
4696 strcpy( name_group, "Groups of Balls" );
4698 aGroup = new HDFgroup( name_group, aTopGroup );
4699 aGroup->CreateOnDisk();
4701 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4702 for ( ; it->More(); it->Next() ) {
4703 SALOMEDS::SObject_wrap mySObject = it->Value();
4704 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4705 if ( !CORBA::is_nil( aSubObject ) ) {
4706 SMESH_GroupBase_i* myGroupImpl =
4707 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4710 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4714 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4715 int anId = myStudyContext->findId( string( objStr.in() ) );
4717 // For each group, create a dataset named "Group <group_persistent_id>"
4718 // and store the group's user name into it
4719 const char* grpName = aGrpBaseDS->GetStoreName();
4720 CORBA::String_var aUserName = myGroupImpl->GetName();
4721 aSize[ 0 ] = strlen( aUserName ) + 1;
4723 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4724 aDataset->CreateOnDisk();
4725 aDataset->WriteOnDisk( aUserName );
4726 aDataset->CloseOnDisk();
4729 // For each group, create a dataset named "Group <group_persistent_id> Color"
4730 // and store the group's color into it
4731 char grpColorName[ 30 ];
4732 sprintf( grpColorName, "ColorGroup %d", anId );
4733 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4735 anRGB[ 0 ] = aColor.R;
4736 anRGB[ 1 ] = aColor.G;
4737 anRGB[ 2 ] = aColor.B;
4739 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4740 aDataset->CreateOnDisk();
4741 aDataset->WriteOnDisk( anRGB );
4742 aDataset->CloseOnDisk();
4744 // Pass SMESHDS_Group to MED writer
4745 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4747 myWriter.AddGroup( aGrpDS );
4749 // write reference on a shape if exists
4750 SMESHDS_GroupOnGeom* aGeomGrp =
4751 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4753 SALOMEDS::SObject_wrap mySubRef, myShape;
4754 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4755 mySubRef->ReferencedObject( myShape.inout() ) &&
4756 !CORBA::is_nil( myShape->GetObject() ))
4758 CORBA::String_var myRefOnObject = myShape->GetID();
4759 if ( myRefOnObject.in()[0] ) {
4760 char aRefName[ 30 ];
4761 sprintf( aRefName, "Ref on shape %d", anId);
4762 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4763 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4764 aDataset->CreateOnDisk();
4765 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4766 aDataset->CloseOnDisk();
4769 else // shape ref is invalid:
4771 // save a group on geometry as ordinary group
4772 myWriter.AddGroup( aGeomGrp );
4775 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4776 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4778 std::string str = aFilterGrp_i->FilterToString();
4779 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4780 aSize[ 0 ] = str.length() + 1;
4781 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4782 aDataset->CreateOnDisk();
4783 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4784 aDataset->CloseOnDisk();
4788 aGroup->CloseOnDisk();
4792 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4794 // Flush current mesh information into MED file
4797 // save info on nb of elements
4798 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4800 // maybe a shape was deleted in the study
4801 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4802 TopoDS_Shape nullShape;
4803 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4806 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4811 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4812 aGroup->CreateOnDisk();
4814 // each element belongs to one or none submesh,
4815 // so for each node/element, we store a submesh ID
4817 // Store submesh IDs
4818 for ( int isNode = 0; isNode < 2; ++isNode )
4820 SMDS_ElemIteratorPtr eIt =
4821 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4822 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4825 std::vector<int> smIDs; smIDs.reserve( nbElems );
4826 while ( eIt->more() )
4827 if ( const SMDS_MeshElement* e = eIt->next())
4828 smIDs.push_back( e->getshapeId() );
4830 aSize[ 0 ] = nbElems;
4831 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4832 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4833 aDataset->CreateOnDisk();
4834 aDataset->WriteOnDisk( & smIDs[0] );
4835 aDataset->CloseOnDisk();
4838 aGroup->CloseOnDisk();
4840 // Store node positions on sub-shapes (SMDS_Position):
4841 // ----------------------------------------------------
4843 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4844 aGroup->CreateOnDisk();
4846 // in aGroup, create 5 datasets to contain:
4847 // "Nodes on Edges" - ID of node on edge
4848 // "Edge positions" - U parameter on node on edge
4849 // "Nodes on Faces" - ID of node on face
4850 // "Face U positions" - U parameter of node on face
4851 // "Face V positions" - V parameter of node on face
4853 // Find out nb of nodes on edges and faces
4854 // Collect corresponding sub-meshes
4855 int nbEdgeNodes = 0, nbFaceNodes = 0;
4856 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4857 // loop on SMESHDS_SubMesh'es
4858 while ( smIt->more() )
4860 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4861 if ( aSubMesh->IsComplexSubmesh() )
4862 continue; // submesh containing other submeshs
4863 int nbNodes = aSubMesh->NbNodes();
4864 if ( nbNodes == 0 ) continue;
4866 int aShapeID = aSubMesh->GetID();
4867 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4869 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4870 // write only SMDS_FacePosition and SMDS_EdgePosition
4871 switch ( aShapeType ) {
4873 nbFaceNodes += nbNodes;
4874 aFaceSM.push_back( aSubMesh );
4877 nbEdgeNodes += nbNodes;
4878 aEdgeSM.push_back( aSubMesh );
4884 // Treat positions on edges or faces
4885 for ( int onFace = 0; onFace < 2; onFace++ )
4887 // Create arrays to store in datasets
4888 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4889 if (!nbNodes) continue;
4890 int* aNodeIDs = new int [ nbNodes ];
4891 double* aUPos = new double [ nbNodes ];
4892 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4895 // loop on sub-meshes
4896 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4897 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4898 for ( ; itSM != pListSM->end(); itSM++ )
4900 SMESHDS_SubMesh* aSubMesh = (*itSM);
4902 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4903 // loop on nodes in aSubMesh
4904 while ( itNode->more() )
4907 const SMDS_MeshNode* node = itNode->next();
4908 aNodeIDs [ iNode ] = node->GetID();
4911 const SMDS_PositionPtr pos = node->GetPosition();
4912 if ( onFace ) { // on FACE
4913 SMDS_FacePositionPtr fPos = pos;
4915 aUPos[ iNode ] = fPos->GetUParameter();
4916 aVPos[ iNode ] = fPos->GetVParameter();
4923 SMDS_EdgePositionPtr ePos = pos;
4925 aUPos[ iNode ] = ePos->GetUParameter();
4931 } // loop on nodes in aSubMesh
4932 } // loop on sub-meshes
4937 aSize[ 0 ] = nbNodes;
4939 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4940 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4941 aDataset->CreateOnDisk();
4942 aDataset->WriteOnDisk( aNodeIDs );
4943 aDataset->CloseOnDisk();
4946 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4947 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4948 aDataset->CreateOnDisk();
4949 aDataset->WriteOnDisk( aUPos );
4950 aDataset->CloseOnDisk();
4953 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4954 aDataset->CreateOnDisk();
4955 aDataset->WriteOnDisk( aVPos );
4956 aDataset->CloseOnDisk();
4961 if ( aVPos ) delete [] aVPos;
4963 } // treat positions on edges or faces
4965 // close "Node Positions" group
4966 aGroup->CloseOnDisk();
4968 } // if ( there are submeshes in SMESHDS_Mesh )
4971 // close mesh HDF group
4972 aTopGroup->CloseOnDisk();
4980 aFile->CloseOnDisk();
4983 // Convert temporary files to stream
4984 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
4986 // Remove temporary files and directory
4988 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4990 return aStreamFile._retn();
4993 //=============================================================================
4995 * SMESH_Gen_i::SaveASCII
4997 * Save SMESH module's data in ASCII format
4999 //=============================================================================
5001 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5003 bool isMultiFile ) {
5004 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5005 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5006 return aStreamFile._retn();
5008 //after usual saving needs to encipher binary to text string
5009 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5010 int size = aStreamFile.in().length();
5011 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5012 for ( int i = 0; i < size; i++ )
5013 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5015 buffer[size * 3] = '\0';
5017 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5019 return anAsciiStreamFile._retn();
5022 //=============================================================================
5024 * SMESH_Gen_i::loadGeomData
5026 * Load GEOM module data
5028 //=============================================================================
5030 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
5032 if ( theCompRoot->_is_nil() )
5035 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
5036 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
5039 //=============================================================================
5043 * Load SMESH module's data
5045 //=============================================================================
5047 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5048 const SALOMEDS::TMPFile& theStream,
5052 //if (!myStudyContext)
5054 SALOMEDS::Study_var aStudy = getStudyServant();
5055 /* if( !theComponent->_is_nil() )
5057 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
5058 loadGeomData( aStudy->FindComponent( "GEOM" ) );
5061 // Get temporary files location
5062 TCollection_AsciiString tmpDir =
5063 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5065 // Convert the stream into sequence of files to process
5066 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5069 TCollection_AsciiString aStudyName( "" );
5070 if ( isMultiFile ) {
5071 CORBA::WString_var url = aStudy->URL();
5072 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5074 // Set names of temporary files
5075 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5076 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5080 HDFdataset* aDataset;
5081 HDFgroup* aTopGroup;
5083 HDFgroup* aSubGroup;
5084 HDFgroup* aSubSubGroup;
5087 // ---> open HDF file
5088 aFile = new HDFfile( (char*) filename.ToCString() );
5090 aFile->OpenOnDisk( HDF_RDONLY );
5092 catch ( HDFexception ) {
5093 INFOS( "Load(): " << filename << " not found!" );
5097 TPythonDump pd; // prevent dump during loading
5099 // DriverMED_R_SMESHDS_Mesh myReader;
5100 // myReader.SetFile( meshfile.ToCString() );
5102 // For PAL13473 ("Repetitive mesh") implementation.
5103 // New dependencies between SMESH objects are established:
5104 // now hypotheses can refer to meshes, shapes and other hypotheses.
5105 // To keep data consistent, the following order of data restoration
5107 // 1. Create hypotheses
5108 // 2. Create all meshes
5109 // 3. Load hypotheses' data
5112 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5113 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5114 list< SMESH::Filter_var > filters;
5116 // get total number of top-level groups
5117 int aNbGroups = aFile->nInternalObjects();
5118 if ( aNbGroups > 0 ) {
5119 // --> in first turn we should read&create hypotheses
5120 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5121 // open hypotheses root HDF group
5122 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5123 aTopGroup->OpenOnDisk();
5125 // get number of hypotheses
5126 int aNbObjects = aTopGroup->nInternalObjects();
5127 for ( int j = 0; j < aNbObjects; j++ ) {
5128 // try to identify hypothesis
5129 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5130 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5132 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5133 // open hypothesis group
5134 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5135 aGroup->OpenOnDisk();
5137 // --> get hypothesis id
5138 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5143 // get number of datasets
5144 int aNbSubObjects = aGroup->nInternalObjects();
5145 for ( int k = 0; k < aNbSubObjects; k++ ) {
5147 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5148 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5149 // --> get hypothesis name
5150 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5151 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5152 aDataset->OpenOnDisk();
5153 size = aDataset->GetSize();
5154 char* hypname_str = new char[ size ];
5155 aDataset->ReadFromDisk( hypname_str );
5156 hypname = string( hypname_str );
5157 delete [] hypname_str;
5158 aDataset->CloseOnDisk();
5160 // --> get hypothesis plugin library name
5161 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5162 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5163 aDataset->OpenOnDisk();
5164 size = aDataset->GetSize();
5165 char* libname_str = new char[ size ];
5166 aDataset->ReadFromDisk( libname_str );
5167 if(MYDEBUG) SCRUTE( libname_str );
5168 libname = string( libname_str );
5169 delete [] libname_str;
5170 aDataset->CloseOnDisk();
5172 // --> get hypothesis data
5173 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5174 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5175 aDataset->OpenOnDisk();
5176 size = aDataset->GetSize();
5177 char* hypdata_str = new char[ size ];
5178 aDataset->ReadFromDisk( hypdata_str );
5179 hypdata = string( hypdata_str );
5180 delete [] hypdata_str;
5181 aDataset->CloseOnDisk();
5184 // close hypothesis HDF group
5185 aGroup->CloseOnDisk();
5187 // --> restore hypothesis from data
5188 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5189 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5190 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5191 SMESH::SMESH_Hypothesis_var myHyp;
5193 try { // protect persistence mechanism against exceptions
5194 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5197 INFOS( "Exception during hypothesis creation" );
5200 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5202 // myImpl->LoadFrom( hypdata.c_str() );
5203 hypDataList.push_back( make_pair( myImpl, hypdata ));
5204 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5205 int newId = myStudyContext->findId( iorString.in() );
5206 myStudyContext->mapOldToNew( id, newId );
5209 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5213 // close hypotheses root HDF group
5214 aTopGroup->CloseOnDisk();
5218 // --> then we should read&create algorithms
5219 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5220 // open algorithms root HDF group
5221 aTopGroup = new HDFgroup( "Algorithms", aFile );
5222 aTopGroup->OpenOnDisk();
5224 // get number of algorithms
5225 int aNbObjects = aTopGroup->nInternalObjects();
5226 for ( int j = 0; j < aNbObjects; j++ ) {
5227 // try to identify algorithm
5228 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5229 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5231 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5232 // open algorithm group
5233 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5234 aGroup->OpenOnDisk();
5236 // --> get algorithm id
5237 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5242 // get number of datasets
5243 int aNbSubObjects = aGroup->nInternalObjects();
5244 for ( int k = 0; k < aNbSubObjects; k++ ) {
5246 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5247 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5248 // --> get algorithm name
5249 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5250 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5251 aDataset->OpenOnDisk();
5252 size = aDataset->GetSize();
5253 char* hypname_str = new char[ size ];
5254 aDataset->ReadFromDisk( hypname_str );
5255 hypname = string( hypname_str );
5256 delete [] hypname_str;
5257 aDataset->CloseOnDisk();
5259 // --> get algorithm plugin library name
5260 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5261 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5262 aDataset->OpenOnDisk();
5263 size = aDataset->GetSize();
5264 char* libname_str = new char[ size ];
5265 aDataset->ReadFromDisk( libname_str );
5266 if(MYDEBUG) SCRUTE( libname_str );
5267 libname = string( libname_str );
5268 delete [] libname_str;
5269 aDataset->CloseOnDisk();
5271 // --> get algorithm data
5272 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5273 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5274 aDataset->OpenOnDisk();
5275 size = aDataset->GetSize();
5276 char* hypdata_str = new char[ size ];
5277 aDataset->ReadFromDisk( hypdata_str );
5278 if(MYDEBUG) SCRUTE( hypdata_str );
5279 hypdata = string( hypdata_str );
5280 delete [] hypdata_str;
5281 aDataset->CloseOnDisk();
5284 // close algorithm HDF group
5285 aGroup->CloseOnDisk();
5287 // --> restore algorithm from data
5288 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5289 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5290 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5291 SMESH::SMESH_Hypothesis_var myHyp;
5293 try { // protect persistence mechanism against exceptions
5294 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5296 catch( SALOME::SALOME_Exception& ex )
5298 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5301 INFOS( "Exception during hypothesis creation" );
5304 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5306 //myImpl->LoadFrom( hypdata.c_str() );
5307 hypDataList.push_back( make_pair( myImpl, hypdata ));
5308 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5309 int newId = myStudyContext->findId( iorString.in() );
5310 myStudyContext->mapOldToNew( id, newId );
5313 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5317 // close algorithms root HDF group
5318 aTopGroup->CloseOnDisk();
5322 // --> the rest groups should be meshes
5323 for ( int i = 0; i < aNbGroups; i++ ) {
5324 // identify next group
5325 char meshName[ HDF_NAME_MAX_LEN+1 ];
5326 aFile->InternalObjectIndentify( i, meshName );
5328 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5330 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5334 // open mesh HDF group
5335 aTopGroup = new HDFgroup( meshName, aFile );
5336 aTopGroup->OpenOnDisk();
5338 // get number of child HDF objects
5339 int aNbObjects = aTopGroup->nInternalObjects();
5340 if ( aNbObjects > 0 ) {
5342 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5343 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5344 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5345 if ( !myNewMeshImpl )
5347 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5349 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5350 int newId = myStudyContext->findId( iorString.in() );
5351 myStudyContext->mapOldToNew( id, newId );
5354 // try to read and set auto color flag
5355 char aMeshAutoColorName[ 30 ];
5356 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5357 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5359 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5360 aDataset->OpenOnDisk();
5361 size = aDataset->GetSize();
5362 int* anAutoColor = new int[ size ];
5363 aDataset->ReadFromDisk( anAutoColor );
5364 aDataset->CloseOnDisk();
5365 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5366 delete [] anAutoColor;
5369 // try to read and set reference to shape
5370 GEOM::GEOM_Object_var aShapeObject;
5371 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5372 // load mesh "Ref on shape" - it's an entry to SObject
5373 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5374 aDataset->OpenOnDisk();
5375 size = aDataset->GetSize();
5376 char* refFromFile = new char[ size ];
5377 aDataset->ReadFromDisk( refFromFile );
5378 aDataset->CloseOnDisk();
5379 if ( strlen( refFromFile ) > 0 ) {
5380 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5382 // Make sure GEOM data are loaded first
5383 //loadGeomData( shapeSO->GetFatherComponent() );
5385 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5386 if ( !CORBA::is_nil( shapeObject ) ) {
5387 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5388 if ( !aShapeObject->_is_nil() )
5389 myNewMeshImpl->SetShape( aShapeObject );
5392 delete [] refFromFile;
5395 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5396 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5398 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5399 aDataset->OpenOnDisk();
5400 size = aDataset->GetSize();
5401 int* meshPersistentId = new int[ size ];
5402 aDataset->ReadFromDisk( meshPersistentId );
5403 aDataset->CloseOnDisk();
5404 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5405 delete [] meshPersistentId;
5408 // Restore file info
5409 if ( aTopGroup->ExistInternalObject( "file info" ))
5411 aDataset = new HDFdataset( "file info", aTopGroup );
5412 aDataset->OpenOnDisk();
5413 size = aDataset->GetSize();
5414 std::string info( size, ' ');
5415 aDataset->ReadFromDisk( (char*) info.data() );
5416 aDataset->CloseOnDisk();
5417 myNewMeshImpl->FileInfoFromString( info );
5423 // As all object that can be referred by hypothesis are created,
5424 // we can restore hypothesis data
5426 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5427 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5429 SMESH_Hypothesis_i* hyp = hyp_data->first;
5430 string & data = hyp_data->second;
5431 hyp->LoadFrom( data.c_str() );
5434 // Restore the rest mesh data
5436 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5437 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5439 aTopGroup = meshi_group->second;
5440 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5441 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5442 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5444 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5445 bool hasData = false;
5448 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5449 int newId = myStudyContext->findId( iorString.in() );
5450 int meshOldId = myStudyContext->getOldId( newId );
5452 // try to find mesh data dataset
5453 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5454 // load mesh "has data" flag
5455 aDataset = new HDFdataset( "Has data", aTopGroup );
5456 aDataset->OpenOnDisk();
5457 size = aDataset->GetSize();
5458 char* strHasData = new char[ size ];
5459 aDataset->ReadFromDisk( strHasData );
5460 aDataset->CloseOnDisk();
5461 if ( strcmp( strHasData, "1") == 0 ) {
5464 delete [] strHasData;
5467 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5468 // nodes and elements are not yet put into sub-meshes)
5469 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5470 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5471 aGroup->OpenOnDisk();
5472 // get number of applied algorithms
5473 int aNbSubObjects = aGroup->nInternalObjects();
5474 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5475 for ( int j = 0; j < aNbSubObjects; j++ ) {
5476 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5477 aGroup->InternalObjectIndentify( j, name_dataset );
5478 // check if it is an algorithm
5479 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5480 aDataset = new HDFdataset( name_dataset, aGroup );
5481 aDataset->OpenOnDisk();
5482 size = aDataset->GetSize();
5483 char* refFromFile = new char[ size ];
5484 aDataset->ReadFromDisk( refFromFile );
5485 aDataset->CloseOnDisk();
5486 // san - it is impossible to recover applied algorithms using their entries within Load() method
5487 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5488 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5489 int id = atoi( refFromFile );
5490 delete [] refFromFile;
5491 string anIOR = myStudyContext->getIORbyOldId( id );
5492 if ( !anIOR.empty() ) {
5493 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5494 if ( !CORBA::is_nil( hypObject ) ) {
5495 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5496 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5497 || !myNewMeshImpl->HasShapeToMesh()) )
5498 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5503 aGroup->CloseOnDisk();
5506 // try to get applied hypotheses
5507 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5508 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5509 aGroup->OpenOnDisk();
5510 // get number of applied hypotheses
5511 int aNbSubObjects = aGroup->nInternalObjects();
5512 for ( int j = 0; j < aNbSubObjects; j++ ) {
5513 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5514 aGroup->InternalObjectIndentify( j, name_dataset );
5515 // check if it is a hypothesis
5516 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5517 aDataset = new HDFdataset( name_dataset, aGroup );
5518 aDataset->OpenOnDisk();
5519 size = aDataset->GetSize();
5520 char* refFromFile = new char[ size ];
5521 aDataset->ReadFromDisk( refFromFile );
5522 aDataset->CloseOnDisk();
5523 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5524 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5525 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5526 int id = atoi( refFromFile );
5527 delete [] refFromFile;
5528 string anIOR = myStudyContext->getIORbyOldId( id );
5529 if ( !anIOR.empty() ) {
5530 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5531 if ( !CORBA::is_nil( hypObject ) ) {
5532 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5533 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5534 || !myNewMeshImpl->HasShapeToMesh()) )
5535 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5540 aGroup->CloseOnDisk();
5543 // --> try to find SUB-MESHES containers for each type of submesh
5544 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5545 const char* name_meshgroup = 0;
5546 if ( j == GetSubMeshOnVertexTag() )
5547 name_meshgroup = "SubMeshes On Vertex";
5548 else if ( j == GetSubMeshOnEdgeTag() )
5549 name_meshgroup = "SubMeshes On Edge";
5550 else if ( j == GetSubMeshOnWireTag() )
5551 name_meshgroup = "SubMeshes On Wire";
5552 else if ( j == GetSubMeshOnFaceTag() )
5553 name_meshgroup = "SubMeshes On Face";
5554 else if ( j == GetSubMeshOnShellTag() )
5555 name_meshgroup = "SubMeshes On Shell";
5556 else if ( j == GetSubMeshOnSolidTag() )
5557 name_meshgroup = "SubMeshes On Solid";
5558 else if ( j == GetSubMeshOnCompoundTag() )
5559 name_meshgroup = "SubMeshes On Compound";
5561 // try to get submeshes container HDF group
5562 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5563 // open submeshes containers HDF group
5564 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5565 aGroup->OpenOnDisk();
5567 // get number of submeshes
5568 int aNbSubMeshes = aGroup->nInternalObjects();
5569 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5571 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5572 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5573 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5574 // --> get submesh id
5575 int subid = atoi( name_submeshgroup + 7 );
5578 // open submesh HDF group
5579 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5580 aSubGroup->OpenOnDisk();
5582 // try to read and set reference to subshape
5583 GEOM::GEOM_Object_var aSubShapeObject;
5584 SMESH::SMESH_subMesh_var aSubMesh;
5586 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5587 // load submesh "Ref on shape" - it's an entry to SObject
5588 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5589 aDataset->OpenOnDisk();
5590 size = aDataset->GetSize();
5591 char* refFromFile = new char[ size ];
5592 aDataset->ReadFromDisk( refFromFile );
5593 aDataset->CloseOnDisk();
5594 if ( strlen( refFromFile ) > 0 ) {
5595 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5596 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5597 if ( !CORBA::is_nil( subShapeObject ) ) {
5598 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5599 if ( !aSubShapeObject->_is_nil() )
5600 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5601 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5602 if ( aSubMesh->_is_nil() )
5604 string iorSubString = GetORB()->object_to_string( aSubMesh );
5605 int newSubId = myStudyContext->findId( iorSubString );
5606 myStudyContext->mapOldToNew( subid, newSubId );
5609 delete [] refFromFile;
5612 if ( aSubMesh->_is_nil() )
5615 // try to get applied algorithms
5616 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5617 // open "applied algorithms" HDF group
5618 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5619 aSubSubGroup->OpenOnDisk();
5620 // get number of applied algorithms
5621 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5622 for ( int l = 0; l < aNbSubObjects; l++ ) {
5623 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5624 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5625 // check if it is an algorithm
5626 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5627 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5628 aDataset->OpenOnDisk();
5629 size = aDataset->GetSize();
5630 char* refFromFile = new char[ size ];
5631 aDataset->ReadFromDisk( refFromFile );
5632 aDataset->CloseOnDisk();
5634 int id = atoi( refFromFile );
5635 string anIOR = myStudyContext->getIORbyOldId( id );
5636 if ( !anIOR.empty() ) {
5637 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5638 if ( !CORBA::is_nil( hypObject ) ) {
5639 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5640 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5641 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5644 delete [] refFromFile;
5647 // close "applied algorithms" HDF group
5648 aSubSubGroup->CloseOnDisk();
5651 // try to get applied hypotheses
5652 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5653 // open "applied hypotheses" HDF group
5654 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5655 aSubSubGroup->OpenOnDisk();
5656 // get number of applied hypotheses
5657 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5658 for ( int l = 0; l < aNbSubObjects; l++ ) {
5659 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5660 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5661 // check if it is a hypothesis
5662 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5663 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5664 aDataset->OpenOnDisk();
5665 size = aDataset->GetSize();
5666 char* refFromFile = new char[ size ];
5667 aDataset->ReadFromDisk( refFromFile );
5668 aDataset->CloseOnDisk();
5670 int id = atoi( refFromFile );
5671 string anIOR = myStudyContext->getIORbyOldId( id );
5672 if ( !anIOR.empty() ) {
5673 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5674 if ( !CORBA::is_nil( hypObject ) ) {
5675 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5676 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5677 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5680 delete [] refFromFile;
5683 // close "APPLIED HYPOTHESES" hdf group
5684 aSubSubGroup->CloseOnDisk();
5687 // close SUB-MESH hdf group
5688 aSubGroup->CloseOnDisk();
5691 // close SUB-MESHES containers hdf group
5692 aGroup->CloseOnDisk();
5696 // try to get GROUPS
5697 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5698 char name_group[ 30 ];
5699 if ( ii == GetNodeGroupsTag() )
5700 strcpy( name_group, "Groups of Nodes" );
5701 else if ( ii == GetEdgeGroupsTag() )
5702 strcpy( name_group, "Groups of Edges" );
5703 else if ( ii == GetFaceGroupsTag() )
5704 strcpy( name_group, "Groups of Faces" );
5705 else if ( ii == GetVolumeGroupsTag() )
5706 strcpy( name_group, "Groups of Volumes" );
5707 else if ( ii == Get0DElementsGroupsTag() )
5708 strcpy( name_group, "Groups of 0D Elements" );
5709 else if ( ii == GetBallElementsGroupsTag() )
5710 strcpy( name_group, "Groups of Balls" );
5712 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5713 aGroup = new HDFgroup( name_group, aTopGroup );
5714 aGroup->OpenOnDisk();
5715 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5716 // within aGroup->ExistInternalObject( name )
5717 std::vector< std::string > subNames;
5718 TColStd_MapOfAsciiString mapOfNames;
5719 aGroup->GetAllObjects( subNames );
5720 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5721 mapOfNames.Add( subNames[ iN ].c_str() );
5723 for ( size_t j = 0; j < subNames.size(); j++ ) {
5724 const std::string& name_dataset = subNames[ j ];
5725 // check if it is a group
5726 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5729 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5732 int groupID = -1; // group local ID (also persistent)
5734 groupID = atoi( endptr + 1 );
5735 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5736 aDataset->OpenOnDisk();
5738 // Retrieve actual group name
5739 size = aDataset->GetSize();
5740 char* nameFromFile = new char[ size ];
5741 aDataset->ReadFromDisk( nameFromFile );
5742 aDataset->CloseOnDisk();
5744 // Try to find a shape reference
5745 TopoDS_Shape aShape;
5746 char aRefName[ 30 ];
5747 sprintf( aRefName, "Ref on shape %d", subid);
5748 if ( mapOfNames.Contains( aRefName ))
5750 // load mesh "Ref on shape" - it's an entry to SObject
5751 aDataset = new HDFdataset( aRefName, aGroup );
5752 aDataset->OpenOnDisk();
5753 size = aDataset->GetSize();
5754 char* refFromFile = new char[ size ];
5755 aDataset->ReadFromDisk( refFromFile );
5756 aDataset->CloseOnDisk();
5757 if ( strlen( refFromFile ) > 0 ) {
5758 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5759 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5760 if ( !CORBA::is_nil( shapeObject ) ) {
5761 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5762 if ( !aShapeObject->_is_nil() )
5763 aShape = GeomObjectToShape( aShapeObject );
5766 delete [] refFromFile;
5768 // Try to read a filter of SMESH_GroupOnFilter
5769 SMESH::Filter_var filter;
5770 SMESH_PredicatePtr predicate;
5771 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5772 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5774 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5775 aDataset->OpenOnDisk();
5776 size = aDataset->GetSize();
5777 char* persistStr = new char[ size ];
5778 aDataset->ReadFromDisk( persistStr );
5779 aDataset->CloseOnDisk();
5780 if ( strlen( persistStr ) > 0 ) {
5781 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5782 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5783 filters.push_back( filter );
5785 delete [] persistStr;
5788 // Create group servant
5789 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5790 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5791 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5792 delete [] nameFromFile;
5793 // Obtain a SMESHDS_Group object
5794 if ( aNewGroup->_is_nil() )
5797 string iorSubString = GetORB()->object_to_string( aNewGroup );
5798 int newSubId = myStudyContext->findId( iorSubString );
5799 myStudyContext->mapOldToNew( subid, newSubId );
5801 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5805 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5806 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5808 aFilterGroup->SetFilter( filter );
5809 filter->UnRegister();
5811 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5812 if ( !aGroupBaseDS )
5815 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5818 // Read color of the group
5819 char aGroupColorName[ 30 ];
5820 sprintf( aGroupColorName, "ColorGroup %d", subid);
5821 if ( mapOfNames.Contains( aGroupColorName ))
5823 aDataset = new HDFdataset( aGroupColorName, aGroup );
5824 aDataset->OpenOnDisk();
5825 size = aDataset->GetSize();
5826 double* anRGB = new double[ size ];
5827 aDataset->ReadFromDisk( anRGB );
5828 aDataset->CloseOnDisk();
5829 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5830 aGroupBaseDS->SetColor( aColor );
5835 aGroup->CloseOnDisk();
5839 // instead of reading mesh data, we read only brief information of all
5840 // objects: mesh, groups, sub-meshes (issue 0021208)
5843 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5844 meshfile.ToCString(), filename.ToCString(),
5848 // read Sub-Mesh ORDER if any
5849 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5850 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5851 aDataset->OpenOnDisk();
5852 size = aDataset->GetSize();
5853 int* smIDs = new int[ size ];
5854 aDataset->ReadFromDisk( smIDs );
5855 aDataset->CloseOnDisk();
5856 TListOfListOfInt anOrderIds;
5857 anOrderIds.push_back( TListOfInt() );
5858 for ( int i = 0; i < size; i++ )
5859 if ( smIDs[ i ] < 0 ) // is separator
5860 anOrderIds.push_back( TListOfInt() );
5862 anOrderIds.back().push_back(smIDs[ i ]);
5864 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5869 // update hyps needing full mesh data restored (issue 20918)
5870 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5872 SMESH_Hypothesis_i* hyp = hyp_data->first;
5873 hyp->UpdateAsMeshesRestored();
5876 // notify algos on completed restoration to set sub-mesh event listeners
5877 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5879 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5880 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5882 TopoDS_Shape myLocShape;
5883 if(myLocMesh.HasShapeToMesh())
5884 myLocShape = myLocMesh.GetShapeToMesh();
5886 myLocShape = SMESH_Mesh::PseudoShape();
5888 myLocMesh.GetSubMesh(myLocShape)->
5889 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5892 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5893 list< SMESH::Filter_var >::iterator f = filters.begin();
5894 for ( ; f != filters.end(); ++f )
5895 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5896 fi->FindBaseObjects();
5901 aTopGroup->CloseOnDisk();
5904 aFile->CloseOnDisk();
5907 // Remove temporary files created from the stream
5910 SMESH_File meshFile( meshfile.ToCString() );
5911 if ( !meshFile ) // no meshfile exists
5913 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5917 Engines::Container_var container = GetContainerRef();
5918 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5920 container_i->registerTemporaryFile( filename.ToCString() );
5921 container_i->registerTemporaryFile( meshfile.ToCString() );
5922 container_i->registerTemporaryFile( tmpDir.ToCString() );
5926 pd << ""; // prevent optimizing pd out
5928 // creation of tree nodes for all data objects in the study
5929 // to support tree representation customization and drag-n-drop:
5930 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5931 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5932 useCaseBuilder->SetRootCurrent();
5933 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5934 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5935 for (it->InitEx(true); it->More(); it->Next()) {
5936 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5943 //=============================================================================
5945 * SMESH_Gen_i::LoadASCII
5947 * Load SMESH module's data in ASCII format
5949 //=============================================================================
5951 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5952 const SALOMEDS::TMPFile& theStream,
5954 bool isMultiFile ) {
5955 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5956 return Load( theComponent, theStream, theURL, isMultiFile );
5958 //before call main ::Load method it's need for decipher text format to
5959 //binary ( "|xx" => x' )
5960 int size = theStream.length();
5961 if ( int((size / 3 )*3) != size ) //error size of buffer
5964 int real_size = int(size / 3);
5966 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5969 unsigned int c = -1;
5970 for ( int i = 0; i < real_size; i++ )
5972 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5973 sscanf( tmp, "%x", &c );
5974 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5977 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5979 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5982 //=============================================================================
5984 * SMESH_Gen_i::Close
5986 * Clears study-connected data when it is closed
5988 //=============================================================================
5990 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
5992 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
5994 // Clear study contexts data
5995 myStudyContext->Clear();
5997 // remove the tmp files meshes are loaded from
5998 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6000 // Clean trace of API methods calls
6006 //=============================================================================
6008 * SMESH_Gen_i::ComponentDataType
6010 * Get component data type
6012 //=============================================================================
6014 char* SMESH_Gen_i::ComponentDataType()
6016 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6017 return CORBA::string_dup( "SMESH" );
6021 //=============================================================================
6023 * SMESH_Gen_i::IORToLocalPersistentID
6025 * Transform data from transient form to persistent
6027 //=============================================================================
6029 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6030 const char* IORString,
6031 CORBA::Boolean /*isMultiFile*/,
6032 CORBA::Boolean /*isASCII*/ )
6034 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6036 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6037 int anId = myStudyContext->findId( IORString );
6039 if(MYDEBUG) MESSAGE( "VSR " << anId )
6041 sprintf( strId, "%d", anId );
6042 return CORBA::string_dup( strId );
6045 return CORBA::string_dup( "" );
6048 //=============================================================================
6050 * SMESH_Gen_i::LocalPersistentIDToIOR
6052 * Transform data from persistent form to transient
6054 //=============================================================================
6056 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6057 const char* aLocalPersistentID,
6058 CORBA::Boolean /*isMultiFile*/,
6059 CORBA::Boolean /*isASCII*/ )
6061 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6063 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6064 int anId = atoi( aLocalPersistentID );
6065 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6067 return CORBA::string_dup( "" );
6070 //=======================================================================
6071 //function : RegisterObject
6073 //=======================================================================
6075 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6077 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6078 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6079 return myStudyContext->addObject( string( iorString.in() ) );
6084 //================================================================================
6086 * \brief Return id of registered object
6087 * \param theObject - the Object
6088 * \retval int - Object id
6090 //================================================================================
6092 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6094 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6095 string iorString = GetORB()->object_to_string( theObject );
6096 return myStudyContext->findId( iorString );
6101 //=============================================================================
6103 * SMESH_Gen_i::SetName
6105 * Set a new object name
6107 //=============================================================================
6108 void SMESH_Gen_i::SetName(const char* theIOR,
6109 const char* theName)
6111 if ( theIOR && strcmp( theIOR, "" ) ) {
6112 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6113 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6114 if ( !aSO->_is_nil() ) {
6115 SetName( aSO, theName );
6120 // Version information
6121 char* SMESH_Gen_i::getVersion()
6123 #if SMESH_DEVELOPMENT
6124 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6126 return CORBA::string_dup(SMESH_VERSION_STR);
6130 //=================================================================================
6131 // function : Move()
6132 // purpose : Moves objects to the specified position.
6133 // Is used in the drag-n-drop functionality.
6134 //=================================================================================
6135 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6136 SALOMEDS::SObject_ptr where,
6139 if ( CORBA::is_nil( where ) ) return;
6141 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6142 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6143 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6144 std::string dataType = father->ComponentDataType();
6145 if ( dataType != "SMESH" ) return; // not a SMESH component
6147 SALOMEDS::SObject_var objAfter;
6148 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6149 // insert at given row -> find insertion position
6150 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6152 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6153 if ( i == row && useCaseIt->More() ) {
6154 objAfter = useCaseIt->Value();
6158 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6159 SALOMEDS::SObject_var sobj = what[i];
6160 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6161 // insert the object to the use case tree
6162 if ( !CORBA::is_nil( objAfter ) )
6163 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6165 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6168 //================================================================================
6170 * \brief Returns true if algorithm can be used to mesh a given geometry
6171 * \param [in] theAlgoType - the algorithm type
6172 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6173 * \param [in] theGeomObject - the geometry to mesh
6174 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6175 * else, returns \c True if at least one shape is meshable
6176 * \return CORBA::Boolean - can or can't
6178 //================================================================================
6180 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6181 const char* theLibName,
6182 GEOM::GEOM_Object_ptr theGeomObject,
6183 CORBA::Boolean toCheckAll)
6187 std::string aPlatformLibName;
6188 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6189 GenericHypothesisCreator_i* aCreator =
6190 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6193 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6194 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6195 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6202 SMESH_CATCH( SMESH::doNothing );
6205 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6210 //=================================================================================
6211 // function : GetInsideSphere
6212 // purpose : Collect indices of elements, which are located inside the sphere
6213 //=================================================================================
6214 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6215 SMESH::ElementType theElemType,
6221 SMESH::long_array_var aResult = new SMESH::long_array();
6222 if ( meshPart->_is_nil() )
6223 return aResult._retn();
6225 // 1. Create geometrical object
6226 gp_Pnt aP( theX, theY, theZ );
6227 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6229 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6231 if ( lst.size() > 0 ) {
6232 aResult->length( lst.size() );
6233 for ( size_t i = 0; i < lst.size(); i++ ) {
6234 aResult[i] = lst[i];
6237 return aResult._retn();
6240 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6241 SMESH::ElementType theElemType,
6242 CORBA::Double theX1,
6243 CORBA::Double theY1,
6244 CORBA::Double theZ1,
6245 CORBA::Double theX2,
6246 CORBA::Double theY2,
6247 CORBA::Double theZ2) {
6248 SMESH::long_array_var aResult = new SMESH::long_array();
6249 if( meshPart->_is_nil() )
6250 return aResult._retn();
6252 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6254 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6256 if( lst.size() > 0 ) {
6257 aResult->length( lst.size() );
6258 for ( size_t i = 0; i < lst.size(); i++ ) {
6259 aResult[i] = lst[i];
6262 return aResult._retn();
6265 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6266 SMESH::ElementType theElemType,
6270 CORBA::Double theDX,
6271 CORBA::Double theDY,
6272 CORBA::Double theDZ,
6274 CORBA::Double theR ){
6275 SMESH::long_array_var aResult = new SMESH::long_array();
6276 if( meshPart->_is_nil() )
6277 return aResult._retn();
6279 gp_Pnt aP( theX, theY, theZ );
6280 gp_Vec aV( theDX, theDY, theDZ );
6281 gp_Ax2 anAxes (aP, aV);
6283 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6285 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6287 if( lst.size() > 0 ) {
6288 aResult->length( lst.size() );
6289 for ( size_t i = 0; i < lst.size(); i++ ) {
6290 aResult[i] = lst[i];
6293 return aResult._retn();
6296 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6297 SMESH::ElementType theElemType,
6298 GEOM::GEOM_Object_ptr theGeom,
6299 CORBA::Double theTolerance ) {
6300 SMESH::long_array_var aResult = new SMESH::long_array();
6301 if( meshPart->_is_nil() || theGeom->_is_nil() )
6302 return aResult._retn();
6304 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6306 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6308 if( lst.size() > 0 ) {
6309 aResult->length( lst.size() );
6310 for ( size_t i = 0; i < lst.size(); i++ ) {
6311 aResult[i] = lst[i];
6314 return aResult._retn();
6319 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6320 SMESH::ElementType theElemType,
6321 TopoDS_Shape& aShape,
6322 double* theTolerance) {
6324 std::vector<long> res;
6325 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6327 if ( mesh->_is_nil() )
6330 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6334 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6339 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6340 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6341 anElementsOnShape->SetAllNodes( true );
6342 anElementsOnShape->SetMesh( meshDS );
6343 anElementsOnShape->SetShape( aShape, aType );
6346 anElementsOnShape->SetTolerance(*theTolerance);
6348 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6349 if ( !msource->_is_nil() ) { // Mesh case
6350 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6352 while ( elemIt->more() ) {
6353 const SMDS_MeshElement* anElem = elemIt->next();
6354 long anId = anElem->GetID();
6355 if ( anElementsOnShape->IsSatisfy( anId ) )
6356 res.push_back( anId );
6360 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6361 if ( !gsource->_is_nil() ) {
6362 if(theElemType == SMESH::NODE) {
6363 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6364 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6365 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6366 long anId = node->GetID();
6367 if ( anElementsOnShape->IsSatisfy( anId ) )
6368 res.push_back( anId );
6371 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6372 SMESH::long_array_var elems = gsource->GetListOfID();
6373 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6374 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6375 long anId = elem->GetID();
6376 if ( anElementsOnShape->IsSatisfy( anId ) )
6377 res.push_back( anId );
6382 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6383 if ( !smsource->_is_nil() ) {
6384 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6385 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6386 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6388 long anId = elem->GetID();
6389 if ( anElementsOnShape->IsSatisfy( anId ) )
6390 res.push_back( anId );
6398 //=============================================================================
6400 * SMESHEngine_factory
6402 * C factory, accessible with dlsym, after dlopen
6404 //=============================================================================
6408 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6409 PortableServer::POA_ptr poa,
6410 PortableServer::ObjectId* contId,
6411 const char* instanceName,
6412 const char* interfaceName )
6414 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6415 if(MYDEBUG) SCRUTE(interfaceName);
6416 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6417 return aSMESHGen->getId() ;