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 increment 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 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2617 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2619 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2620 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2621 while ( elemIt->more() )
2623 const SMDS_MeshElement* elem = elemIt->next();
2624 elemType.myNodes.resize( elem->NbNodes() );
2626 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2627 for ( int k = 0; itNodes->more(); k++)
2629 const SMDS_MeshNode* node = itNodes->next();
2630 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2633 // creates a corresponding element on existent nodes in new mesh
2634 newElems[ elem->GetID() ] =
2635 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2637 newEditor.ClearLastCreated(); // forget the history
2640 // create groups of just added elements
2641 SMESH::SMESH_Group_var newGroup;
2642 SMESH::ElementType groupType;
2643 if ( theCommonGroups )
2646 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2647 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2648 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2649 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2652 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2654 for( groupType = SMESH::NODE;
2655 groupType < SMESH::NB_ELEMENT_TYPES;
2656 groupType = (SMESH::ElementType)( groupType + 1 ))
2658 if ( curState[ groupType ] <= prevState[ groupType ])
2659 continue; // no elements of groupType added from the i-th mesh
2661 // make a group name
2662 std::string groupName = "Gr";
2663 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2665 CORBA::String_var name = meshSO->GetName();
2669 groupName += typeNames[ groupType ];
2671 // make and fill a group
2672 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2673 std::vector< const SMDS_MeshElement* > & elemVec =
2674 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2675 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2677 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2679 for ( size_t j = 0; j < elemVec.size(); ++j )
2681 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2682 grpDS->Add( elemVec[j] );
2686 listOfNewGroups.clear();
2687 listOfNewGroups.push_back( newGroup );
2688 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2693 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2697 SMESH::SMESH_GroupBase_ptr group;
2698 CORBA::String_var groupName;
2699 SMESH::long_array_var newIDs = new SMESH::long_array();
2701 // loop on groups of a source mesh
2702 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2703 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2705 group = listOfGroups[iG];
2706 groupType = group->GetType();
2707 groupName = group->GetName();
2708 std::string name = groupName.in();
2710 // convert a list of IDs
2711 newIDs->length( group->Size() );
2712 std::vector< const SMDS_MeshElement* > & elemVec =
2713 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2714 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2716 while ( itGrElems->more() )
2718 const SMDS_MeshElement* elem = itGrElems->next();
2719 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2721 newIDs[ nbElems++ ] = newElem->GetID();
2723 newIDs->length( nbElems );
2725 // check that a current group name and type don't have identical ones in final mesh
2726 listOfNewGroups.clear();
2727 TNameAndType nameAndType( name, groupType );
2728 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2729 if ( anIter == groupsMap.end() )
2731 // add a new group in the mesh
2732 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2733 newGroup->Add( newIDs );
2735 listOfNewGroups.push_back( newGroup );
2736 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2738 else if ( theUniteIdenticalGroups )
2740 // unite identical groups
2741 TListOfNewGroups& aNewGroups = anIter->second;
2742 aNewGroups.front()->Add( newIDs );
2746 // rename identical groups
2747 newGroup = newImpl->CreateGroup( groupType, groupName );
2748 newGroup->Add( newIDs );
2750 TListOfNewGroups& newGroups = anIter->second;
2751 std::string newGroupName;
2752 if ( newGroups.size() == 1 )
2754 newGroupName = name + "_1";
2755 newGroups.front()->SetName( newGroupName.c_str() );
2757 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2758 newGroup->SetName( newGroupName.c_str() );
2759 newGroups.push_back( newGroup );
2762 } // if an IDSource is a mesh
2765 if ( theMergeNodesAndElements ) // merge nodes
2767 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2768 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2769 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2770 /*SeparateCornersAndMedium=*/ false );
2771 newEditor.MergeNodes( groupsOfNodes );
2773 newEditor.MergeEqualElements();
2776 // Update Python script
2777 pythonDump << newMesh << " = " << this
2778 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2779 << theMeshesArray << ", "
2780 << theUniteIdenticalGroups << ", "
2781 << theMergeNodesAndElements << ", "
2782 << TVar( theMergeTolerance ) << ", "
2783 << theMeshToAppendTo << " )";
2785 pPythonDump.reset(); // enable python dump from GetGroups()
2787 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2788 if ( !newMesh->_is_nil() )
2790 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2793 // IPAL21468 Change icon of compound because it need not be computed.
2794 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2795 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2797 newMeshDS->Modified();
2799 return newMesh._retn();
2802 //================================================================================
2804 * \brief Create a mesh by copying a part of another mesh
2805 * \param meshPart - a part of mesh to copy
2806 * \param toCopyGroups - to create in the new mesh groups
2807 * the copied elements belongs to
2808 * \param toKeepIDs - to preserve IDs of the copied elements or not
2809 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2811 //================================================================================
2813 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2814 const char* meshName,
2815 CORBA::Boolean toCopyGroups,
2816 CORBA::Boolean toKeepIDs)
2817 throw ( SALOME::SALOME_Exception )
2819 Unexpect aCatch(SALOME_SalomeException);
2821 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2822 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2824 // 1. Get source mesh
2826 if ( CORBA::is_nil( meshPart ))
2827 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2829 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2830 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2832 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2834 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2836 // 2. Make a new mesh
2838 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2839 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2841 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2842 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2843 if ( !meshSO->_is_nil() )
2845 SetName( meshSO, meshName, "Mesh" );
2846 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2848 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2849 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2850 ::SMESH_MeshEditor::ElemFeatures elemType;
2852 // 3. Get elements to copy
2854 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2855 TIDSortedElemSet srcElems;
2856 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2857 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2860 srcElemIt = srcMeshDS->elementsIterator();
2861 srcNodeIt = srcMeshDS->nodesIterator();
2865 SMESH::long_array_var ids = meshPart->GetIDs();
2866 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2868 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2869 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2870 srcElems.insert( elem );
2874 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2875 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2876 srcElems.insert( elem );
2878 if ( srcElems.empty() )
2879 return newMesh._retn();
2881 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2882 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2887 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2888 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2889 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2891 const SMDS_MeshNode *nSrc, *nTgt;
2892 vector< const SMDS_MeshNode* > nodes;
2893 while ( srcElemIt->more() )
2895 const SMDS_MeshElement * elem = srcElemIt->next();
2897 nodes.resize( elem->NbNodes());
2898 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2900 for ( iN = 0; nIt->more(); ++iN )
2902 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2903 nTgt = newMeshDS->FindNode( nSrc->GetID());
2905 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2910 for ( iN = 0; nIt->more(); ++iN )
2912 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2913 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2915 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2916 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2920 if ( elem->GetType() != SMDSAbs_Node )
2922 elemType.Init( elem, /*basicOnly=*/false );
2923 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2925 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2926 if ( toCopyGroups && !toKeepIDs )
2927 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2929 } // while ( srcElemIt->more() )
2931 // 4(b). Copy free nodes
2933 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2935 while ( srcNodeIt->more() )
2937 nSrc = srcNodeIt->next();
2938 if ( nSrc->NbInverseElements() == 0 )
2941 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2943 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2950 int nbNewGroups = 0;
2953 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2954 while ( gIt->more() )
2956 SMESH_Group* group = gIt->next();
2957 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2959 // Check group type. We copy nodal groups containing nodes of copied element
2960 SMDSAbs_ElementType groupType = groupDS->GetType();
2961 if ( groupType != SMDSAbs_Node &&
2962 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2963 continue; // group type differs from types of meshPart
2965 // Find copied elements in the group
2966 vector< const SMDS_MeshElement* > groupElems;
2967 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2970 const SMDS_MeshElement* foundElem;
2971 if ( groupType == SMDSAbs_Node )
2973 while ( eIt->more() )
2974 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2975 groupElems.push_back( foundElem );
2979 while ( eIt->more() )
2980 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2981 groupElems.push_back( foundElem );
2986 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2987 if ( e2eMap.empty() ) continue;
2988 int minID = e2eMap.begin()->first->GetID();
2989 int maxID = e2eMap.rbegin()->first->GetID();
2990 TE2EMap::iterator e2e;
2991 while ( eIt->more() && groupElems.size() < e2eMap.size())
2993 const SMDS_MeshElement* e = eIt->next();
2994 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2995 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2996 groupElems.push_back( e2e->second );
3000 if ( !groupElems.empty() )
3002 SMESH::SMESH_Group_var newGroupObj =
3003 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3004 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3006 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3007 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3008 for ( unsigned i = 0; i < groupElems.size(); ++i )
3009 smdsGroup.Add( groupElems[i] );
3017 newMeshDS->Modified();
3019 *pyDump << newMesh << " = " << this
3020 << ".CopyMesh( " << meshPart << ", "
3021 << "'" << meshName << "', "
3022 << toCopyGroups << ", "
3023 << toKeepIDs << ")";
3025 pyDumpDeleter.reset(); // allow dump in GetGroups()
3027 if ( nbNewGroups > 0 ) // dump created groups
3028 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3030 return newMesh._retn();
3034 namespace // utils for CopyMeshWithGeom()
3036 typedef std::map< std::string, std::string > TStr2StrMap;
3037 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3038 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3039 typedef std::map< std::string, int > TName2IndexMap;
3041 //================================================================================
3043 * \brief Return a new sub-shape corresponding to an old one
3045 //================================================================================
3049 SMESH_Mesh_i* mySrcMesh_i;
3050 SMESH_Mesh_i* myNewMesh_i;
3051 SMESH_Gen_i* myGen_i;
3055 TStr2StrMap myOld2NewEntryMap; // map of study entries
3057 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3058 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3059 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3062 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3064 // not directly relating to shape search
3065 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3067 //================================================================================
3069 * \brief Constructor
3071 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3072 SMESH_Mesh_i* newMesh_i,
3073 SMESH_Gen_i* smeshGen_i )
3074 : mySrcMesh_i( srcMesh_i ),
3075 myNewMesh_i( newMesh_i ),
3076 myGen_i ( smeshGen_i ),
3077 myToPublish( smeshGen_i->IsEnablePublish() ),
3078 myGIPMapDone( false )
3080 // retrieve from the study shape mapping made thanks to
3081 // "Set presentation parameters and sub-shapes from arguments" option
3083 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3084 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3085 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3086 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3087 if ( newSO->_is_nil() )
3089 myToPublish = false;
3092 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3094 CORBA::String_var oldEntry = oldSO->GetID();
3095 CORBA::String_var newEntry = newSO->GetID();
3096 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3097 std::string( newEntry.in() )));
3098 std::string newMainEntry = newEntry.in();
3100 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3101 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3102 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3103 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3104 /*groupsOnly=*/false );
3105 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3107 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3108 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3109 bool refFound = false;
3110 for ( ; anIter->More(); anIter->Next() )
3112 SALOMEDS::SObject_wrap so = anIter->Value();
3113 if ( so->ReferencedObject( oldSO.inout() ))
3115 oldEntry = oldSO->GetID();
3116 newEntry = newSO->GetID();
3117 if (( refFound = ( newMainEntry != oldEntry.in() )))
3118 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3119 std::string( newEntry.in() )));
3124 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3125 if ( father->_is_equivalent( mainShapeNew ))
3127 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3128 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3129 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3130 CORBA::String_var name = newSO->GetName();
3132 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3138 //================================================================================
3140 * \brief Find a new sub-shape corresponding to an old one
3142 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3145 return GEOM::GEOM_Object::_duplicate( oldShape );
3147 GEOM::GEOM_Object_var newShape;
3149 if ( CORBA::is_nil( oldShape ))
3150 return newShape._retn();
3152 if ( !isChildOfOld( oldShape ))
3153 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3155 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3156 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3158 // try to find by entry or name
3161 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3162 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3163 if ( o2nID != myOld2NewEntryMap.end() )
3165 newShape = getShapeByEntry( o2nID->second );
3167 if ( newShape->_is_nil() )
3169 CORBA::String_var name = oldShape->GetName();
3170 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3171 if ( n2ind != myName2SubshapeIndex.end() )
3173 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3174 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3175 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3176 if ( oldIndices->length() == 0 ||
3177 newIndices->length() == 0 ||
3178 getShapeType( myNewMesh_i, newIndices[0] ) !=
3179 getShapeType( mySrcMesh_i, oldIndices[0] ))
3180 newShape = GEOM::GEOM_Object::_nil();
3185 if ( newShape->_is_nil() )
3187 // try to construct a new sub-shape using myGIPMap
3189 std::vector< int > newIndices;
3190 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3191 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3193 findNewIDs( oldIndices[i], newIndices );
3195 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3198 newShape = getInPlace( oldShape );
3200 if ( !newIndices.empty() && newShape->_is_nil() )
3202 // search for a sub-shape with same ids
3203 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3204 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3205 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3206 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3208 if ( newShape->_is_nil() )
3211 // create a new shape
3212 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3214 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3216 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3217 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3219 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3220 newIndicesList->length( newIndices.size() );
3221 for ( size_t i = 0; i < newIndices.size(); ++i )
3222 newIndicesList[ i ] = newIndices[ i ];
3223 grOp->UnionIDs( newShape, newIndicesList );
3227 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3228 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3237 if ( !newShape->_is_nil() && myToPublish )
3239 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3240 if ( !newEntry.in() || !newEntry.in()[0] )
3242 CORBA::String_var name = oldShape->GetName();
3243 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3244 newEntry = newShape->GetStudyEntry();
3245 oldEntry = oldShape->GetStudyEntry();
3246 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3247 std::string( newEntry.in() )));
3251 return newShape._retn();
3254 //================================================================================
3256 * \brief Return a study entry of a new shape by study entry of the old one
3258 std::string FindNew( const std::string & oldEntry )
3263 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3264 if ( o2nID != myOld2NewEntryMap.end() )
3265 return o2nID->second;
3267 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3268 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3271 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3272 if ( newShape->_is_nil() )
3273 return std::string();
3275 CORBA::String_var newEntry = newShape->GetStudyEntry();
3276 return newEntry.in();
3279 //================================================================================
3281 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3282 * Return zero if not found or there are more than one new ID
3284 int FindNew( int oldID )
3293 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3295 if ( myGIPMap[ oldID ].length() == 1 )
3297 newID = myGIPMap[ oldID ][ 0 ];
3299 else if ( myGIPMap[ oldID ].length() > 1 &&
3300 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3302 // select a meshed VERTEX
3303 SMESH_subMesh* newSM;
3304 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3305 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3306 ( !newSM->IsEmpty() ))
3307 newID = myGIPMap[ oldID ][ i ];
3313 //================================================================================
3315 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3316 * Return zero if the old shape is not kept as is in the new shape.
3318 int FindNewNotChanged( SMESH_subMesh* oldSM )
3321 return oldSM->GetId();
3323 int newID = FindNew( oldSM->GetId() );
3327 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3331 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3332 // one new sub-shape of the same type.
3334 if ( oldSM->DependsOn().size() !=
3335 newSM->DependsOn().size() )
3338 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3339 while ( srcSMIt->more() )
3341 oldSM = srcSMIt->next();
3342 int newSubID = FindNew( oldSM->GetId() );
3343 if ( getShapeType( myNewMesh_i, newSubID ) !=
3344 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3350 //================================================================================
3352 * \brief Return shape by study entry
3354 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3356 GEOM::GEOM_Object_var shape;
3357 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3358 if ( !so->_is_nil() )
3360 CORBA::Object_var obj = so->GetObject();
3361 shape = GEOM::GEOM_Object::_narrow( obj );
3363 return shape._retn();
3366 //================================================================================
3368 * \brief Fill myGIPMap by calling GetInPlaceMap()
3372 if ( !myGIPMapDone )
3374 myGIPMapDone = true;
3376 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3377 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3378 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3379 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3382 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3386 myGIPMap = new GEOM::ListOfListOfLong();
3391 //================================================================================
3393 * \brief Get new sub-shape by calling GetInPlace()
3395 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3397 GEOM::GEOM_Object_var newShape;
3399 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3400 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3401 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3404 newShape = op->GetInPlace( mainShapeNew, oldShape );
3409 return newShape._retn();
3412 //================================================================================
3414 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3415 * number of found IDs
3417 int findNewIDs( int oldID, std::vector< int >& newIDs )
3419 size_t prevNbIDs = newIDs.size();
3421 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3423 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3424 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3426 return newIDs.size() - prevNbIDs;
3429 //================================================================================
3431 * \brief Check if an object relates to the old shape
3433 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3435 if ( CORBA::is_nil( oldShape ))
3437 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3438 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3439 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3440 mainShapeOld1->_is_equivalent( oldShape ));
3443 //================================================================================
3445 * \brief Return shape type by shape ID
3447 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3449 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3450 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3451 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3454 //================================================================================
3456 * \brief Store a source sub-shape for which a counterpart not found and
3457 * a smesh object invalid due to that
3459 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3460 SALOMEDS::SObject_wrap smeshSO )
3462 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3463 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3465 CORBA::String_var smeshEntry = smeshSO->GetID();
3466 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3470 //================================================================================
3472 * \brief Store a source sub-shape for which a counterpart not found and
3473 * a smesh object invalid due to that
3475 void AddInvalid( std::string geomEntry,
3476 SALOMEDS::SObject_wrap smeshSO )
3478 if ( !geomEntry.empty() )
3480 CORBA::String_var smeshEntry = smeshSO->GetID();
3481 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3485 //================================================================================
3487 * \brief Store a source sub-shape for which a counterpart not found and
3488 * a smesh object invalid due to that
3490 void AddInvalid( int oldGeomID,
3491 SALOMEDS::SObject_wrap smeshSO )
3493 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3494 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3497 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3498 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3500 SMESH_Comment geomName( typeName[ shapeType ]);
3501 geomName << " #" << oldGeomID;
3503 CORBA::String_var smeshEntry = smeshSO->GetID();
3504 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3507 //================================================================================
3509 * \brief Return entries of a source sub-shape for which a counterpart not found and
3510 * of smesh objects invalid due to that
3512 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3513 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3516 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3517 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3519 nbSO += 1 + entry2entrySet->second.size();
3521 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3522 theInvalidEntries->length ( nbSO );
3523 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3525 entry2entrySet = myInvalidMap.begin();
3526 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3528 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3530 std::set< std::string > & entrySet = entry2entrySet->second;
3531 std::set< std::string >::iterator entry = entrySet.begin();
3532 for ( ; entry != entrySet.end(); ++entry )
3534 theInvalidEntries[ iEntry++ ] = entry->c_str();
3536 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3537 if ( !so->_is_nil() )
3538 theInvalidMeshSObjects[ iSO++ ] = so;
3543 }; // struct ShapeMapper
3545 //================================================================================
3547 * \brief Append an item to a CORBA sequence
3549 template < class CORBA_seq, class ITEM >
3550 void append( CORBA_seq& seq, ITEM item )
3552 if ( !CORBA::is_nil( item ))
3554 seq->length( 1 + seq->length() );
3555 seq[ seq->length() - 1 ] = item;
3558 } // namespace // utils for CopyMeshWithGeom()
3560 //================================================================================
3562 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3563 * \param [in] sourceMesh - a mesh to copy
3564 * \param [in] newGeometry - a new geometry
3565 * \param [in] toCopyGroups - to create groups in the new mesh
3566 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3567 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3568 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3569 * \param [out] newMesh - return a new mesh
3570 * \param [out] newGroups - return new groups
3571 * \param [out] newSubmeshes - return new sub-meshes
3572 * \param [out] newHypotheses - return new algorithms and hypotheses
3573 * \param [out] invalidEntries - return study entries of objects whose
3574 * counterparts are not found in the newGeometry, followed by entries
3575 * of mesh sub-objects that are invalid because they depend on a not found
3576 * preceding sub-shape
3577 * \return CORBA::Boolean - is a success
3579 //================================================================================
3581 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3582 GEOM::GEOM_Object_ptr theNewGeometry,
3583 const char* theMeshName,
3584 CORBA::Boolean theToCopyGroups,
3585 CORBA::Boolean theToReuseHypotheses,
3586 CORBA::Boolean theToCopyElements,
3587 SMESH::SMESH_Mesh_out theNewMesh,
3588 SMESH::ListOfGroups_out theNewGroups,
3589 SMESH::submesh_array_out theNewSubmeshes,
3590 SMESH::ListOfHypothesis_out theNewHypotheses,
3591 SMESH::string_array_out theInvalidEntries)
3592 throw ( SALOME::SALOME_Exception )
3594 if ( CORBA::is_nil( theSourceMesh ) ||
3595 CORBA::is_nil( theNewGeometry ))
3596 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3598 if ( !theSourceMesh->HasShapeToMesh() )
3599 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3604 TPythonDump pyDump; // prevent dump from CreateMesh()
3606 theNewMesh = CreateMesh( theNewGeometry );
3607 theNewGroups = new SMESH::ListOfGroups();
3608 theNewSubmeshes = new SMESH::submesh_array();
3609 theNewHypotheses = new SMESH::ListOfHypothesis();
3610 theInvalidEntries = new SMESH::string_array();
3612 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3614 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3615 GEOM::GEOM_Object_var geom, newGeom;
3616 SALOMEDS::SObject_wrap so;
3618 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3619 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3622 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3624 // treat hypotheses of mesh and sub-meshes
3625 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3626 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3628 bool isSubMesh = ( iSM < smList->length() );
3631 // create a new sub-mesh
3632 SMESH::SMESH_subMesh_var newSM;
3633 geom = smList[iSM]->GetSubShape();
3634 so = ObjectToSObject( smList[iSM] );
3635 CORBA::String_var name;
3636 if ( !so->_is_nil() )
3637 name = so->GetName();
3638 newGeom = shapeMapper.FindNew( geom );
3639 if ( newGeom->_is_nil() )
3641 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3642 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3647 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3649 append( theNewSubmeshes, newSM );
3651 if ( newGeom->_is_nil() )
3652 continue; // don't assign hypotheses
3656 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3658 so = ObjectToSObject( theNewMesh );
3659 SetName( so, theMeshName, "Mesh" );
3662 // assign hypotheses
3663 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3664 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3666 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3667 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3669 // get geometry hyp depends on
3670 std::vector< std::string > entryArray;
3671 std::vector< int > subIDArray;
3672 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3674 if ( !theToReuseHypotheses || dependsOnGeom )
3676 // create a new hypothesis
3677 CORBA::String_var type = hyp->GetName();
3678 CORBA::String_var lib = hyp->GetLibName();
3679 CORBA::String_var data = hyp_i->SaveTo();
3682 hyp = CreateHypothesis( type, lib );
3683 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3684 hyp_i->LoadFrom( data.in() );
3685 append( theNewHypotheses, hyp );
3689 // update geometry hyp depends on
3690 if ( dependsOnGeom )
3692 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3694 if ( !entryArray[ iGeo ].empty() )
3696 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3697 if ( newEntry.empty() )
3700 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3701 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3703 entryArray[ iGeo ] = newEntry;
3706 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3708 if ( subIDArray[ iGeo ] > 0 )
3710 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3714 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3715 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3717 subIDArray[ iGeo ] = newID;
3720 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3724 CORBA::String_var errorText;
3725 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3726 if ( errorText.in()[0] )
3729 } // loop on hypotheses
3730 } // loop on sub-meshes and mesh
3733 // copy mesh elements, keeping IDs
3734 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3735 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3737 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3738 ::SMESH_MeshEditor::ElemFeatures elemData;
3740 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3741 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3742 /*vertexLast=*/false);
3743 while ( srcSMIt->more() )
3745 SMESH_subMesh* srcSM = srcSMIt->next();
3746 if ( srcSM->IsEmpty() )
3747 continue; // not yet computed
3748 int newID = shapeMapper.FindNewNotChanged( srcSM );
3752 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3753 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3754 while ( nIt->more() )
3756 SMESH_NodeXYZ node( nIt->next() );
3757 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3759 const SMDS_PositionPtr pos = node->GetPosition();
3760 const double* uv = pos->GetParameters();
3761 switch ( pos->GetTypeOfPosition() )
3763 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3764 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3765 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3766 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3770 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3771 while( eIt->more() )
3773 const SMDS_MeshElement* e = eIt->next();
3774 elemData.Init( e, /*basicOnly=*/false );
3775 elemData.SetID( e->GetID() );
3776 elemData.myNodes.resize( e->NbNodes() );
3777 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3779 for ( iN = 0; nnIt->more(); ++iN )
3781 const SMDS_MeshNode* srcNode = nnIt->next();
3782 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3783 if ( !elemData.myNodes[ iN ])
3786 if ( iN == elemData.myNodes.size() )
3787 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3788 newMeshDS->SetMeshElementOnShape( newElem, newID );
3790 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3791 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3794 newMeshDS->Modified();
3800 TStr2StrMap old2newGroupMap;
3802 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3804 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3805 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3806 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3808 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3809 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3810 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3812 CORBA::String_var name = groups[ i ]->GetName();
3813 SMESH::ElementType elemType = groups[ i ]->GetType();
3815 SMESH::SMESH_GroupBase_var newGroup;
3817 if ( !stdlGroup->_is_nil() )
3819 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3821 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3822 const bool isElem = ( elemType != SMESH::NODE );
3823 CORBA::ULong iE = 0;
3824 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3825 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3827 if ( iE < elemIDs->length() )
3829 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3830 stdlGroup->Add( elemIDs );
3831 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3835 else if ( !geomGroup->_is_nil() )
3837 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3838 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3839 if ( newGeom->_is_nil() )
3841 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3842 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3847 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3850 else if ( !fltrGroup->_is_nil() )
3852 // replace geometry in a filter
3853 SMESH::Filter_var filter = fltrGroup->GetFilter();
3854 SMESH::Filter::Criteria_var criteria;
3855 filter->GetCriteria( criteria.out() );
3857 bool isMissingGroup = false;
3858 std::vector< std::string > badEntries;
3860 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3862 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3863 switch ( criteria[ iCr ].Type )
3865 case SMESH::FT_BelongToMeshGroup:
3867 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3868 btgg->SetGroupID( thresholdID );
3869 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3870 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3871 if ( refGroupSO->_is_nil() )
3873 CORBA::String_var refID = refGroupSO->GetID();
3874 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3875 if ( o2nID == old2newGroupMap.end() )
3877 isMissingGroup = true; // corresponding new group not yet created
3880 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3882 if ( o2nID->second.empty() ) // new referred group is invalid
3883 badEntries.push_back( refID.in() );
3886 case SMESH::FT_BelongToGeom:
3887 case SMESH::FT_BelongToPlane:
3888 case SMESH::FT_BelongToCylinder:
3889 case SMESH::FT_BelongToGenSurface:
3890 case SMESH::FT_LyingOnGeom:
3892 std::string newID = shapeMapper.FindNew( thresholdID );
3893 criteria[ iCr ].ThresholdID = newID.c_str();
3894 if ( newID.empty() )
3895 badEntries.push_back( thresholdID );
3898 case SMESH::FT_ConnectedElements:
3900 if ( thresholdID && thresholdID[0] )
3902 std::string newID = shapeMapper.FindNew( thresholdID );
3903 criteria[ iCr ].ThresholdID = newID.c_str();
3904 if ( newID.empty() )
3905 badEntries.push_back( thresholdID );
3911 } // loop on criteria
3913 if ( isMissingGroup && i < nbGroups )
3915 // to treat the group again
3916 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3920 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3921 newFilter->SetCriteria( criteria );
3923 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3924 newFilter->UnRegister();
3926 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3927 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3928 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3930 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3932 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3935 if ( !badEntries.empty() )
3938 } // treat a group on filter
3940 append( theNewGroups, newGroup );
3942 // fill old2newGroupMap
3943 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3944 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3945 if ( !srcSO->_is_nil() )
3947 CORBA::String_var srcID, newID("");
3948 srcID = srcSO->GetID();
3949 if ( !newSO->_is_nil() )
3950 newID = newSO->GetID();
3951 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3952 std::string( newID.in() )));
3955 if ( newGroup->_is_nil() )
3960 newMeshDS->CompactMesh();
3963 if ( !theMeshName || !theMeshName[0] )
3965 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3966 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3967 CORBA::String_var oldName = soOld->GetName();
3968 SetName( soNew, oldName.in(), "Mesh" );
3970 // mark invalid objects
3971 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3973 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3974 highLightInvalid( invalidSObjects[i].in(), true );
3977 << theNewMesh << ", "
3978 << theNewGroups << ", "
3979 << *theNewSubmeshes.ptr() << ", "
3980 << *theNewHypotheses.ptr() << ", "
3981 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3982 << theSourceMesh << ", "
3983 << theNewGeometry << ", "
3984 << "'" << theMeshName << "', "
3985 << theToCopyGroups << ", "
3986 << theToReuseHypotheses << ", "
3987 << theToCopyElements << " )";
3989 SMESH_CATCH( SMESH::throwCorbaException );
3994 //================================================================================
3996 * \brief Get version of MED format being used.
3998 //================================================================================
4000 char* SMESH_Gen_i::GetMEDFileVersion()
4002 MED::TInt majeur, mineur, release;
4003 majeur = mineur = release = 0;
4004 MED::GetVersionRelease(majeur, mineur, release);
4005 std::ostringstream version;
4006 version << majeur << "." << mineur << "." << release;
4007 return CORBA::string_dup( version.str().c_str() );
4010 //================================================================================
4012 * SMESH_Gen_i::GetMEDVersion
4014 * Get MED version of the file by its name
4016 //================================================================================
4017 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4019 std::string version = MED::GetMEDVersion( theFileName );
4020 return CORBA::string_dup( version.c_str() );
4023 //================================================================================
4025 * SMESH_Gen_i::CheckCompatibility
4027 * Check compatibility of file with MED format being used, read only.
4029 //================================================================================
4030 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4032 return MED::CheckCompatibility( theFileName );
4035 //================================================================================
4037 * SMESH_Gen_i::CheckWriteCompatibility
4039 * Check compatibility of file with MED format being used, for append on write.
4041 //================================================================================
4042 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4044 return MED::CheckCompatibility( theFileName, true );
4047 //================================================================================
4049 * SMESH_Gen_i::GetMeshNames
4051 * Get names of meshes defined in file with the specified name
4053 //================================================================================
4054 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4056 //MESSAGE("GetMeshNames " << theFileName);
4057 SMESH::string_array_var aResult = new SMESH::string_array();
4058 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4060 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4061 //MESSAGE("---" << aNbMeshes);
4063 aResult->length( aNbMeshes );
4064 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4065 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4066 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4069 return aResult._retn();
4072 //=============================================================================
4076 * Save SMESH module's data
4078 //=============================================================================
4079 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4084 Kernel_Utils::Localizer loc;
4086 if (!myStudyContext)
4089 // Store study contents as a set of python commands
4092 SALOMEDS::Study_var aStudy = getStudyServant();
4094 // Declare a byte stream
4095 SALOMEDS::TMPFile_var aStreamFile;
4097 // Obtain a temporary dir
4098 TCollection_AsciiString tmpDir =
4099 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4101 // Create a sequence of files processed
4102 SALOMEDS_Tool::ListOfFiles aFileSeq;
4103 aFileSeq.reserve( NUM_TMP_FILES );
4105 TCollection_AsciiString aStudyName( "" );
4107 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4109 // Set names of temporary files
4110 TCollection_AsciiString filename =
4111 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4112 TCollection_AsciiString meshfile =
4113 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4114 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4115 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4116 filename = tmpDir + filename;
4117 meshfile = tmpDir + meshfile;
4120 HDFdataset* aDataset;
4121 HDFgroup* aTopGroup;
4123 HDFgroup* aSubGroup;
4124 HDFgroup* aSubSubGroup;
4125 hdf_size aSize[ 1 ];
4128 //Remove the files if they exist: BugID: 11225
4129 #ifndef WIN32 /* unix functionality */
4130 TCollection_AsciiString cmd("rm -f \"");
4132 TCollection_AsciiString cmd("del /F \"");
4142 system(cmd.ToCString());
4144 // MED writer to be used by storage process
4145 DriverMED_W_SMESHDS_Mesh myWriter;
4146 myWriter.SetFile( meshfile.ToCString() );
4149 // SetStoreName() to groups before storing hypotheses to let them refer to
4150 // groups using "store name", which is "Group <group_persistent_id>"
4152 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4153 for ( ; itBig->More(); itBig->Next() ) {
4154 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4155 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4156 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4157 if ( !CORBA::is_nil( anObject ) ) {
4158 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4159 if ( !myMesh->_is_nil() ) {
4160 myMesh->Load(); // load from study file if not yet done
4161 TPythonDump pd; // not to dump GetGroups()
4162 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4163 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4165 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4168 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4169 int anId = myStudyContext->findId( string( objStr.in() ) );
4171 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4172 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4173 aGrpBaseDS->SetStoreName( grpName );
4183 // ---> create HDF file
4184 aFile = new HDFfile( (char*) filename.ToCString() );
4185 aFile->CreateOnDisk();
4187 // --> iterator for top-level objects
4188 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4189 for ( ; itBig->More(); itBig->Next() ) {
4190 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4192 // --> hypotheses root branch (only one for the study)
4193 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4194 // create hypotheses root HDF group
4195 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4196 aTopGroup->CreateOnDisk();
4198 // iterator for all hypotheses
4199 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4200 for ( ; it->More(); it->Next() ) {
4201 SALOMEDS::SObject_wrap mySObject = it->Value();
4202 CORBA::Object_var anObject = SObjectToObject( mySObject );
4203 if ( !CORBA::is_nil( anObject ) ) {
4204 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4205 if ( !myHyp->_is_nil() ) {
4206 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4208 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4209 std::string hypname = hn.in();
4210 std::string libname = ln.in();
4212 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4213 // WIN32 and ".so" for X-system) must be deleted
4214 int libname_len = libname.length();
4216 if( libname_len > 4 )
4217 libname.resize( libname_len - 4 );
4219 // PAL17753 (Regression: missing hypothesis in restored study)
4220 // "lib" also should be removed from the beginning
4221 //if( libname_len > 3 )
4222 //libname.resize( libname_len - 3 );
4223 if( libname_len > 6 )
4224 libname = libname.substr( 3, libname_len - 3 - 3 );
4226 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4227 CORBA::String_var hypdata = myImpl->SaveTo();
4228 int id = myStudyContext->findId( string( objStr.in() ));
4230 // for each hypothesis create HDF group basing on its id
4231 char hypGrpName[30];
4232 sprintf( hypGrpName, "Hypothesis %d", id );
4233 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4234 aGroup->CreateOnDisk();
4235 // --> type name of hypothesis
4236 aSize[ 0 ] = hypname.length() + 1;
4237 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4238 aDataset->CreateOnDisk();
4239 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4240 aDataset->CloseOnDisk();
4241 // --> server plugin library name of hypothesis
4242 aSize[ 0 ] = libname.length() + 1;
4243 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4244 aDataset->CreateOnDisk();
4245 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4246 aDataset->CloseOnDisk();
4247 // --> persistent data of hypothesis
4248 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4249 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4250 aDataset->CreateOnDisk();
4251 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4252 aDataset->CloseOnDisk();
4253 // close hypothesis HDF group
4254 aGroup->CloseOnDisk();
4259 // close hypotheses root HDF group
4260 aTopGroup->CloseOnDisk();
4262 // --> algorithms root branch (only one for the study)
4263 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4264 // create algorithms root HDF group
4265 aTopGroup = new HDFgroup( "Algorithms", aFile );
4266 aTopGroup->CreateOnDisk();
4268 // iterator for all algorithms
4269 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4270 for ( ; it->More(); it->Next() ) {
4271 SALOMEDS::SObject_wrap mySObject = it->Value();
4272 CORBA::Object_var anObject = SObjectToObject( mySObject );
4273 if ( !CORBA::is_nil( anObject ) ) {
4274 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4275 if ( !myHyp->_is_nil() ) {
4276 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4278 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4279 std::string hypname = hn.in();
4280 std::string libname = ln.in();
4282 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4283 // WIN32 and ".so" for X-system) must be deleted
4284 int libname_len = libname.length();
4286 if( libname_len > 4 )
4287 libname.resize( libname_len - 4 );
4289 // PAL17753 (Regression: missing hypothesis in restored study)
4290 // "lib" also should be removed from the beginning
4291 //if( libname_len > 3 )
4292 //libname.resize( libname_len - 3 );
4293 if( libname_len > 6 )
4294 libname = libname.substr( 3, libname_len - 3 - 3 );
4296 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4297 CORBA::String_var hypdata = myImpl->SaveTo();
4298 int id = myStudyContext->findId( string( objStr.in() ) );
4300 // for each algorithm create HDF group basing on its id
4301 char hypGrpName[30];
4302 sprintf( hypGrpName, "Algorithm %d", id );
4303 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4304 aGroup->CreateOnDisk();
4305 // --> type name of algorithm
4306 aSize[0] = hypname.length() + 1;
4307 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4308 aDataset->CreateOnDisk();
4309 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4310 aDataset->CloseOnDisk();
4311 // --> server plugin library name of hypothesis
4312 aSize[0] = libname.length() + 1;
4313 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4314 aDataset->CreateOnDisk();
4315 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4316 aDataset->CloseOnDisk();
4317 // --> persistent data of algorithm
4318 aSize[0] = strlen( hypdata.in() ) + 1;
4319 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4320 aDataset->CreateOnDisk();
4321 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4322 aDataset->CloseOnDisk();
4323 // close algorithm HDF group
4324 aGroup->CloseOnDisk();
4329 // close algorithms root HDF group
4330 aTopGroup->CloseOnDisk();
4332 // --> mesh objects roots branches
4333 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4334 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4335 if ( !CORBA::is_nil( anObject ) ) {
4336 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4337 if ( !myMesh->_is_nil() ) {
4338 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4340 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4341 int id = myStudyContext->findId( string( objStr.in() ) );
4342 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4343 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4344 bool hasShape = myLocMesh.HasShapeToMesh();
4346 // for each mesh open the HDF group basing on its id
4347 char meshGrpName[ 30 ];
4348 sprintf( meshGrpName, "Mesh %d", id );
4349 aTopGroup = new HDFgroup( meshGrpName, aFile );
4350 aTopGroup->CreateOnDisk();
4352 // --> put dataset to hdf file which is a flag that mesh has data
4353 string strHasData = "0";
4354 // check if the mesh is not empty
4355 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4356 // write mesh data to med file
4357 myWriter.SetMesh( mySMESHDSMesh );
4358 myWriter.SetMeshId( id );
4361 aSize[ 0 ] = strHasData.length() + 1;
4362 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4363 aDataset->CreateOnDisk();
4364 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4365 aDataset->CloseOnDisk();
4368 // for each mesh open the HDF group basing on its auto color parameter
4369 char meshAutoColorName[ 30 ];
4370 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4372 anAutoColor[0] = myImpl->GetAutoColor();
4374 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4375 aDataset->CreateOnDisk();
4376 aDataset->WriteOnDisk( anAutoColor );
4377 aDataset->CloseOnDisk();
4379 // issue 0020693. Store _isModified flag
4380 int isModified = myLocMesh.GetIsModified();
4382 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4383 aDataset->CreateOnDisk();
4384 aDataset->WriteOnDisk( &isModified );
4385 aDataset->CloseOnDisk();
4387 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4388 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4390 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4391 aDataset->CreateOnDisk();
4392 aDataset->WriteOnDisk( &meshPersistentId );
4393 aDataset->CloseOnDisk();
4395 // write reference on a shape if exists
4396 SALOMEDS::SObject_wrap myRef;
4397 bool shapeRefFound = false;
4398 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4400 SALOMEDS::SObject_wrap myShape;
4401 bool ok = myRef->ReferencedObject( myShape.inout() );
4403 CORBA::Object_var shapeObj = myShape->GetObject();
4404 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4405 CORBA::String_var myRefOnObject = myShape->GetID();
4406 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4407 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4408 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4409 aDataset->CreateOnDisk();
4410 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4411 aDataset->CloseOnDisk();
4417 std::string info = myImpl->FileInfoToString();
4418 if ( !info.empty() )
4420 aSize[ 0 ] = info.size();
4421 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4422 aDataset->CreateOnDisk();
4423 aDataset->WriteOnDisk( (char*) info.data() );
4424 aDataset->CloseOnDisk();
4427 // write applied hypotheses if exist
4428 SALOMEDS::SObject_wrap myHypBranch;
4429 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4430 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4431 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4433 if ( found && (shapeRefFound || !hasShape) ) {
4434 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4435 aGroup->CreateOnDisk();
4437 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4439 for ( ; it->More(); it->Next() ) {
4440 SALOMEDS::SObject_wrap mySObject = it->Value();
4441 SALOMEDS::SObject_wrap myRefOnHyp;
4442 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4444 // san - it is impossible to recover applied hypotheses
4445 // using their entries within Load() method,
4446 // for there are no AttributeIORs in the study when Load() is working.
4447 // Hence, it is better to store persistent IDs of hypotheses as references to them
4449 //string myRefOnObject = myRefOnHyp->GetID();
4450 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4451 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4452 int id = myStudyContext->findId( string( objStr.in() ) );
4453 //if ( myRefOnObject.length() > 0 ) {
4454 //aSize[ 0 ] = myRefOnObject.length() + 1;
4455 char hypName[ 30 ], hypId[ 30 ];
4456 sprintf( hypName, "Hyp %d", ++hypNb );
4457 sprintf( hypId, "%d", id );
4458 aSize[ 0 ] = strlen( hypId ) + 1;
4459 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4460 aDataset->CreateOnDisk();
4461 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4462 aDataset->WriteOnDisk( hypId );
4463 aDataset->CloseOnDisk();
4467 aGroup->CloseOnDisk();
4470 // write applied algorithms if exist
4471 SALOMEDS::SObject_wrap myAlgoBranch;
4472 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4473 myAlgoBranch.inout() );
4474 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4475 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4477 if ( found && (shapeRefFound || !hasShape)) {
4478 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4479 aGroup->CreateOnDisk();
4481 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4483 for ( ; it->More(); it->Next() ) {
4484 SALOMEDS::SObject_wrap mySObject = it->Value();
4485 SALOMEDS::SObject_wrap myRefOnAlgo;
4486 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4488 // san - it is impossible to recover applied algorithms
4489 // using their entries within Load() method,
4490 // for there are no AttributeIORs in the study when Load() is working.
4491 // Hence, it is better to store persistent IDs of algorithms as references to them
4493 //string myRefOnObject = myRefOnAlgo->GetID();
4494 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4495 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4496 int id = myStudyContext->findId( string( objStr.in() ) );
4497 //if ( myRefOnObject.length() > 0 ) {
4498 //aSize[ 0 ] = myRefOnObject.length() + 1;
4499 char algoName[ 30 ], algoId[ 30 ];
4500 sprintf( algoName, "Algo %d", ++algoNb );
4501 sprintf( algoId, "%d", id );
4502 aSize[ 0 ] = strlen( algoId ) + 1;
4503 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4504 aDataset->CreateOnDisk();
4505 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4506 aDataset->WriteOnDisk( algoId );
4507 aDataset->CloseOnDisk();
4511 aGroup->CloseOnDisk();
4514 // --> submesh objects sub-branches
4516 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4517 SALOMEDS::SObject_wrap mySubmeshBranch;
4518 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4520 if ( found ) // check if there is shape reference in submeshes
4522 bool hasShapeRef = false;
4523 SALOMEDS::ChildIterator_wrap itSM =
4524 aStudy->NewChildIterator( mySubmeshBranch );
4525 for ( ; itSM->More(); itSM->Next() ) {
4526 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4527 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4528 mySubRef->ReferencedObject( myShape.inout() );
4529 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4532 { // remove one submesh
4533 if ( shapeRefFound )
4534 { // unassign hypothesis
4535 SMESH::SMESH_subMesh_var mySubMesh =
4536 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4537 if ( !mySubMesh->_is_nil() ) {
4538 int shapeID = mySubMesh->GetId();
4539 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4540 const list<const SMESHDS_Hypothesis*>& hypList =
4541 mySMESHDSMesh->GetHypothesis( S );
4542 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4543 while ( hyp != hypList.end() ) {
4544 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4545 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4549 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4551 } // loop on submeshes of a type
4552 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4553 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4556 } // end check if there is shape reference in submeshes
4558 char name_meshgroup[ 30 ];
4559 if ( i == GetSubMeshOnVertexTag() )
4560 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4561 else if ( i == GetSubMeshOnEdgeTag() )
4562 strcpy( name_meshgroup, "SubMeshes On Edge" );
4563 else if ( i == GetSubMeshOnWireTag() )
4564 strcpy( name_meshgroup, "SubMeshes On Wire" );
4565 else if ( i == GetSubMeshOnFaceTag() )
4566 strcpy( name_meshgroup, "SubMeshes On Face" );
4567 else if ( i == GetSubMeshOnShellTag() )
4568 strcpy( name_meshgroup, "SubMeshes On Shell" );
4569 else if ( i == GetSubMeshOnSolidTag() )
4570 strcpy( name_meshgroup, "SubMeshes On Solid" );
4571 else if ( i == GetSubMeshOnCompoundTag() )
4572 strcpy( name_meshgroup, "SubMeshes On Compound" );
4574 // for each type of submeshes create container HDF group
4575 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4576 aGroup->CreateOnDisk();
4578 // iterator for all submeshes of given type
4579 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4580 for ( ; itSM->More(); itSM->Next() ) {
4581 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4582 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4583 if ( !CORBA::is_nil( anSubObject ))
4585 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4586 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4587 int subid = myStudyContext->findId( string( objStr.in() ) );
4589 // for each mesh open the HDF group basing on its id
4590 char submeshGrpName[ 30 ];
4591 sprintf( submeshGrpName, "SubMesh %d", subid );
4592 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4593 aSubGroup->CreateOnDisk();
4595 // write reference on a shape, already checked if it exists
4596 SALOMEDS::SObject_wrap mySubRef, myShape;
4597 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4598 mySubRef->ReferencedObject( myShape.inout() );
4599 string myRefOnObject = myShape->GetID();
4600 if ( myRefOnObject.length() > 0 ) {
4601 aSize[ 0 ] = myRefOnObject.length() + 1;
4602 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4603 aDataset->CreateOnDisk();
4604 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4605 aDataset->CloseOnDisk();
4608 // write applied hypotheses if exist
4609 SALOMEDS::SObject_wrap mySubHypBranch;
4610 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4611 mySubHypBranch.inout() );
4613 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4614 aSubSubGroup->CreateOnDisk();
4616 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4618 for ( ; it->More(); it->Next() ) {
4619 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4620 SALOMEDS::SObject_wrap myRefOnHyp;
4621 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4623 //string myRefOnObject = myRefOnHyp->GetID();
4624 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4625 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4626 int id = myStudyContext->findId( string( objStr.in() ) );
4627 //if ( myRefOnObject.length() > 0 ) {
4628 //aSize[ 0 ] = myRefOnObject.length() + 1;
4629 char hypName[ 30 ], hypId[ 30 ];
4630 sprintf( hypName, "Hyp %d", ++hypNb );
4631 sprintf( hypId, "%d", id );
4632 aSize[ 0 ] = strlen( hypId ) + 1;
4633 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4634 aDataset->CreateOnDisk();
4635 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4636 aDataset->WriteOnDisk( hypId );
4637 aDataset->CloseOnDisk();
4641 aSubSubGroup->CloseOnDisk();
4644 // write applied algorithms if exist
4645 SALOMEDS::SObject_wrap mySubAlgoBranch;
4646 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4647 mySubAlgoBranch.inout() );
4649 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4650 aSubSubGroup->CreateOnDisk();
4652 SALOMEDS::ChildIterator_wrap it =
4653 aStudy->NewChildIterator( mySubAlgoBranch );
4655 for ( ; it->More(); it->Next() ) {
4656 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4657 SALOMEDS::SObject_wrap myRefOnAlgo;
4658 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4660 //string myRefOnObject = myRefOnAlgo->GetID();
4661 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4662 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4663 int id = myStudyContext->findId( string( objStr.in() ) );
4664 //if ( myRefOnObject.length() > 0 ) {
4665 //aSize[ 0 ] = myRefOnObject.length() + 1;
4666 char algoName[ 30 ], algoId[ 30 ];
4667 sprintf( algoName, "Algo %d", ++algoNb );
4668 sprintf( algoId, "%d", id );
4669 aSize[ 0 ] = strlen( algoId ) + 1;
4670 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4671 aDataset->CreateOnDisk();
4672 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4673 aDataset->WriteOnDisk( algoId );
4674 aDataset->CloseOnDisk();
4678 aSubSubGroup->CloseOnDisk();
4680 // close submesh HDF group
4681 aSubGroup->CloseOnDisk();
4684 // close container of submeshes by type HDF group
4685 aGroup->CloseOnDisk();
4688 // All sub-meshes will be stored in MED file
4689 // .. will NOT (PAL 12992)
4690 //if ( shapeRefFound )
4691 //myWriter.AddAllSubMeshes();
4693 // store submesh order if any
4694 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4695 if ( theOrderIds.size() ) {
4696 char order_list[ 30 ];
4697 strcpy( order_list, "Mesh Order" );
4698 // count number of submesh ids
4700 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4701 for ( ; idIt != theOrderIds.end(); idIt++ )
4702 nbIDs += (*idIt).size();
4703 // number of values = number of IDs +
4704 // number of lists (for separators) - 1
4705 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4706 idIt = theOrderIds.begin();
4707 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4708 const TListOfInt& idList = *idIt;
4709 if (idIt != theOrderIds.begin()) // not first list
4710 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4711 // dump submesh ids from current list
4712 TListOfInt::const_iterator id_smId = idList.begin();
4713 for( ; id_smId != idList.end(); id_smId++ )
4714 smIDs[ i++ ] = *id_smId;
4717 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4719 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4720 aDataset->CreateOnDisk();
4721 aDataset->WriteOnDisk( smIDs );
4722 aDataset->CloseOnDisk();
4727 // groups root sub-branch
4728 SALOMEDS::SObject_wrap myGroupsBranch;
4729 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4730 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4732 char name_group[ 30 ];
4733 if ( i == GetNodeGroupsTag() )
4734 strcpy( name_group, "Groups of Nodes" );
4735 else if ( i == GetEdgeGroupsTag() )
4736 strcpy( name_group, "Groups of Edges" );
4737 else if ( i == GetFaceGroupsTag() )
4738 strcpy( name_group, "Groups of Faces" );
4739 else if ( i == GetVolumeGroupsTag() )
4740 strcpy( name_group, "Groups of Volumes" );
4741 else if ( i == Get0DElementsGroupsTag() )
4742 strcpy( name_group, "Groups of 0D Elements" );
4743 else if ( i == GetBallElementsGroupsTag() )
4744 strcpy( name_group, "Groups of Balls" );
4746 aGroup = new HDFgroup( name_group, aTopGroup );
4747 aGroup->CreateOnDisk();
4749 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4750 for ( ; it->More(); it->Next() ) {
4751 SALOMEDS::SObject_wrap mySObject = it->Value();
4752 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4753 if ( !CORBA::is_nil( aSubObject ) ) {
4754 SMESH_GroupBase_i* myGroupImpl =
4755 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4758 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4762 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4763 int anId = myStudyContext->findId( string( objStr.in() ) );
4765 // For each group, create a dataset named "Group <group_persistent_id>"
4766 // and store the group's user name into it
4767 const char* grpName = aGrpBaseDS->GetStoreName();
4768 CORBA::String_var aUserName = myGroupImpl->GetName();
4769 aSize[ 0 ] = strlen( aUserName ) + 1;
4771 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4772 aDataset->CreateOnDisk();
4773 aDataset->WriteOnDisk( aUserName );
4774 aDataset->CloseOnDisk();
4777 // For each group, create a dataset named "Group <group_persistent_id> Color"
4778 // and store the group's color into it
4779 char grpColorName[ 30 ];
4780 sprintf( grpColorName, "ColorGroup %d", anId );
4781 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4783 anRGB[ 0 ] = aColor.R;
4784 anRGB[ 1 ] = aColor.G;
4785 anRGB[ 2 ] = aColor.B;
4787 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4788 aDataset->CreateOnDisk();
4789 aDataset->WriteOnDisk( anRGB );
4790 aDataset->CloseOnDisk();
4792 // Pass SMESHDS_Group to MED writer
4793 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4795 myWriter.AddGroup( aGrpDS );
4797 // write reference on a shape if exists
4798 SMESHDS_GroupOnGeom* aGeomGrp =
4799 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4801 SALOMEDS::SObject_wrap mySubRef, myShape;
4802 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4803 mySubRef->ReferencedObject( myShape.inout() ) &&
4804 !CORBA::is_nil( myShape->GetObject() ))
4806 CORBA::String_var myRefOnObject = myShape->GetID();
4807 if ( myRefOnObject.in()[0] ) {
4808 char aRefName[ 30 ];
4809 sprintf( aRefName, "Ref on shape %d", anId);
4810 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4811 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4812 aDataset->CreateOnDisk();
4813 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4814 aDataset->CloseOnDisk();
4817 else // shape ref is invalid:
4819 // save a group on geometry as ordinary group
4820 myWriter.AddGroup( aGeomGrp );
4823 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4824 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4826 std::string str = aFilterGrp_i->FilterToString();
4827 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4828 aSize[ 0 ] = str.length() + 1;
4829 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4830 aDataset->CreateOnDisk();
4831 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4832 aDataset->CloseOnDisk();
4836 aGroup->CloseOnDisk();
4840 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4842 // Flush current mesh information into MED file
4845 // save info on nb of elements
4846 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4848 // maybe a shape was deleted in the study
4849 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4850 TopoDS_Shape nullShape;
4851 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4854 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4859 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4860 aGroup->CreateOnDisk();
4862 // each element belongs to one or none submesh,
4863 // so for each node/element, we store a submesh ID
4865 // Store submesh IDs
4866 for ( int isNode = 0; isNode < 2; ++isNode )
4868 SMDS_ElemIteratorPtr eIt =
4869 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4870 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4873 std::vector<int> smIDs; smIDs.reserve( nbElems );
4874 while ( eIt->more() )
4875 if ( const SMDS_MeshElement* e = eIt->next())
4876 smIDs.push_back( e->getshapeId() );
4878 aSize[ 0 ] = nbElems;
4879 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4880 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4881 aDataset->CreateOnDisk();
4882 aDataset->WriteOnDisk( & smIDs[0] );
4883 aDataset->CloseOnDisk();
4886 aGroup->CloseOnDisk();
4888 // Store node positions on sub-shapes (SMDS_Position):
4889 // ----------------------------------------------------
4891 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4892 aGroup->CreateOnDisk();
4894 // in aGroup, create 5 datasets to contain:
4895 // "Nodes on Edges" - ID of node on edge
4896 // "Edge positions" - U parameter on node on edge
4897 // "Nodes on Faces" - ID of node on face
4898 // "Face U positions" - U parameter of node on face
4899 // "Face V positions" - V parameter of node on face
4901 // Find out nb of nodes on edges and faces
4902 // Collect corresponding sub-meshes
4903 int nbEdgeNodes = 0, nbFaceNodes = 0;
4904 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4905 // loop on SMESHDS_SubMesh'es
4906 while ( smIt->more() )
4908 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4909 if ( aSubMesh->IsComplexSubmesh() )
4910 continue; // submesh containing other submeshs
4911 int nbNodes = aSubMesh->NbNodes();
4912 if ( nbNodes == 0 ) continue;
4914 int aShapeID = aSubMesh->GetID();
4915 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4917 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4918 // write only SMDS_FacePosition and SMDS_EdgePosition
4919 switch ( aShapeType ) {
4921 nbFaceNodes += nbNodes;
4922 aFaceSM.push_back( aSubMesh );
4925 nbEdgeNodes += nbNodes;
4926 aEdgeSM.push_back( aSubMesh );
4932 // Treat positions on edges or faces
4933 for ( int onFace = 0; onFace < 2; onFace++ )
4935 // Create arrays to store in datasets
4936 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4937 if (!nbNodes) continue;
4938 int* aNodeIDs = new int [ nbNodes ];
4939 double* aUPos = new double [ nbNodes ];
4940 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4943 // loop on sub-meshes
4944 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4945 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4946 for ( ; itSM != pListSM->end(); itSM++ )
4948 SMESHDS_SubMesh* aSubMesh = (*itSM);
4950 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4951 // loop on nodes in aSubMesh
4952 while ( itNode->more() )
4955 const SMDS_MeshNode* node = itNode->next();
4956 aNodeIDs [ iNode ] = node->GetID();
4959 const SMDS_PositionPtr pos = node->GetPosition();
4960 if ( onFace ) { // on FACE
4961 SMDS_FacePositionPtr fPos = pos;
4963 aUPos[ iNode ] = fPos->GetUParameter();
4964 aVPos[ iNode ] = fPos->GetVParameter();
4971 SMDS_EdgePositionPtr ePos = pos;
4973 aUPos[ iNode ] = ePos->GetUParameter();
4979 } // loop on nodes in aSubMesh
4980 } // loop on sub-meshes
4985 aSize[ 0 ] = nbNodes;
4987 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4988 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4989 aDataset->CreateOnDisk();
4990 aDataset->WriteOnDisk( aNodeIDs );
4991 aDataset->CloseOnDisk();
4994 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4995 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4996 aDataset->CreateOnDisk();
4997 aDataset->WriteOnDisk( aUPos );
4998 aDataset->CloseOnDisk();
5001 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5002 aDataset->CreateOnDisk();
5003 aDataset->WriteOnDisk( aVPos );
5004 aDataset->CloseOnDisk();
5009 if ( aVPos ) delete [] aVPos;
5011 } // treat positions on edges or faces
5013 // close "Node Positions" group
5014 aGroup->CloseOnDisk();
5016 } // if ( there are submeshes in SMESHDS_Mesh )
5019 // close mesh HDF group
5020 aTopGroup->CloseOnDisk();
5028 aFile->CloseOnDisk();
5031 // Convert temporary files to stream
5032 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5034 // Remove temporary files and directory
5036 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5038 return aStreamFile._retn();
5041 //=============================================================================
5043 * SMESH_Gen_i::SaveASCII
5045 * Save SMESH module's data in ASCII format
5047 //=============================================================================
5049 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5051 bool isMultiFile ) {
5052 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5053 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5054 return aStreamFile._retn();
5056 //after usual saving needs to encipher binary to text string
5057 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5058 int size = aStreamFile.in().length();
5059 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5060 for ( int i = 0; i < size; i++ )
5061 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5063 buffer[size * 3] = '\0';
5065 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5067 return anAsciiStreamFile._retn();
5070 //=============================================================================
5072 * SMESH_Gen_i::loadGeomData
5074 * Load GEOM module data
5076 //=============================================================================
5078 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
5080 if ( theCompRoot->_is_nil() )
5083 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
5084 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
5087 //=============================================================================
5091 * Load SMESH module's data
5093 //=============================================================================
5095 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5096 const SALOMEDS::TMPFile& theStream,
5101 Kernel_Utils::Localizer loc;
5103 //if (!myStudyContext)
5105 SALOMEDS::Study_var aStudy = getStudyServant();
5106 /* if( !theComponent->_is_nil() )
5108 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
5109 loadGeomData( aStudy->FindComponent( "GEOM" ) );
5112 // Get temporary files location
5113 TCollection_AsciiString tmpDir =
5114 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5116 // Convert the stream into sequence of files to process
5117 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5120 TCollection_AsciiString aStudyName( "" );
5121 if ( isMultiFile ) {
5122 CORBA::WString_var url = aStudy->URL();
5123 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5125 // Set names of temporary files
5126 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5127 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5131 HDFdataset* aDataset;
5132 HDFgroup* aTopGroup;
5134 HDFgroup* aSubGroup;
5135 HDFgroup* aSubSubGroup;
5138 // ---> open HDF file
5139 aFile = new HDFfile( (char*) filename.ToCString() );
5141 aFile->OpenOnDisk( HDF_RDONLY );
5143 catch ( HDFexception ) {
5144 INFOS( "Load(): " << filename << " not found!" );
5148 TPythonDump pd; // prevent dump during loading
5150 // DriverMED_R_SMESHDS_Mesh myReader;
5151 // myReader.SetFile( meshfile.ToCString() );
5153 // For PAL13473 ("Repetitive mesh") implementation.
5154 // New dependencies between SMESH objects are established:
5155 // now hypotheses can refer to meshes, shapes and other hypotheses.
5156 // To keep data consistent, the following order of data restoration
5158 // 1. Create hypotheses
5159 // 2. Create all meshes
5160 // 3. Load hypotheses' data
5163 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5164 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5165 list< SMESH::Filter_var > filters;
5167 // get total number of top-level groups
5168 int aNbGroups = aFile->nInternalObjects();
5169 if ( aNbGroups > 0 ) {
5170 // --> in first turn we should read&create hypotheses
5171 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5172 // open hypotheses root HDF group
5173 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5174 aTopGroup->OpenOnDisk();
5176 // get number of hypotheses
5177 int aNbObjects = aTopGroup->nInternalObjects();
5178 for ( int j = 0; j < aNbObjects; j++ ) {
5179 // try to identify hypothesis
5180 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5181 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5183 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5184 // open hypothesis group
5185 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5186 aGroup->OpenOnDisk();
5188 // --> get hypothesis id
5189 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5194 // get number of datasets
5195 int aNbSubObjects = aGroup->nInternalObjects();
5196 for ( int k = 0; k < aNbSubObjects; k++ ) {
5198 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5199 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5200 // --> get hypothesis name
5201 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5202 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5203 aDataset->OpenOnDisk();
5204 size = aDataset->GetSize();
5205 char* hypname_str = new char[ size ];
5206 aDataset->ReadFromDisk( hypname_str );
5207 hypname = string( hypname_str );
5208 delete [] hypname_str;
5209 aDataset->CloseOnDisk();
5211 // --> get hypothesis plugin library name
5212 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5213 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5214 aDataset->OpenOnDisk();
5215 size = aDataset->GetSize();
5216 char* libname_str = new char[ size ];
5217 aDataset->ReadFromDisk( libname_str );
5218 if(MYDEBUG) SCRUTE( libname_str );
5219 libname = string( libname_str );
5220 delete [] libname_str;
5221 aDataset->CloseOnDisk();
5223 // --> get hypothesis data
5224 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5225 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5226 aDataset->OpenOnDisk();
5227 size = aDataset->GetSize();
5228 char* hypdata_str = new char[ size ];
5229 aDataset->ReadFromDisk( hypdata_str );
5230 hypdata = string( hypdata_str );
5231 delete [] hypdata_str;
5232 aDataset->CloseOnDisk();
5235 // close hypothesis HDF group
5236 aGroup->CloseOnDisk();
5238 // --> restore hypothesis from data
5239 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5240 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5241 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5242 SMESH::SMESH_Hypothesis_var myHyp;
5244 try { // protect persistence mechanism against exceptions
5245 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5248 INFOS( "Exception during hypothesis creation" );
5251 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5253 // myImpl->LoadFrom( hypdata.c_str() );
5254 hypDataList.push_back( make_pair( myImpl, hypdata ));
5255 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5256 int newId = myStudyContext->findId( iorString.in() );
5257 myStudyContext->mapOldToNew( id, newId );
5260 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5264 // close hypotheses root HDF group
5265 aTopGroup->CloseOnDisk();
5269 // --> then we should read&create algorithms
5270 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5271 // open algorithms root HDF group
5272 aTopGroup = new HDFgroup( "Algorithms", aFile );
5273 aTopGroup->OpenOnDisk();
5275 // get number of algorithms
5276 int aNbObjects = aTopGroup->nInternalObjects();
5277 for ( int j = 0; j < aNbObjects; j++ ) {
5278 // try to identify algorithm
5279 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5280 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5282 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5283 // open algorithm group
5284 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5285 aGroup->OpenOnDisk();
5287 // --> get algorithm id
5288 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5293 // get number of datasets
5294 int aNbSubObjects = aGroup->nInternalObjects();
5295 for ( int k = 0; k < aNbSubObjects; k++ ) {
5297 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5298 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5299 // --> get algorithm name
5300 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5301 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5302 aDataset->OpenOnDisk();
5303 size = aDataset->GetSize();
5304 char* hypname_str = new char[ size ];
5305 aDataset->ReadFromDisk( hypname_str );
5306 hypname = string( hypname_str );
5307 delete [] hypname_str;
5308 aDataset->CloseOnDisk();
5310 // --> get algorithm plugin library name
5311 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5312 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5313 aDataset->OpenOnDisk();
5314 size = aDataset->GetSize();
5315 char* libname_str = new char[ size ];
5316 aDataset->ReadFromDisk( libname_str );
5317 if(MYDEBUG) SCRUTE( libname_str );
5318 libname = string( libname_str );
5319 delete [] libname_str;
5320 aDataset->CloseOnDisk();
5322 // --> get algorithm data
5323 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5324 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5325 aDataset->OpenOnDisk();
5326 size = aDataset->GetSize();
5327 char* hypdata_str = new char[ size ];
5328 aDataset->ReadFromDisk( hypdata_str );
5329 if(MYDEBUG) SCRUTE( hypdata_str );
5330 hypdata = string( hypdata_str );
5331 delete [] hypdata_str;
5332 aDataset->CloseOnDisk();
5335 // close algorithm HDF group
5336 aGroup->CloseOnDisk();
5338 // --> restore algorithm from data
5339 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5340 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5341 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5342 SMESH::SMESH_Hypothesis_var myHyp;
5344 try { // protect persistence mechanism against exceptions
5345 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5347 catch( SALOME::SALOME_Exception& ex )
5349 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5352 INFOS( "Exception during hypothesis creation" );
5355 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5357 //myImpl->LoadFrom( hypdata.c_str() );
5358 hypDataList.push_back( make_pair( myImpl, hypdata ));
5359 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5360 int newId = myStudyContext->findId( iorString.in() );
5361 myStudyContext->mapOldToNew( id, newId );
5364 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5368 // close algorithms root HDF group
5369 aTopGroup->CloseOnDisk();
5373 // --> the rest groups should be meshes
5374 for ( int i = 0; i < aNbGroups; i++ ) {
5375 // identify next group
5376 char meshName[ HDF_NAME_MAX_LEN+1 ];
5377 aFile->InternalObjectIndentify( i, meshName );
5379 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5381 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5385 // open mesh HDF group
5386 aTopGroup = new HDFgroup( meshName, aFile );
5387 aTopGroup->OpenOnDisk();
5389 // get number of child HDF objects
5390 int aNbObjects = aTopGroup->nInternalObjects();
5391 if ( aNbObjects > 0 ) {
5393 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5394 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5395 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5396 if ( !myNewMeshImpl )
5398 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5400 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5401 int newId = myStudyContext->findId( iorString.in() );
5402 myStudyContext->mapOldToNew( id, newId );
5405 // try to read and set auto color flag
5406 char aMeshAutoColorName[ 30 ];
5407 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5408 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5410 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5411 aDataset->OpenOnDisk();
5412 size = aDataset->GetSize();
5413 int* anAutoColor = new int[ size ];
5414 aDataset->ReadFromDisk( anAutoColor );
5415 aDataset->CloseOnDisk();
5416 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5417 delete [] anAutoColor;
5420 // try to read and set reference to shape
5421 GEOM::GEOM_Object_var aShapeObject;
5422 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5423 // load mesh "Ref on shape" - it's an entry to SObject
5424 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5425 aDataset->OpenOnDisk();
5426 size = aDataset->GetSize();
5427 char* refFromFile = new char[ size ];
5428 aDataset->ReadFromDisk( refFromFile );
5429 aDataset->CloseOnDisk();
5430 if ( strlen( refFromFile ) > 0 ) {
5431 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5433 // Make sure GEOM data are loaded first
5434 //loadGeomData( shapeSO->GetFatherComponent() );
5436 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5437 if ( !CORBA::is_nil( shapeObject ) ) {
5438 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5439 if ( !aShapeObject->_is_nil() )
5440 myNewMeshImpl->SetShape( aShapeObject );
5443 delete [] refFromFile;
5446 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5447 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5449 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5450 aDataset->OpenOnDisk();
5451 size = aDataset->GetSize();
5452 int* meshPersistentId = new int[ size ];
5453 aDataset->ReadFromDisk( meshPersistentId );
5454 aDataset->CloseOnDisk();
5455 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5456 delete [] meshPersistentId;
5459 // Restore file info
5460 if ( aTopGroup->ExistInternalObject( "file info" ))
5462 aDataset = new HDFdataset( "file info", aTopGroup );
5463 aDataset->OpenOnDisk();
5464 size = aDataset->GetSize();
5465 std::string info( size, ' ');
5466 aDataset->ReadFromDisk( (char*) info.data() );
5467 aDataset->CloseOnDisk();
5468 myNewMeshImpl->FileInfoFromString( info );
5474 // As all object that can be referred by hypothesis are created,
5475 // we can restore hypothesis data
5477 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5478 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5480 SMESH_Hypothesis_i* hyp = hyp_data->first;
5481 string & data = hyp_data->second;
5482 hyp->LoadFrom( data.c_str() );
5485 // Restore the rest mesh data
5487 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5488 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5490 aTopGroup = meshi_group->second;
5491 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5492 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5493 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5495 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5496 bool hasData = false;
5499 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5500 int newId = myStudyContext->findId( iorString.in() );
5501 int meshOldId = myStudyContext->getOldId( newId );
5503 // try to find mesh data dataset
5504 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5505 // load mesh "has data" flag
5506 aDataset = new HDFdataset( "Has data", aTopGroup );
5507 aDataset->OpenOnDisk();
5508 size = aDataset->GetSize();
5509 char* strHasData = new char[ size ];
5510 aDataset->ReadFromDisk( strHasData );
5511 aDataset->CloseOnDisk();
5512 if ( strcmp( strHasData, "1") == 0 ) {
5515 delete [] strHasData;
5518 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5519 // nodes and elements are not yet put into sub-meshes)
5520 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5521 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5522 aGroup->OpenOnDisk();
5523 // get number of applied algorithms
5524 int aNbSubObjects = aGroup->nInternalObjects();
5525 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5526 for ( int j = 0; j < aNbSubObjects; j++ ) {
5527 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5528 aGroup->InternalObjectIndentify( j, name_dataset );
5529 // check if it is an algorithm
5530 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5531 aDataset = new HDFdataset( name_dataset, aGroup );
5532 aDataset->OpenOnDisk();
5533 size = aDataset->GetSize();
5534 char* refFromFile = new char[ size ];
5535 aDataset->ReadFromDisk( refFromFile );
5536 aDataset->CloseOnDisk();
5537 // san - it is impossible to recover applied algorithms using their entries within Load() method
5538 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5539 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5540 int id = atoi( refFromFile );
5541 delete [] refFromFile;
5542 string anIOR = myStudyContext->getIORbyOldId( id );
5543 if ( !anIOR.empty() ) {
5544 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5545 if ( !CORBA::is_nil( hypObject ) ) {
5546 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5547 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5548 || !myNewMeshImpl->HasShapeToMesh()) )
5549 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5554 aGroup->CloseOnDisk();
5557 // try to get applied hypotheses
5558 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5559 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5560 aGroup->OpenOnDisk();
5561 // get number of applied hypotheses
5562 int aNbSubObjects = aGroup->nInternalObjects();
5563 for ( int j = 0; j < aNbSubObjects; j++ ) {
5564 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5565 aGroup->InternalObjectIndentify( j, name_dataset );
5566 // check if it is a hypothesis
5567 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5568 aDataset = new HDFdataset( name_dataset, aGroup );
5569 aDataset->OpenOnDisk();
5570 size = aDataset->GetSize();
5571 char* refFromFile = new char[ size ];
5572 aDataset->ReadFromDisk( refFromFile );
5573 aDataset->CloseOnDisk();
5574 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5575 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5576 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5577 int id = atoi( refFromFile );
5578 delete [] refFromFile;
5579 string anIOR = myStudyContext->getIORbyOldId( id );
5580 if ( !anIOR.empty() ) {
5581 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5582 if ( !CORBA::is_nil( hypObject ) ) {
5583 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5584 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5585 || !myNewMeshImpl->HasShapeToMesh()) )
5586 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5591 aGroup->CloseOnDisk();
5594 // --> try to find SUB-MESHES containers for each type of submesh
5595 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5596 const char* name_meshgroup = 0;
5597 if ( j == GetSubMeshOnVertexTag() )
5598 name_meshgroup = "SubMeshes On Vertex";
5599 else if ( j == GetSubMeshOnEdgeTag() )
5600 name_meshgroup = "SubMeshes On Edge";
5601 else if ( j == GetSubMeshOnWireTag() )
5602 name_meshgroup = "SubMeshes On Wire";
5603 else if ( j == GetSubMeshOnFaceTag() )
5604 name_meshgroup = "SubMeshes On Face";
5605 else if ( j == GetSubMeshOnShellTag() )
5606 name_meshgroup = "SubMeshes On Shell";
5607 else if ( j == GetSubMeshOnSolidTag() )
5608 name_meshgroup = "SubMeshes On Solid";
5609 else if ( j == GetSubMeshOnCompoundTag() )
5610 name_meshgroup = "SubMeshes On Compound";
5612 // try to get submeshes container HDF group
5613 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5614 // open submeshes containers HDF group
5615 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5616 aGroup->OpenOnDisk();
5618 // get number of submeshes
5619 int aNbSubMeshes = aGroup->nInternalObjects();
5620 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5622 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5623 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5624 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5625 // --> get submesh id
5626 int subid = atoi( name_submeshgroup + 7 );
5629 // open submesh HDF group
5630 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5631 aSubGroup->OpenOnDisk();
5633 // try to read and set reference to subshape
5634 GEOM::GEOM_Object_var aSubShapeObject;
5635 SMESH::SMESH_subMesh_var aSubMesh;
5637 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5638 // load submesh "Ref on shape" - it's an entry to SObject
5639 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5640 aDataset->OpenOnDisk();
5641 size = aDataset->GetSize();
5642 char* refFromFile = new char[ size ];
5643 aDataset->ReadFromDisk( refFromFile );
5644 aDataset->CloseOnDisk();
5645 if ( strlen( refFromFile ) > 0 ) {
5646 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5647 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5648 if ( !CORBA::is_nil( subShapeObject ) ) {
5649 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5650 if ( !aSubShapeObject->_is_nil() )
5651 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5652 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5653 if ( aSubMesh->_is_nil() )
5655 string iorSubString = GetORB()->object_to_string( aSubMesh );
5656 int newSubId = myStudyContext->findId( iorSubString );
5657 myStudyContext->mapOldToNew( subid, newSubId );
5660 delete [] refFromFile;
5663 if ( aSubMesh->_is_nil() )
5666 // try to get applied algorithms
5667 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5668 // open "applied algorithms" HDF group
5669 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5670 aSubSubGroup->OpenOnDisk();
5671 // get number of applied algorithms
5672 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5673 for ( int l = 0; l < aNbSubObjects; l++ ) {
5674 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5675 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5676 // check if it is an algorithm
5677 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5678 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5679 aDataset->OpenOnDisk();
5680 size = aDataset->GetSize();
5681 char* refFromFile = new char[ size ];
5682 aDataset->ReadFromDisk( refFromFile );
5683 aDataset->CloseOnDisk();
5685 int id = atoi( refFromFile );
5686 string anIOR = myStudyContext->getIORbyOldId( id );
5687 if ( !anIOR.empty() ) {
5688 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5689 if ( !CORBA::is_nil( hypObject ) ) {
5690 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5691 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5692 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5695 delete [] refFromFile;
5698 // close "applied algorithms" HDF group
5699 aSubSubGroup->CloseOnDisk();
5702 // try to get applied hypotheses
5703 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5704 // open "applied hypotheses" HDF group
5705 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5706 aSubSubGroup->OpenOnDisk();
5707 // get number of applied hypotheses
5708 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5709 for ( int l = 0; l < aNbSubObjects; l++ ) {
5710 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5711 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5712 // check if it is a hypothesis
5713 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5714 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5715 aDataset->OpenOnDisk();
5716 size = aDataset->GetSize();
5717 char* refFromFile = new char[ size ];
5718 aDataset->ReadFromDisk( refFromFile );
5719 aDataset->CloseOnDisk();
5721 int id = atoi( refFromFile );
5722 string anIOR = myStudyContext->getIORbyOldId( id );
5723 if ( !anIOR.empty() ) {
5724 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5725 if ( !CORBA::is_nil( hypObject ) ) {
5726 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5727 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5728 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5731 delete [] refFromFile;
5734 // close "APPLIED HYPOTHESES" hdf group
5735 aSubSubGroup->CloseOnDisk();
5738 // close SUB-MESH hdf group
5739 aSubGroup->CloseOnDisk();
5742 // close SUB-MESHES containers hdf group
5743 aGroup->CloseOnDisk();
5747 // try to get GROUPS
5748 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5749 char name_group[ 30 ];
5750 if ( ii == GetNodeGroupsTag() )
5751 strcpy( name_group, "Groups of Nodes" );
5752 else if ( ii == GetEdgeGroupsTag() )
5753 strcpy( name_group, "Groups of Edges" );
5754 else if ( ii == GetFaceGroupsTag() )
5755 strcpy( name_group, "Groups of Faces" );
5756 else if ( ii == GetVolumeGroupsTag() )
5757 strcpy( name_group, "Groups of Volumes" );
5758 else if ( ii == Get0DElementsGroupsTag() )
5759 strcpy( name_group, "Groups of 0D Elements" );
5760 else if ( ii == GetBallElementsGroupsTag() )
5761 strcpy( name_group, "Groups of Balls" );
5763 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5764 aGroup = new HDFgroup( name_group, aTopGroup );
5765 aGroup->OpenOnDisk();
5766 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5767 // within aGroup->ExistInternalObject( name )
5768 std::vector< std::string > subNames;
5769 TColStd_MapOfAsciiString mapOfNames;
5770 aGroup->GetAllObjects( subNames );
5771 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5772 mapOfNames.Add( subNames[ iN ].c_str() );
5774 for ( size_t j = 0; j < subNames.size(); j++ ) {
5775 const std::string& name_dataset = subNames[ j ];
5776 // check if it is a group
5777 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5780 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5783 int groupID = -1; // group local ID (also persistent)
5785 groupID = atoi( endptr + 1 );
5786 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5787 aDataset->OpenOnDisk();
5789 // Retrieve actual group name
5790 size = aDataset->GetSize();
5791 char* nameFromFile = new char[ size ];
5792 aDataset->ReadFromDisk( nameFromFile );
5793 aDataset->CloseOnDisk();
5795 // Try to find a shape reference
5796 TopoDS_Shape aShape;
5797 char aRefName[ 30 ];
5798 sprintf( aRefName, "Ref on shape %d", subid);
5799 if ( mapOfNames.Contains( aRefName ))
5801 // load mesh "Ref on shape" - it's an entry to SObject
5802 aDataset = new HDFdataset( aRefName, aGroup );
5803 aDataset->OpenOnDisk();
5804 size = aDataset->GetSize();
5805 char* refFromFile = new char[ size ];
5806 aDataset->ReadFromDisk( refFromFile );
5807 aDataset->CloseOnDisk();
5808 if ( strlen( refFromFile ) > 0 ) {
5809 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5810 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5811 if ( !CORBA::is_nil( shapeObject ) ) {
5812 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5813 if ( !aShapeObject->_is_nil() )
5814 aShape = GeomObjectToShape( aShapeObject );
5817 delete [] refFromFile;
5819 // Try to read a filter of SMESH_GroupOnFilter
5820 SMESH::Filter_var filter;
5821 SMESH_PredicatePtr predicate;
5822 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5823 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5825 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5826 aDataset->OpenOnDisk();
5827 size = aDataset->GetSize();
5828 char* persistStr = new char[ size ];
5829 aDataset->ReadFromDisk( persistStr );
5830 aDataset->CloseOnDisk();
5831 if ( strlen( persistStr ) > 0 ) {
5832 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5833 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5834 filters.push_back( filter );
5836 delete [] persistStr;
5839 // Create group servant
5840 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5841 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5842 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5843 delete [] nameFromFile;
5844 // Obtain a SMESHDS_Group object
5845 if ( aNewGroup->_is_nil() )
5848 string iorSubString = GetORB()->object_to_string( aNewGroup );
5849 int newSubId = myStudyContext->findId( iorSubString );
5850 myStudyContext->mapOldToNew( subid, newSubId );
5852 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5856 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5857 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5859 aFilterGroup->SetFilter( filter );
5860 filter->UnRegister();
5862 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5863 if ( !aGroupBaseDS )
5866 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5869 // Read color of the group
5870 char aGroupColorName[ 30 ];
5871 sprintf( aGroupColorName, "ColorGroup %d", subid);
5872 if ( mapOfNames.Contains( aGroupColorName ))
5874 aDataset = new HDFdataset( aGroupColorName, aGroup );
5875 aDataset->OpenOnDisk();
5876 size = aDataset->GetSize();
5877 double* anRGB = new double[ size ];
5878 aDataset->ReadFromDisk( anRGB );
5879 aDataset->CloseOnDisk();
5880 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5881 aGroupBaseDS->SetColor( aColor );
5886 aGroup->CloseOnDisk();
5890 // instead of reading mesh data, we read only brief information of all
5891 // objects: mesh, groups, sub-meshes (issue 0021208)
5894 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5895 meshfile.ToCString(), filename.ToCString(),
5899 // read Sub-Mesh ORDER if any
5900 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5901 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5902 aDataset->OpenOnDisk();
5903 size = aDataset->GetSize();
5904 int* smIDs = new int[ size ];
5905 aDataset->ReadFromDisk( smIDs );
5906 aDataset->CloseOnDisk();
5907 TListOfListOfInt anOrderIds;
5908 anOrderIds.push_back( TListOfInt() );
5909 for ( int i = 0; i < size; i++ )
5910 if ( smIDs[ i ] < 0 ) // is separator
5911 anOrderIds.push_back( TListOfInt() );
5913 anOrderIds.back().push_back(smIDs[ i ]);
5915 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5920 // update hyps needing full mesh data restored (issue 20918)
5921 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5923 SMESH_Hypothesis_i* hyp = hyp_data->first;
5924 hyp->UpdateAsMeshesRestored();
5927 // notify algos on completed restoration to set sub-mesh event listeners
5928 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5930 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5931 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5933 TopoDS_Shape myLocShape;
5934 if(myLocMesh.HasShapeToMesh())
5935 myLocShape = myLocMesh.GetShapeToMesh();
5937 myLocShape = SMESH_Mesh::PseudoShape();
5939 myLocMesh.GetSubMesh(myLocShape)->
5940 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5943 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5944 list< SMESH::Filter_var >::iterator f = filters.begin();
5945 for ( ; f != filters.end(); ++f )
5946 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5947 fi->FindBaseObjects();
5952 aTopGroup->CloseOnDisk();
5955 aFile->CloseOnDisk();
5958 // Remove temporary files created from the stream
5961 SMESH_File meshFile( meshfile.ToCString() );
5962 if ( !meshFile ) // no meshfile exists
5964 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5968 Engines::Container_var container = GetContainerRef();
5969 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5971 container_i->registerTemporaryFile( filename.ToCString() );
5972 container_i->registerTemporaryFile( meshfile.ToCString() );
5973 container_i->registerTemporaryFile( tmpDir.ToCString() );
5977 pd << ""; // prevent optimizing pd out
5979 // creation of tree nodes for all data objects in the study
5980 // to support tree representation customization and drag-n-drop:
5981 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5982 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5983 useCaseBuilder->SetRootCurrent();
5984 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5985 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5986 for (it->InitEx(true); it->More(); it->Next()) {
5987 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5994 //=============================================================================
5996 * SMESH_Gen_i::LoadASCII
5998 * Load SMESH module's data in ASCII format
6000 //=============================================================================
6002 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6003 const SALOMEDS::TMPFile& theStream,
6005 bool isMultiFile ) {
6006 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6007 return Load( theComponent, theStream, theURL, isMultiFile );
6009 //before call main ::Load method it's need for decipher text format to
6010 //binary ( "|xx" => x' )
6011 int size = theStream.length();
6012 if ( int((size / 3 )*3) != size ) //error size of buffer
6015 int real_size = int(size / 3);
6017 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6020 unsigned int c = -1;
6021 for ( int i = 0; i < real_size; i++ )
6023 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6024 sscanf( tmp, "%x", &c );
6025 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6028 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6030 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6033 //=============================================================================
6035 * SMESH_Gen_i::Close
6037 * Clears study-connected data when it is closed
6039 //=============================================================================
6041 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6043 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6045 // Clear study contexts data
6046 myStudyContext->Clear();
6048 // remove the tmp files meshes are loaded from
6049 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6051 // Clean trace of API methods calls
6057 //=============================================================================
6059 * SMESH_Gen_i::ComponentDataType
6061 * Get component data type
6063 //=============================================================================
6065 char* SMESH_Gen_i::ComponentDataType()
6067 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6068 return CORBA::string_dup( "SMESH" );
6072 //=============================================================================
6074 * SMESH_Gen_i::IORToLocalPersistentID
6076 * Transform data from transient form to persistent
6078 //=============================================================================
6080 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6081 const char* IORString,
6082 CORBA::Boolean /*isMultiFile*/,
6083 CORBA::Boolean /*isASCII*/ )
6085 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6087 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6088 int anId = myStudyContext->findId( IORString );
6090 if(MYDEBUG) MESSAGE( "VSR " << anId )
6092 sprintf( strId, "%d", anId );
6093 return CORBA::string_dup( strId );
6096 return CORBA::string_dup( "" );
6099 //=============================================================================
6101 * SMESH_Gen_i::LocalPersistentIDToIOR
6103 * Transform data from persistent form to transient
6105 //=============================================================================
6107 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6108 const char* aLocalPersistentID,
6109 CORBA::Boolean /*isMultiFile*/,
6110 CORBA::Boolean /*isASCII*/ )
6112 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6114 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6115 int anId = atoi( aLocalPersistentID );
6116 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6118 return CORBA::string_dup( "" );
6121 //=======================================================================
6122 //function : RegisterObject
6124 //=======================================================================
6126 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6128 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6129 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6130 return myStudyContext->addObject( string( iorString.in() ) );
6135 //================================================================================
6137 * \brief Return id of registered object
6138 * \param theObject - the Object
6139 * \retval int - Object id
6141 //================================================================================
6143 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6145 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6146 string iorString = GetORB()->object_to_string( theObject );
6147 return myStudyContext->findId( iorString );
6152 //=============================================================================
6154 * SMESH_Gen_i::SetName
6156 * Set a new object name
6158 //=============================================================================
6159 void SMESH_Gen_i::SetName(const char* theIOR,
6160 const char* theName)
6162 if ( theIOR && strcmp( theIOR, "" ) ) {
6163 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6164 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6165 if ( !aSO->_is_nil() ) {
6166 SetName( aSO, theName );
6171 // Version information
6172 char* SMESH_Gen_i::getVersion()
6174 #if SMESH_DEVELOPMENT
6175 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6177 return CORBA::string_dup(SMESH_VERSION_STR);
6181 //=================================================================================
6182 // function : Move()
6183 // purpose : Moves objects to the specified position.
6184 // Is used in the drag-n-drop functionality.
6185 //=================================================================================
6186 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6187 SALOMEDS::SObject_ptr where,
6190 if ( CORBA::is_nil( where ) ) return;
6192 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6193 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6194 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6195 std::string dataType = father->ComponentDataType();
6196 if ( dataType != "SMESH" ) return; // not a SMESH component
6198 SALOMEDS::SObject_var objAfter;
6199 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6200 // insert at given row -> find insertion position
6201 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6203 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6204 if ( i == row && useCaseIt->More() ) {
6205 objAfter = useCaseIt->Value();
6209 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6210 SALOMEDS::SObject_var sobj = what[i];
6211 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6212 // insert the object to the use case tree
6213 if ( !CORBA::is_nil( objAfter ) )
6214 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6216 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6219 //================================================================================
6221 * \brief Returns true if algorithm can be used to mesh a given geometry
6222 * \param [in] theAlgoType - the algorithm type
6223 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6224 * \param [in] theGeomObject - the geometry to mesh
6225 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6226 * else, returns \c True if at least one shape is meshable
6227 * \return CORBA::Boolean - can or can't
6229 //================================================================================
6231 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6232 const char* theLibName,
6233 GEOM::GEOM_Object_ptr theGeomObject,
6234 CORBA::Boolean toCheckAll)
6238 std::string aPlatformLibName;
6239 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6240 GenericHypothesisCreator_i* aCreator =
6241 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6244 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6245 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6246 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6253 SMESH_CATCH( SMESH::doNothing );
6256 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6261 //=================================================================================
6262 // function : GetInsideSphere
6263 // purpose : Collect indices of elements, which are located inside the sphere
6264 //=================================================================================
6265 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6266 SMESH::ElementType theElemType,
6272 SMESH::long_array_var aResult = new SMESH::long_array();
6273 if ( meshPart->_is_nil() )
6274 return aResult._retn();
6276 // 1. Create geometrical object
6277 gp_Pnt aP( theX, theY, theZ );
6278 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6280 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6282 if ( lst.size() > 0 ) {
6283 aResult->length( lst.size() );
6284 for ( size_t i = 0; i < lst.size(); i++ ) {
6285 aResult[i] = lst[i];
6288 return aResult._retn();
6291 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6292 SMESH::ElementType theElemType,
6293 CORBA::Double theX1,
6294 CORBA::Double theY1,
6295 CORBA::Double theZ1,
6296 CORBA::Double theX2,
6297 CORBA::Double theY2,
6298 CORBA::Double theZ2) {
6299 SMESH::long_array_var aResult = new SMESH::long_array();
6300 if( meshPart->_is_nil() )
6301 return aResult._retn();
6303 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6305 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6307 if( lst.size() > 0 ) {
6308 aResult->length( lst.size() );
6309 for ( size_t i = 0; i < lst.size(); i++ ) {
6310 aResult[i] = lst[i];
6313 return aResult._retn();
6316 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6317 SMESH::ElementType theElemType,
6321 CORBA::Double theDX,
6322 CORBA::Double theDY,
6323 CORBA::Double theDZ,
6325 CORBA::Double theR ){
6326 SMESH::long_array_var aResult = new SMESH::long_array();
6327 if( meshPart->_is_nil() )
6328 return aResult._retn();
6330 gp_Pnt aP( theX, theY, theZ );
6331 gp_Vec aV( theDX, theDY, theDZ );
6332 gp_Ax2 anAxes (aP, aV);
6334 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6336 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6338 if( lst.size() > 0 ) {
6339 aResult->length( lst.size() );
6340 for ( size_t i = 0; i < lst.size(); i++ ) {
6341 aResult[i] = lst[i];
6344 return aResult._retn();
6347 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6348 SMESH::ElementType theElemType,
6349 GEOM::GEOM_Object_ptr theGeom,
6350 CORBA::Double theTolerance ) {
6351 SMESH::long_array_var aResult = new SMESH::long_array();
6352 if( meshPart->_is_nil() || theGeom->_is_nil() )
6353 return aResult._retn();
6355 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6357 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6359 if( lst.size() > 0 ) {
6360 aResult->length( lst.size() );
6361 for ( size_t i = 0; i < lst.size(); i++ ) {
6362 aResult[i] = lst[i];
6365 return aResult._retn();
6370 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6371 SMESH::ElementType theElemType,
6372 TopoDS_Shape& aShape,
6373 double* theTolerance) {
6375 std::vector<long> res;
6376 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6378 if ( mesh->_is_nil() )
6381 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6385 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6390 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6391 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6392 anElementsOnShape->SetAllNodes( true );
6393 anElementsOnShape->SetMesh( meshDS );
6394 anElementsOnShape->SetShape( aShape, aType );
6397 anElementsOnShape->SetTolerance(*theTolerance);
6399 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6400 if ( !msource->_is_nil() ) { // Mesh case
6401 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6403 while ( elemIt->more() ) {
6404 const SMDS_MeshElement* anElem = elemIt->next();
6405 long anId = anElem->GetID();
6406 if ( anElementsOnShape->IsSatisfy( anId ) )
6407 res.push_back( anId );
6411 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6412 if ( !gsource->_is_nil() ) {
6413 if(theElemType == SMESH::NODE) {
6414 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6415 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6416 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6417 long anId = node->GetID();
6418 if ( anElementsOnShape->IsSatisfy( anId ) )
6419 res.push_back( anId );
6422 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6423 SMESH::long_array_var elems = gsource->GetListOfID();
6424 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6425 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6426 long anId = elem->GetID();
6427 if ( anElementsOnShape->IsSatisfy( anId ) )
6428 res.push_back( anId );
6433 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6434 if ( !smsource->_is_nil() ) {
6435 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6436 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6437 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6439 long anId = elem->GetID();
6440 if ( anElementsOnShape->IsSatisfy( anId ) )
6441 res.push_back( anId );
6449 //=============================================================================
6451 * SMESHEngine_factory
6453 * C factory, accessible with dlsym, after dlopen
6455 //=============================================================================
6459 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6460 PortableServer::POA_ptr poa,
6461 PortableServer::ObjectId* contId,
6462 const char* instanceName,
6463 const char* interfaceName )
6465 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6466 if(MYDEBUG) SCRUTE(interfaceName);
6467 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6468 return aSMESHGen->getId() ;