1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
161 CORBA::ORB_var SMESH_Gen_i::myOrb;
162 PortableServer::POA_var SMESH_Gen_i::myPoa;
163 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
164 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
165 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
168 const int nbElemPerDiagonal = 10;
170 //=============================================================================
172 * GetServant [ static ]
174 * Get servant of the CORBA object
176 //=============================================================================
178 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
180 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
183 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
186 catch (PortableServer::POA::ObjectNotActive &ex)
188 INFOS("GetServant: ObjectNotActive");
191 catch (PortableServer::POA::WrongAdapter &ex)
193 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
196 catch (PortableServer::POA::WrongPolicy &ex)
198 INFOS("GetServant: WrongPolicy");
203 INFOS( "GetServant - Unknown exception was caught!!!" );
208 //=============================================================================
210 * SObjectToObject [ static ]
212 * Get CORBA object corresponding to the SALOMEDS::SObject
214 //=============================================================================
216 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
218 SALOMEDS::GenericAttribute_wrap anAttr;
219 CORBA::Object_var anObj;
220 if ( !theSObject->_is_nil() ) {
222 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
223 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
224 CORBA::String_var aValue = anIOR->Value();
225 if( strcmp( aValue, "" ) != 0 )
226 anObj = GetORB()->string_to_object( aValue );
230 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
236 //=============================================================================
240 * Get SALOME_NamingService object
242 //=============================================================================
244 SALOME_NamingService* SMESH_Gen_i::GetNS()
246 if ( myNS == NULL ) {
247 myNS = SINGLETON_<SALOME_NamingService>::Instance();
248 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
249 myNS->init_orb( GetORB() );
254 //=============================================================================
258 * Get SALOME_LifeCycleCORBA object
260 //=============================================================================
261 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
262 if ( myLCC == NULL ) {
263 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
269 //=============================================================================
271 * GetGeomEngine [ static ]
273 * Get GEOM::GEOM_Gen reference
275 //=============================================================================
276 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
277 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
278 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
279 //CCRT return aGeomEngine._retn();
280 if(CORBA::is_nil(myGeomGen))
282 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
283 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
288 //=============================================================================
290 * SMESH_Gen_i::SMESH_Gen_i
292 * Default constructor: not for use
294 //=============================================================================
296 SMESH_Gen_i::SMESH_Gen_i()
300 //=============================================================================
302 * SMESH_Gen_i::SMESH_Gen_i
304 * Standard constructor, used with Container
306 //=============================================================================
308 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
309 PortableServer::POA_ptr poa,
310 PortableServer::ObjectId* contId,
311 const char* instanceName,
312 const char* interfaceName )
313 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
316 myOrb = CORBA::ORB::_duplicate(orb);
317 myPoa = PortableServer::POA::_duplicate(poa);
320 _id = myPoa->activate_object( _thisObj );
322 myStudyContext = new StudyContext;
324 myIsEmbeddedMode = false;
325 myIsEnablePublish = true;
326 myShapeReader = NULL; // shape reader
328 myIsHistoricalPythonDump = true;
329 myToForgetMeshDataOnHypModif = false;
331 // set it in standalone mode only
332 //OSD::SetSignal( true );
334 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
335 // find out mode (embedded or standalone) here else
336 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
337 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
338 if ( SALOME_NamingService* ns = GetNS() )
340 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
341 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
342 if ( !session->_is_nil() )
344 CORBA::String_var str_host = session->getHostname();
345 CORBA::Long s_pid = session->getPID();
346 string my_host = Kernel_Utils::GetHostname();
348 long my_pid = (long)_getpid();
350 long my_pid = (long) getpid();
352 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
357 //=============================================================================
359 * SMESH_Gen_i::~SMESH_Gen_i
363 //=============================================================================
365 SMESH_Gen_i::~SMESH_Gen_i()
367 // delete hypothesis creators
368 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
369 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
371 // same creator can be mapped under different names
372 GenericHypothesisCreator_i* creator = (*itHyp).second;
376 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
377 if ( creator == (*itHyp2).second )
378 (*itHyp2).second = 0;
380 myHypCreatorMap.clear();
382 // Clear study contexts data
383 delete myStudyContext;
385 // delete shape reader
387 delete myShapeReader;
389 //=============================================================================
391 * SMESH_Gen_i::getHypothesisCreator
393 * Get hypothesis creator
395 //=============================================================================
396 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
397 const char* theLibName,
398 std::string& thePlatformLibName)
399 throw (SALOME::SALOME_Exception)
401 std::string aPlatformLibName;
402 /* It's Need to translate lib name for WIN32 or X platform */
403 if ( theLibName && theLibName[0] != '\0' )
405 int libNameLen = strlen(theLibName);
406 //check for old format "libXXXXXXX.so"
407 if (libNameLen > 7 &&
408 !strncmp( theLibName, "lib", 3 ) &&
409 !strcmp( theLibName+libNameLen-3, ".so" ))
413 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
414 #elif defined(__APPLE__)
415 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
417 aPlatformLibName = theLibName;
422 //try to use new format
424 aPlatformLibName = theLibName;
425 aPlatformLibName += ".dll";
426 #elif defined(__APPLE__)
427 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
429 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
433 thePlatformLibName = aPlatformLibName;
435 Unexpect aCatch(SALOME_SalomeException);
436 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
438 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
439 GenericHypothesisCreator_i* aCreator;
442 // check, if creator for this hypothesis type already exists
443 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
445 // load plugin library
446 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
449 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
451 const char* path = aPlatformLibName.c_str();
454 const char* path = aPlatformLibName.c_str();
456 LibHandle libHandle = LoadLib( path );
457 #if defined(WIN32) && defined(UNICODE)
462 // report any error, if occurred
464 const char* anError = dlerror();
465 throw(SALOME_Exception( anError ));
467 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
468 << aPlatformLibName));
472 // get method, returning hypothesis creator
473 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
474 GetHypothesisCreator procHandle =
475 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
478 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
479 << aPlatformLibName ));
480 UnLoadLib(libHandle);
483 // get hypothesis creator
484 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
485 aCreator = procHandle(theHypName);
488 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
489 << aPlatformLibName));
491 // map hypothesis creator to a hypothesis name
492 myHypCreatorMap[string(theHypName)] = aCreator;
497 return myHypCreatorMap[string(theHypName)];
500 catch (SALOME_Exception& S_ex)
502 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
507 //=============================================================================
509 * SMESH_Gen_i::createHypothesis
511 * Create hypothesis of given type
513 //=============================================================================
514 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
515 const char* theLibName)
517 SMESH_Hypothesis_i* myHypothesis_i = 0;
518 SMESH::SMESH_Hypothesis_var hypothesis_i;
519 std::string aPlatformLibName;
520 GenericHypothesisCreator_i* aCreator =
521 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
523 // create a new hypothesis object, store its ref. in studyContext
524 myHypothesis_i = aCreator->Create(myPoa, &myGen);
527 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
528 CORBA::String_var hypName = myHypothesis_i->GetName();
529 myHypCreatorMap[ hypName.in() ] = aCreator;
531 // activate the CORBA servant of hypothesis
532 hypothesis_i = myHypothesis_i->_this();
533 int nextId = RegisterObject( hypothesis_i );
534 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
535 else { nextId = 0; } // avoid "unused variable" warning in release mode
537 return hypothesis_i._retn();
540 //=============================================================================
542 * SMESH_Gen_i::createMesh
544 * Create empty mesh on shape
546 //=============================================================================
547 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
548 throw ( SALOME::SALOME_Exception )
550 Unexpect aCatch(SALOME_SalomeException);
551 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
553 // Get or create the GEOM_Client instance
555 // create a new mesh object servant, store it in a map in study context
556 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
557 // create a new mesh object
558 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
559 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
561 // activate the CORBA servant of Mesh
562 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
563 int nextId = RegisterObject( mesh );
564 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
565 else { nextId = 0; } // avoid "unused variable" warning in release mode
568 catch (SALOME_Exception& S_ex) {
569 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
571 return SMESH::SMESH_Mesh::_nil();
574 //=============================================================================
576 * SMESH_Gen_i::GetShapeReader
580 //=============================================================================
581 GEOM_Client* SMESH_Gen_i::GetShapeReader()
583 // create shape reader if necessary
584 if ( !myShapeReader )
585 myShapeReader = new GEOM_Client(GetContainerRef());
586 ASSERT( myShapeReader );
587 return myShapeReader;
590 //=============================================================================
592 * SMESH_Gen_i::SetGeomEngine
594 * Set GEOM::GEOM_Gen reference
596 //=============================================================================
597 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
598 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
600 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
601 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
602 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
606 //=============================================================================
608 * SMESH_Gen_i::SetEmbeddedMode
612 //=============================================================================
614 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
616 myIsEmbeddedMode = theMode;
618 if ( !myIsEmbeddedMode ) {
619 //PAL10867: disable signals catching with "noexcepthandler" option
620 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
621 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
626 char* envDisableFPE = getenv("DISABLE_FPE");
627 if (envDisableFPE && atoi(envDisableFPE))
632 OSD::SetSignal( raiseFPE );
634 // else OSD::SetSignal() is called in GUI
638 //=============================================================================
640 * SMESH_Gen_i::IsEmbeddedMode
644 //=============================================================================
646 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
648 return myIsEmbeddedMode;
651 //=============================================================================
653 * SMESH_Gen_i::SetEnablePublish
655 * Set enable publishing in the study
657 //=============================================================================
658 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
660 myIsEnablePublish = theIsEnablePublish;
663 //=============================================================================
665 * SMESH_Gen_i::IsEnablePublish
667 * Check enable publishing
669 //=============================================================================
671 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
673 return myIsEnablePublish;
676 //=============================================================================
678 * SMESH_Gen_i::UpdateStudy
680 * Update study (needed at switching GEOM->SMESH)
682 //=============================================================================
684 void SMESH_Gen_i::UpdateStudy()
686 if ( !myStudyContext )
687 myStudyContext = new StudyContext;
689 SALOMEDS::Study_var aStudy = getStudyServant();
690 if ( !CORBA::is_nil( aStudy ) ) {
691 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
692 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
693 if( !GEOM_var->_is_nil() )
694 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
695 // NPAL16168, issue 0020210
696 // Let meshes update their data depending on GEOM groups that could change
697 CORBA::String_var compDataType = ComponentDataType();
698 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
699 if ( !me->_is_nil() ) {
700 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
701 for ( ; anIter->More(); anIter->Next() ) {
702 SALOMEDS::SObject_wrap so = anIter->Value();
703 CORBA::Object_var ior = SObjectToObject( so );
704 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
705 mesh->CheckGeomModif();
711 //=============================================================================
713 * SMESH_Gen_i::GetStudyContext
717 //=============================================================================
718 StudyContext* SMESH_Gen_i::GetStudyContext()
720 return myStudyContext;
723 //=============================================================================
725 * SMESH_Gen_i::CreateHypothesis
727 * Create hypothesis/algorithm of given type and publish it in the study
729 //=============================================================================
731 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
732 const char* theLibName )
733 throw ( SALOME::SALOME_Exception )
735 Unexpect aCatch(SALOME_SalomeException);
736 // Create hypothesis/algorithm
737 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
739 // Publish hypothesis/algorithm in the study
740 if ( CanPublishInStudy( hyp ) ) {
741 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
742 if ( !aSO->_is_nil() ) {
743 // Update Python script
744 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
745 << theHypName << "', '" << theLibName << "')";
752 //================================================================================
754 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
755 * existing on the given geometry or to size of the geometry.
756 * \param theHypType - hypothesis type name
757 * \param theLibName - plugin library name
758 * \param theMesh - The mesh of interest
759 * \param theGeom - The shape to get parameter values from
760 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
761 * in a study and used to compute the mesh, or a temporary one created just to pass
764 //================================================================================
766 SMESH::SMESH_Hypothesis_ptr
767 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
768 const char* theLibName,
769 SMESH::SMESH_Mesh_ptr theMesh,
770 GEOM::GEOM_Object_ptr theGeom,
771 const SMESH::HypInitParams& theParams)
772 throw ( SALOME::SALOME_Exception )
774 Unexpect aCatch(SALOME_SalomeException);
776 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
777 if ( byMesh && CORBA::is_nil( theMesh ) )
778 return SMESH::SMESH_Hypothesis::_nil();
779 if ( byMesh && CORBA::is_nil( theGeom ) )
780 return SMESH::SMESH_Hypothesis::_nil();
782 // -----------------------------------------------
783 // find hypothesis used to mesh theGeom
784 // -----------------------------------------------
786 // get mesh and shape
787 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
788 TopoDS_Shape shape = GeomObjectToShape( theGeom );
789 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
790 return SMESH::SMESH_Hypothesis::_nil();
791 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
793 // create a temporary hypothesis to know its dimension
794 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
795 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
797 return SMESH::SMESH_Hypothesis::_nil();
798 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
801 // look for a hypothesis of theHypType used to mesh the shape
802 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
805 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
806 int nbLocalHyps = aHypList->length();
807 for ( int i = 0; i < nbLocalHyps; i++ ) {
808 CORBA::String_var hypName = aHypList[i]->GetName();
809 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
810 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
812 // check super shapes
813 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
814 while ( nbLocalHyps == 0 && itShape.More() ) {
815 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
816 if ( ! CORBA::is_nil( geomObj )) {
817 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
818 nbLocalHyps = aHypList->length();
819 for ( int i = 0; i < nbLocalHyps; i++ )
820 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
821 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
827 // let the temporary hypothesis find out somehow parameter values by mesh
828 if ( hyp->SetParametersByMesh( mesh, shape ))
829 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
833 ::SMESH_Hypothesis::TDefaults dflts;
834 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
835 dflts._nbSegments = myGen.GetDefaultNbSegments();
836 dflts._elemLength = theParams.averageLength;
837 dflts._quadDominated = theParams.quadDominated;
838 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
841 dflts._diagonal = mesh->GetShapeDiagonalSize();
843 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
844 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
845 dflts._shape = &shape;
847 // let the hypothesis initialize it's values
848 if ( hyp->SetParametersByDefaults( dflts, mesh ))
849 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
852 return SMESH::SMESH_Hypothesis::_nil();
855 //=============================================================================
857 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
858 * \param [in] theHyp - the hypothesis of interest
859 * \param [out] theMesh - the sole mesh using \a theHyp
860 * \param [out] theShape - the sole geometry \a theHyp is assigned to
861 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
863 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
864 * considered as SAME sub-mesh => result is \c true.
865 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
866 * a shape to which an hyp being edited is assigned.
868 //=============================================================================
870 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
871 SMESH::SMESH_Mesh_out theMesh,
872 GEOM::GEOM_Object_out theShape)
874 if ( CORBA::is_nil( theHyp ))
877 // get Mesh component SO
878 CORBA::String_var compDataType = ComponentDataType();
879 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
880 if ( CORBA::is_nil( comp ))
883 // look for child SO of meshes
884 SMESH::SMESH_Mesh_var foundMesh;
885 TopoDS_Shape foundShape;
887 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
888 for ( ; meshIter->More() && isSole; meshIter->Next() )
890 SALOMEDS::SObject_wrap curSO = meshIter->Value();
891 CORBA::Object_var obj = SObjectToObject( curSO );
892 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
896 // look for a sole shape where theHyp is assigned
897 bool isHypFound = false;
898 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
899 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
900 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
902 const THypList& hyps = s2hypsIt.Value();
903 THypList::const_iterator h = hyps.begin();
904 for ( ; h != hyps.end(); ++h )
905 if ( (*h)->GetID() == theHyp->GetId() )
907 if ( h != hyps.end()) // theHyp found
910 if ( ! foundShape.IsNull() &&
911 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
913 foundShape.Nullify();
917 foundShape = s2hypsIt.Key();
919 } // loop on assigned hyps
921 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
923 if ( !foundMesh->_is_nil() ) // not a sole mesh
925 if ( !foundMesh->HasShapeToMesh() ||
926 !mesh_i ->HasShapeToMesh() )
928 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
932 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
933 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
934 isSole = s1->IsSame( s2 );
937 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
943 ! foundMesh->_is_nil() &&
944 ! foundShape.IsNull() )
946 theMesh = foundMesh._retn();
947 theShape = ShapeToGeomObject( foundShape );
948 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
953 //=============================================================================
955 * Sets number of segments per diagonal of boundary box of geometry by which
956 * default segment length of appropriate 1D hypotheses is defined
958 //=============================================================================
960 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
961 throw ( SALOME::SALOME_Exception )
963 if ( theNbSegments > 0 )
964 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
966 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
968 //=============================================================================
970 * \brief Sets default number of segments per edge
972 //=============================================================================
973 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
974 throw ( SALOME::SALOME_Exception )
976 if ( theNbSegments > 0 )
977 myGen.SetDefaultNbSegments( int(theNbSegments) );
979 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
982 //=============================================================================
986 //=============================================================================
988 void SMESH_Gen_i::SetOption(const char* name, const char* value)
990 if ( name && value && strlen( value ) > 0 )
993 if ( strcmp(name, "historical_python_dump") == 0 )
995 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
996 msgToGUI = "preferences/SMESH/historical_python_dump/";
997 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
999 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1001 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1002 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1003 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1005 else if ( strcmp(name, "default_grp_color") == 0 )
1009 // color must be presented as a string of following form:
1010 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1011 str = str.substr(1);
1012 for ( size_t i = 0; i < str.length()/2; i++ )
1013 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1014 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1016 else if ( value ) { // rgb color ("255,170,0", for example)
1017 string tempValue( value );
1018 char* colorValue = strtok( &tempValue[0], "," );
1019 while ( colorValue != NULL ) {
1020 int c_value = atoi( colorValue );
1021 if ( c_value >= 0 && c_value <= 255 )
1022 color.push_back( c_value );
1023 colorValue = strtok( NULL, "," );
1026 if ( color.size() == 3 ) { // color must have three valid component
1027 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1028 myDefaultGroupColor = value;
1029 msgToGUI = "preferences/SMESH/default_grp_color/";
1034 // update preferences in case if SetOption() is invoked from python console
1035 if ( !msgToGUI.empty() )
1037 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1038 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1039 if ( !CORBA::is_nil( session ) )
1040 session->emitMessageOneWay(msgToGUI.c_str());
1045 //=============================================================================
1047 Return an option value
1049 //=============================================================================
1051 char* SMESH_Gen_i::GetOption(const char* name)
1055 if ( strcmp(name, "historical_python_dump") == 0 )
1057 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1059 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1061 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1063 if ( strcmp(name, "default_grp_color") == 0 )
1065 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1068 return CORBA::string_dup( "" );
1071 //=============================================================================
1073 * SMESH_Gen_i::CreateMesh
1075 * Create empty mesh on a shape and publish it in the study
1077 //=============================================================================
1079 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1080 throw ( SALOME::SALOME_Exception )
1082 Unexpect aCatch(SALOME_SalomeException);
1083 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1085 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1087 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1088 ASSERT( meshServant );
1089 meshServant->SetShape( theShapeObject );
1091 // publish mesh in the study
1092 if ( CanPublishInStudy( mesh ) ) {
1093 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1094 aStudyBuilder->NewCommand(); // There is a transaction
1095 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1096 aStudyBuilder->CommitCommand();
1097 if ( !aSO->_is_nil() ) {
1098 // Update Python script
1099 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1103 return mesh._retn();
1106 //=============================================================================
1108 * SMESH_Gen_i::CreateEmptyMesh
1112 //=============================================================================
1114 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1115 throw ( SALOME::SALOME_Exception )
1117 Unexpect aCatch(SALOME_SalomeException);
1118 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1120 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1122 // publish mesh in the study
1123 if ( CanPublishInStudy( mesh ) ) {
1124 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1125 aStudyBuilder->NewCommand(); // There is a transaction
1126 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1127 aStudyBuilder->CommitCommand();
1128 if ( !aSO->_is_nil() ) {
1129 // Update Python script
1130 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1134 return mesh._retn();
1139 //================================================================================
1141 * \brief Throws an exception in case if the file can't be read
1143 //================================================================================
1145 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1147 SMESH_File f ( theFileName );
1150 if ( !f.error().empty() )
1151 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1153 THROW_SALOME_CORBA_EXCEPTION
1154 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1155 SALOME::BAD_PARAM );
1160 //=============================================================================
1162 * SMESH_Gen_i::CreateMeshFromUNV
1164 * Create mesh and import data from UNV file
1166 //=============================================================================
1168 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1169 throw ( SALOME::SALOME_Exception )
1171 Unexpect aCatch(SALOME_SalomeException);
1173 checkFileReadable( theFileName );
1175 SMESH::SMESH_Mesh_var aMesh = createMesh();
1177 // publish mesh in the study
1178 if ( CanPublishInStudy( aMesh ) ) {
1179 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1180 aStudyBuilder->NewCommand(); // There is a transaction
1181 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1182 aStudyBuilder->CommitCommand();
1183 if ( !aSO->_is_nil() ) {
1184 // Update Python script
1185 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1189 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1191 aServant->ImportUNVFile( theFileName );
1193 // Dump creation of groups
1194 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1196 aServant->GetImpl().GetMeshDS()->Modified();
1197 return aMesh._retn();
1200 //=============================================================================
1202 * SMESH_Gen_i::CreateMeshFromMED
1204 * Create mesh and import data from MED file
1206 //=============================================================================
1208 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1209 SMESH::DriverMED_ReadStatus& theStatus,
1210 const char* theCommandNameForPython,
1211 const char* theFileNameForPython)
1214 char bname[ _MAX_FNAME ];
1215 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1216 string aFileName = bname;
1218 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1220 // Retrieve mesh names from the file
1221 DriverMED_R_SMESHDS_Mesh myReader;
1222 myReader.SetFile( theFileName );
1223 myReader.SetMeshId( -1 );
1224 Driver_Mesh::Status aStatus;
1225 list<string> aNames = myReader.GetMeshNames(aStatus);
1226 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1227 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1229 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1232 TPythonDump aPythonDump;
1233 aPythonDump << "([";
1235 if (theStatus == SMESH::DRS_OK) {
1236 SALOMEDS::StudyBuilder_var aStudyBuilder;
1237 aStudyBuilder = getStudyServant()->NewBuilder();
1238 aStudyBuilder->NewCommand(); // There is a transaction
1240 aResult->length( aNames.size() );
1243 // Iterate through all meshes and create mesh objects
1244 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1247 if (i > 0) aPythonDump << ", ";
1250 SMESH::SMESH_Mesh_var mesh = createMesh();
1252 // publish mesh in the study
1253 SALOMEDS::SObject_wrap aSO;
1254 if ( CanPublishInStudy( mesh ) )
1255 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1256 // - as names of meshes are stored in MED file, we use them for data publishing
1257 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1258 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1261 if ( !aSO->_is_nil() ) {
1264 aPythonDump << "mesh_" << i;
1267 // Read mesh data (groups are published automatically by ImportMEDFile())
1268 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1269 ASSERT( meshServant );
1270 SMESH::DriverMED_ReadStatus status1 =
1271 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1272 if (status1 > theStatus)
1273 theStatus = status1;
1275 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1276 meshServant->GetImpl().GetMeshDS()->Modified();
1278 if ( !aStudyBuilder->_is_nil() )
1279 aStudyBuilder->CommitCommand();
1282 // Update Python script
1283 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1285 // Dump creation of groups
1286 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1287 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1289 return aResult._retn();
1292 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1293 SMESH::DriverMED_ReadStatus& theStatus)
1294 throw ( SALOME::SALOME_Exception )
1296 Unexpect aCatch(SALOME_SalomeException);
1297 checkFileReadable( theFileName );
1299 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1303 //=============================================================================
1305 * SMESH_Gen_i::CreateMeshFromSAUV
1307 * Create mesh and import data from SAUV file
1309 //=============================================================================
1311 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1312 SMESH::DriverMED_ReadStatus& theStatus)
1313 throw ( SALOME::SALOME_Exception )
1315 Unexpect aCatch(SALOME_SalomeException);
1316 checkFileReadable( theFileName );
1318 std::string sauvfilename(theFileName);
1319 std::string medfilename(theFileName);
1320 medfilename += ".med";
1323 cmd = "%PYTHONBIN% ";
1328 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1330 system(cmd.c_str());
1331 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1333 cmd = "%PYTHONBIN% ";
1338 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1340 system(cmd.c_str());
1344 //=============================================================================
1346 * SMESH_Gen_i::CreateMeshFromSTL
1348 * Create mesh and import data from STL file
1350 //=============================================================================
1352 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1353 throw ( SALOME::SALOME_Exception )
1355 Unexpect aCatch(SALOME_SalomeException);
1356 checkFileReadable( theFileName );
1358 SMESH::SMESH_Mesh_var aMesh = createMesh();
1361 char bname[ _MAX_FNAME ];
1362 _splitpath( theFileName, NULL, NULL, bname, NULL );
1363 string aFileName = bname;
1365 string aFileName = basename( const_cast<char *>(theFileName) );
1367 // publish mesh in the study
1368 if ( CanPublishInStudy( aMesh ) ) {
1369 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1370 aStudyBuilder->NewCommand(); // There is a transaction
1371 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1372 aStudyBuilder->CommitCommand();
1373 if ( !aSO->_is_nil() ) {
1374 // Update Python script
1375 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1379 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1381 aServant->ImportSTLFile( theFileName );
1382 aServant->GetImpl().GetMeshDS()->Modified();
1383 return aMesh._retn();
1386 //================================================================================
1388 * \brief Create meshes and import data from the CGSN file
1390 //================================================================================
1392 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1393 SMESH::DriverMED_ReadStatus& theStatus)
1394 throw ( SALOME::SALOME_Exception )
1396 Unexpect aCatch(SALOME_SalomeException);
1397 checkFileReadable( theFileName );
1399 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1402 // Retrieve nb meshes from the file
1403 DriverCGNS_Read myReader;
1404 myReader.SetFile( theFileName );
1405 Driver_Mesh::Status aStatus;
1406 int nbMeshes = myReader.GetNbMeshes(aStatus);
1407 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1409 aResult->length( nbMeshes );
1411 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1414 TPythonDump aPythonDump;
1415 aPythonDump << "([";
1417 if (theStatus == SMESH::DRS_OK)
1419 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1420 aStudyBuilder->NewCommand(); // There is a transaction
1424 // Iterate through all meshes and create mesh objects
1425 for ( ; i < nbMeshes; ++i )
1428 if (i > 0) aPythonDump << ", ";
1431 SMESH::SMESH_Mesh_var mesh = createMesh();
1432 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1434 // Read mesh data (groups are published automatically by ImportMEDFile())
1435 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1436 ASSERT( meshServant );
1438 SMESH::DriverMED_ReadStatus status1 =
1439 meshServant->ImportCGNSFile( theFileName, i, meshName );
1440 if (status1 > theStatus)
1441 theStatus = status1;
1443 meshServant->GetImpl().GetMeshDS()->Modified();
1444 // publish mesh in the study
1445 SALOMEDS::SObject_wrap aSO;
1446 if ( CanPublishInStudy( mesh ) )
1447 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1450 if ( !aSO->_is_nil() ) {
1454 aPythonDump << "mesh_" << i;
1457 aStudyBuilder->CommitCommand();
1460 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1462 // Dump creation of groups
1463 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1464 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1466 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1469 return aResult._retn();
1472 //================================================================================
1474 * \brief Create a mesh and import data from a GMF file
1476 //================================================================================
1478 SMESH::SMESH_Mesh_ptr
1479 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1480 CORBA::Boolean theMakeRequiredGroups,
1481 SMESH::ComputeError_out theError)
1482 throw ( SALOME::SALOME_Exception )
1484 Unexpect aCatch(SALOME_SalomeException);
1485 checkFileReadable( theFileName );
1487 SMESH::SMESH_Mesh_var aMesh = createMesh();
1489 char bname[ _MAX_FNAME ];
1490 _splitpath( theFileName, NULL, NULL, bname, NULL );
1491 string aFileName = bname;
1493 string aFileName = basename( const_cast<char *>(theFileName) );
1495 // publish mesh in the study
1496 if ( CanPublishInStudy( aMesh ) ) {
1497 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1498 aStudyBuilder->NewCommand(); // There is a transaction
1499 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1500 aStudyBuilder->CommitCommand();
1501 if ( !aSO->_is_nil() ) {
1502 // Update Python script
1503 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1504 << theFileName << "', "
1505 << theMakeRequiredGroups << " )";
1508 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1510 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1511 aServant->GetImpl().GetMeshDS()->Modified();
1512 return aMesh._retn();
1516 //=============================================================================
1518 * SMESH_Gen_i::IsReadyToCompute
1520 * Returns true if mesh contains enough data to be computed
1522 //=============================================================================
1524 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1525 GEOM::GEOM_Object_ptr theShapeObject )
1526 throw ( SALOME::SALOME_Exception )
1528 Unexpect aCatch(SALOME_SalomeException);
1529 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1531 if ( CORBA::is_nil( theShapeObject ) )
1532 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1533 SALOME::BAD_PARAM );
1535 if ( CORBA::is_nil( theMesh ) )
1536 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1537 SALOME::BAD_PARAM );
1541 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1542 ASSERT( meshServant );
1543 if ( meshServant ) {
1544 // get local TopoDS_Shape
1545 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1546 // call implementation
1547 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1548 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1551 catch ( SALOME_Exception& S_ex ) {
1552 INFOS( "catch exception "<< S_ex.what() );
1557 //================================================================================
1559 * \brief Find SObject for an algo
1561 //================================================================================
1563 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1566 SALOMEDS::Study_var aStudy = getStudyServant();
1567 if ( !aStudy->_is_nil() ) {
1568 // find algo in the study
1569 CORBA::String_var compDataType = ComponentDataType();
1570 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1571 if ( !father->_is_nil() ) {
1572 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1573 for ( ; itBig->More(); itBig->Next() ) {
1574 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1575 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1576 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1577 for ( ; algoIt->More(); algoIt->Next() ) {
1578 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1579 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1580 if ( !CORBA::is_nil( algoIOR )) {
1581 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1582 if ( impl && impl->GetImpl() == algo )
1583 return algoSO._retn();
1585 } // loop on algo SO's
1588 } // SMESH component iterator
1592 return SALOMEDS::SObject::_nil();
1595 //================================================================================
1597 * \brief Return errors of mesh computation
1599 //================================================================================
1601 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1602 GEOM::GEOM_Object_ptr theSubObject )
1603 throw ( SALOME::SALOME_Exception )
1605 Unexpect aCatch(SALOME_SalomeException);
1606 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1608 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1609 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1611 if ( CORBA::is_nil( theMesh ) )
1612 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1614 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1616 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1619 if(theMesh->HasShapeToMesh())
1620 shape = GeomObjectToShape( theSubObject );
1622 shape = SMESH_Mesh::PseudoShape();
1624 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1626 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1629 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1630 const bool includeSelf = true, complexShapeFirst = true;
1631 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1633 while ( smIt->more() )
1636 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1638 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1639 if ( error && !error->IsOK() )
1641 if ( !( error->myAlgo ) &&
1642 !( error->myAlgo = sm->GetAlgo() ))
1644 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1645 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1646 errStruct.comment = error->myComment.c_str();
1647 errStruct.subShapeID = sm->GetId();
1648 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1649 if ( !algoSO->_is_nil() ) {
1650 CORBA::String_var algoName = algoSO->GetName();
1651 errStruct.algoName = algoName;
1654 errStruct.algoName = error->myAlgo->GetName();
1656 errStruct.hasBadMesh = error->HasBadElems();
1659 error_array->length( nbErr );
1662 catch ( SALOME_Exception& S_ex ) {
1663 INFOS( "catch exception "<< S_ex.what() );
1666 return error_array._retn();
1669 //================================================================================
1671 * \brief Return mesh elements preventing computation of a subshape
1673 //================================================================================
1675 SMESH::MeshPreviewStruct*
1676 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1677 CORBA::Short theSubShapeID )
1678 throw ( SALOME::SALOME_Exception )
1680 Unexpect aCatch(SALOME_SalomeException);
1681 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1683 if ( CORBA::is_nil( theMesh ) )
1684 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1686 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1689 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1691 // mesh implementation
1692 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1693 // submesh by subshape id
1694 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1697 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1698 if ( error && error->HasBadElems() )
1700 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1701 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1703 // get nodes of elements and count elements
1704 TNode2LocalIDMap mapNode2LocalID;
1705 list< TNodeLocalID > connectivity;
1706 int i, nbElements = 0, nbConnNodes = 0;
1708 const list<const SMDS_MeshElement*>& badElems =
1709 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1710 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1711 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1712 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1714 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1715 while ( nIt->more() )
1716 connectivity.push_back
1717 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1719 // fill node coords and assign local ids to the nodes
1720 int nbNodes = mapNode2LocalID.size();
1721 result->nodesXYZ.length( nbNodes );
1722 TNodeLocalID node2ID = mapNode2LocalID.begin();
1723 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1724 node2ID->second = i;
1725 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1726 result->nodesXYZ[i].x = node->X();
1727 result->nodesXYZ[i].y = node->Y();
1728 result->nodesXYZ[i].z = node->Z();
1730 // fill connectivity
1731 result->elementConnectivities.length( nbConnNodes );
1732 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1733 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1734 result->elementConnectivities[i] = (*connIt)->second;
1736 // fill element types
1737 result->elementTypes.length( nbElements );
1738 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1740 const SMDS_MeshElement* elem = *elemIt;
1741 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1742 result->elementTypes[i].isPoly = elem->IsPoly();
1743 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1749 catch ( SALOME_Exception& S_ex ) {
1750 INFOS( "catch exception "<< S_ex.what() );
1753 return result._retn();
1756 //================================================================================
1758 * \brief Create a group of elements preventing computation of a sub-shape
1760 //================================================================================
1762 SMESH::ListOfGroups*
1763 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1764 CORBA::Short theSubShapeID,
1765 const char* theGroupName )
1766 throw ( SALOME::SALOME_Exception )
1768 Unexpect aCatch(SALOME_SalomeException);
1770 SMESH::ListOfGroups_var groups;
1772 if ( CORBA::is_nil( theMesh ) )
1773 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1776 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1778 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1779 TPythonDump() << groups << " = " << this
1780 << ".MakeGroupsOfBadInputElements( "
1781 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1784 catch ( SALOME_Exception& S_ex ) {
1785 INFOS( "catch exception "<< S_ex.what() );
1787 return groups._retn();
1790 //================================================================================
1792 * \brief Returns errors of hypotheses definition
1793 * \param theMesh - the mesh
1794 * \param theSubObject - the main or sub- shape
1795 * \retval SMESH::algo_error_array* - sequence of errors
1797 //================================================================================
1799 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1800 GEOM::GEOM_Object_ptr theSubObject )
1801 throw ( SALOME::SALOME_Exception )
1803 Unexpect aCatch(SALOME_SalomeException);
1804 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1806 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1807 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1809 if ( CORBA::is_nil( theMesh ) )
1810 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1812 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1814 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1815 ASSERT( meshServant );
1816 if ( meshServant ) {
1817 TopoDS_Shape myLocShape;
1818 if(theMesh->HasShapeToMesh())
1819 myLocShape = GeomObjectToShape( theSubObject );
1821 myLocShape = SMESH_Mesh::PseudoShape();
1823 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1824 list< ::SMESH_Gen::TAlgoStateError > error_list;
1825 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1826 // call ::SMESH_Gen::GetAlgoState()
1827 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1828 error_array->length( error_list.size() );
1830 for ( error = error_list.begin(); error != error_list.end(); ++error )
1832 // fill AlgoStateError structure
1833 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1834 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1835 errStruct.algoDim = error->_algoDim;
1836 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1837 errStruct.algoName = "";
1838 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1839 if ( !algoSO->_is_nil() ) {
1840 CORBA::String_var algoName = algoSO->GetName();
1841 errStruct.algoName = algoName.in();
1846 catch ( SALOME_Exception& S_ex ) {
1847 INFOS( "catch exception "<< S_ex.what() );
1849 return error_array._retn();
1852 //=============================================================================
1854 * SMESH_Gen_i::GetSubShapesId
1856 * Get sub-shapes unique ID's list
1858 //=============================================================================
1861 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1862 const SMESH::object_array& theListOfSubShapeObject )
1863 throw ( SALOME::SALOME_Exception )
1865 Unexpect aCatch(SALOME_SalomeException);
1866 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1868 SMESH::long_array_var shapesId = new SMESH::long_array;
1871 if ( CORBA::is_nil( theMainShapeObject ) )
1872 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1876 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1877 TopTools_IndexedMapOfShape myIndexToShape;
1878 TopExp::MapShapes(myMainShape,myIndexToShape);
1880 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1882 GEOM::GEOM_Object_var aShapeObject
1883 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1884 if ( CORBA::is_nil( aShapeObject ) )
1885 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1886 SALOME::BAD_PARAM );
1888 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1889 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1891 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1892 setId.insert(myIndexToShape.FindIndex(F));
1893 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1895 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1897 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1898 setId.insert(myIndexToShape.FindIndex(E));
1899 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1901 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1903 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1904 setId.insert(myIndexToShape.FindIndex(V));
1905 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1908 shapesId->length(setId.size());
1909 set<int>::iterator iind;
1911 for (iind = setId.begin(); iind != setId.end(); iind++)
1913 if(MYDEBUG) SCRUTE((*iind));
1914 shapesId[i] = (*iind);
1915 if(MYDEBUG) SCRUTE(shapesId[i]);
1919 catch (SALOME_Exception& S_ex)
1921 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1924 return shapesId._retn();
1927 //=============================================================================
1929 * SMESH_Gen_i::Compute
1931 * Compute mesh on a shape
1933 //=============================================================================
1935 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1936 GEOM::GEOM_Object_ptr theShapeObject )
1937 throw ( SALOME::SALOME_Exception )
1940 Unexpect aCatch(SALOME_SalomeException);
1941 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1943 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1944 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1945 SALOME::BAD_PARAM );
1947 if ( CORBA::is_nil( theMesh ) )
1948 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1949 SALOME::BAD_PARAM );
1951 // Update Python script
1952 TPythonDump() << "isDone = " << this << ".Compute( "
1953 << theMesh << ", " << theShapeObject << ")";
1957 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1958 ASSERT( meshServant );
1959 if ( meshServant ) {
1960 meshServant->Load();
1961 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
1962 meshServant->CheckGeomModif();
1963 // get local TopoDS_Shape
1964 TopoDS_Shape myLocShape;
1965 if(theMesh->HasShapeToMesh())
1966 myLocShape = GeomObjectToShape( theShapeObject );
1968 myLocShape = SMESH_Mesh::PseudoShape();
1969 // call implementation compute
1970 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1971 myGen.PrepareCompute( myLocMesh, myLocShape );
1972 int how = ::SMESH_Gen::COMPACT_MESH;
1973 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1974 how |= ::SMESH_Gen::SHAPE_ONLY;
1975 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1976 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1977 myLocMesh.GetMeshDS()->Modified();
1978 UpdateIcons( theMesh );
1980 HighLightInvalid( theMesh, /*isInvalid=*/false );
1984 catch ( std::bad_alloc ) {
1985 INFOS( "Compute(): lack of memory" );
1987 catch ( SALOME_Exception& S_ex ) {
1988 INFOS( "Compute(): catch exception "<< S_ex.what() );
1991 INFOS( "Compute(): unknown exception " );
1996 //=============================================================================
1998 * SMESH_Gen_i::CancelCompute
2000 * Cancel Compute mesh on a shape
2002 //=============================================================================
2004 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2005 GEOM::GEOM_Object_ptr theShapeObject )
2007 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2009 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2010 TopoDS_Shape myLocShape;
2011 if(theMesh->HasShapeToMesh())
2012 myLocShape = GeomObjectToShape( theShapeObject );
2014 myLocShape = SMESH_Mesh::PseudoShape();
2015 myGen.CancelCompute( myLocMesh, myLocShape);
2019 //=============================================================================
2021 * SMESH_Gen_i::Precompute
2023 * Compute mesh as preview till indicated dimension on shape
2025 //=============================================================================
2027 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2028 GEOM::GEOM_Object_ptr theShapeObject,
2029 SMESH::Dimension theDimension,
2030 SMESH::long_array& theShapesId)
2031 throw ( SALOME::SALOME_Exception )
2033 Unexpect aCatch(SALOME_SalomeException);
2034 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2036 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2037 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2038 SALOME::BAD_PARAM );
2040 if ( CORBA::is_nil( theMesh ) )
2041 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2042 SALOME::BAD_PARAM );
2044 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2047 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2048 meshServant->Load();
2049 ASSERT( meshServant );
2050 if ( meshServant ) {
2051 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2052 meshServant->CheckGeomModif();
2053 // get local TopoDS_Shape
2054 TopoDS_Shape myLocShape;
2055 if(theMesh->HasShapeToMesh())
2056 myLocShape = GeomObjectToShape( theShapeObject );
2058 return result._retn();;
2060 // call implementation compute
2061 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2063 ::MeshDimension aDim = (MeshDimension)theDimension;
2064 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2066 int nbShapeId = shapeIds.size();
2067 theShapesId.length( nbShapeId );
2068 // iterates on shapes and collect mesh entities into mesh preview
2069 TSetOfInt::const_iterator idIt = shapeIds.begin();
2070 TSetOfInt::const_iterator idEnd = shapeIds.end();
2071 std::map< int, int > mapOfShIdNb;
2072 std::set< SMESH_TLink > setOfEdge;
2073 std::list< SMDSAbs_ElementType > listOfElemType;
2074 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2075 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2076 TNode2LocalIDMap mapNode2LocalID;
2077 list< TNodeLocalID > connectivity;
2078 int i, nbConnNodes = 0;
2079 std::set< const SMESH_subMesh* > setOfVSubMesh;
2080 // iterates on shapes
2081 for ( ; idIt != idEnd; idIt++ )
2083 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2085 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2086 if ( !sm || !sm->IsMeshComputed() )
2089 const TopoDS_Shape& aSh = sm->GetSubShape();
2090 const int shDim = myGen.GetShapeDim( aSh );
2091 if ( shDim < 1 || shDim > theDimension )
2094 mapOfShIdNb[ *idIt ] = 0;
2095 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2097 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2098 if ( !smDS ) continue;
2100 if ( theDimension == SMESH::DIM_2D )
2102 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2103 while ( faceIt->more() )
2105 const SMDS_MeshElement* face = faceIt->next();
2106 int aNbNode = face->NbNodes();
2108 aNbNode /= 2; // do not take into account additional middle nodes
2110 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2111 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2113 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2114 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2116 listOfElemType.push_back( SMDSAbs_Edge );
2117 connectivity.push_back
2118 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2119 connectivity.push_back
2120 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2126 else if ( theDimension == SMESH::DIM_1D )
2128 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2129 while ( nodeIt->more() )
2131 listOfElemType.push_back( SMDSAbs_Node );
2132 connectivity.push_back
2133 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2135 // add corner nodes by first vertex from edge
2136 SMESH_subMeshIteratorPtr edgeSmIt =
2137 sm->getDependsOnIterator(/*includeSelf*/false,
2138 /*complexShapeFirst*/false);
2139 while ( edgeSmIt->more() )
2141 SMESH_subMesh* vertexSM = edgeSmIt->next();
2142 // check that vertex is not already treated
2143 if ( !setOfVSubMesh.insert( vertexSM ).second )
2145 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2148 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2149 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2150 while ( nodeIt->more() )
2152 listOfElemType.push_back( SMDSAbs_Node );
2153 connectivity.push_back
2154 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2160 // fill node coords and assign local ids to the nodes
2161 int nbNodes = mapNode2LocalID.size();
2162 result->nodesXYZ.length( nbNodes );
2163 TNodeLocalID node2ID = mapNode2LocalID.begin();
2164 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2165 node2ID->second = i;
2166 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2167 result->nodesXYZ[i].x = node->X();
2168 result->nodesXYZ[i].y = node->Y();
2169 result->nodesXYZ[i].z = node->Z();
2171 // fill connectivity
2172 result->elementConnectivities.length( nbConnNodes );
2173 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2174 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2175 result->elementConnectivities[i] = (*connIt)->second;
2178 // fill element types
2179 result->elementTypes.length( listOfElemType.size() );
2180 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2181 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2182 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2184 SMDSAbs_ElementType elemType = *typeIt;
2185 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2186 result->elementTypes[i].isPoly = false;
2187 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2190 // correct number of shapes
2191 theShapesId.length( mapOfShIdNb.size() );
2195 catch ( std::bad_alloc ) {
2196 INFOS( "Precompute(): lack of memory" );
2198 catch ( SALOME_Exception& S_ex ) {
2199 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2202 INFOS( "Precompute(): unknown exception " );
2204 return result._retn();
2208 //=============================================================================
2210 * SMESH_Gen_i::Evaluate
2212 * Evaluate mesh on a shape
2214 //=============================================================================
2216 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2217 GEOM::GEOM_Object_ptr theShapeObject)
2218 // SMESH::long_array& theNbElems)
2219 throw ( SALOME::SALOME_Exception )
2221 Unexpect aCatch(SALOME_SalomeException);
2222 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2224 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2225 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2226 SALOME::BAD_PARAM );
2228 if ( CORBA::is_nil( theMesh ) )
2229 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2230 SALOME::BAD_PARAM );
2232 SMESH::long_array_var nbels = new SMESH::long_array;
2233 nbels->length(SMESH::Entity_Last);
2234 int i = SMESH::Entity_Node;
2235 for (; i < SMESH::Entity_Last; i++)
2238 // Update Python script
2239 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2240 << theMesh << ", " << theShapeObject << ")";
2244 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2245 ASSERT( meshServant );
2246 if ( meshServant ) {
2247 meshServant->Load();
2248 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2249 meshServant->CheckGeomModif();
2250 // get local TopoDS_Shape
2251 TopoDS_Shape myLocShape;
2252 if(theMesh->HasShapeToMesh())
2253 myLocShape = GeomObjectToShape( theShapeObject );
2255 myLocShape = SMESH_Mesh::PseudoShape();
2256 // call implementation compute
2257 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2258 MapShapeNbElems aResMap;
2259 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2260 MapShapeNbElemsItr anIt = aResMap.begin();
2261 for(; anIt!=aResMap.end(); anIt++) {
2262 const vector<int>& aVec = (*anIt).second;
2263 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2264 int nbElem = aVec[i];
2265 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2267 SMESH_subMesh* sm = anIt->first;
2268 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2269 const SMESH_Algo* algo = sm->GetAlgo();
2270 if ( (algo && !error.get()) || error->IsOK() )
2271 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2275 nbels[i] += aVec[i];
2279 return nbels._retn();
2282 catch ( std::bad_alloc ) {
2283 INFOS( "Evaluate(): lack of memory" );
2285 catch ( SALOME_Exception& S_ex ) {
2286 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2289 INFOS( "Evaluate(): unknown exception " );
2292 return nbels._retn();
2295 //================================================================================
2297 * \brief Return geometrical object the given element is built on
2298 * \param theMesh - the mesh the element is in
2299 * \param theElementID - the element ID
2300 * \param theGeomName - the name of the result geom object if it is not yet published
2301 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2303 //================================================================================
2305 GEOM::GEOM_Object_ptr
2306 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2307 CORBA::Long theElementID,
2308 const char* theGeomName)
2309 throw ( SALOME::SALOME_Exception )
2311 Unexpect aCatch(SALOME_SalomeException);
2313 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2314 if ( !geom->_is_nil() ) {
2315 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2316 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2318 // try to find the corresponding SObject
2319 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2320 if ( SObj->_is_nil() ) // submesh can be not found even if published
2322 // try to find published submesh
2323 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2324 if ( !geom->IsMainShape() && list->length() == 1 ) {
2325 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2326 SALOMEDS::ChildIterator_wrap it;
2327 if ( !mainSO->_is_nil() ) {
2328 it = getStudyServant()->NewChildIterator( mainSO );
2330 if ( !it->_is_nil() ) {
2331 for ( it->InitEx(true); it->More(); it->Next() ) {
2332 SALOMEDS::SObject_wrap so = it->Value();
2333 CORBA::Object_var obj = SObjectToObject( so );
2334 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2335 if ( !subGeom->_is_nil() ) {
2336 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2337 if ( subList->length() == 1 && list[0] == subList[0] ) {
2347 if ( SObj->_is_nil() ) // publish a new subshape
2348 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2350 // return only published geometry
2351 if ( !SObj->_is_nil() ) {
2352 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2353 CORBA::Object_var obj = SObjectToObject( SObj );
2354 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2358 return GEOM::GEOM_Object::_nil();
2361 //================================================================================
2363 * \brief Return geometrical object the given element is built on.
2364 * \param theMesh - the mesh the element is in
2365 * \param theElementID - the element ID
2366 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2368 //================================================================================
2370 GEOM::GEOM_Object_ptr
2371 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2372 CORBA::Long theElementID)
2373 throw ( SALOME::SALOME_Exception )
2375 Unexpect aCatch(SALOME_SalomeException);
2376 if ( CORBA::is_nil( theMesh ) )
2377 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2379 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2380 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2382 // get a core mesh DS
2383 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2384 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2386 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2387 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2388 // find the element in mesh
2389 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2390 // find a shape id by the element
2391 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2392 // get a geom object by the shape id
2393 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2394 if ( geom->_is_nil() ) {
2395 // try to find a published sub-shape
2396 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2397 SALOMEDS::ChildIterator_wrap it;
2398 if ( !mainSO->_is_nil() ) {
2399 it = getStudyServant()->NewChildIterator( mainSO );
2401 if ( !it->_is_nil() ) {
2402 for ( it->InitEx(true); it->More(); it->Next() ) {
2403 SALOMEDS::SObject_wrap so = it->Value();
2404 CORBA::Object_var obj = SObjectToObject( so );
2405 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2406 if ( !subGeom->_is_nil() ) {
2407 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2408 if ( subList->length() == 1 && shapeID == subList[0] ) {
2416 if ( geom->_is_nil() ) {
2418 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2419 if ( !op->_is_nil() )
2420 geom = op->GetSubShape( mainShape, shapeID );
2425 if ( !geom->_is_nil() ) {
2426 GeomObjectToShape( geom ); // let geom client remember the found shape
2427 return geom._retn();
2432 return GEOM::GEOM_Object::_nil();
2435 //================================================================================
2437 * SMESH_Gen_i::Concatenate
2439 * Concatenate the given meshes into one mesh
2441 //================================================================================
2443 SMESH::SMESH_Mesh_ptr
2444 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2445 CORBA::Boolean theUniteIdenticalGroups,
2446 CORBA::Boolean theMergeNodesAndElements,
2447 CORBA::Double theMergeTolerance,
2448 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2449 throw ( SALOME::SALOME_Exception )
2451 return ConcatenateCommon(theMeshesArray,
2452 theUniteIdenticalGroups,
2453 theMergeNodesAndElements,
2459 //================================================================================
2461 * SMESH_Gen_i::ConcatenateWithGroups
2463 * Concatenate the given meshes into one mesh
2464 * Create the groups of all elements from initial meshes
2466 //================================================================================
2468 SMESH::SMESH_Mesh_ptr
2469 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2470 CORBA::Boolean theUniteIdenticalGroups,
2471 CORBA::Boolean theMergeNodesAndElements,
2472 CORBA::Double theMergeTolerance,
2473 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2474 throw ( SALOME::SALOME_Exception )
2476 return ConcatenateCommon(theMeshesArray,
2477 theUniteIdenticalGroups,
2478 theMergeNodesAndElements,
2484 //================================================================================
2486 * SMESH_Gen_i::ConcatenateCommon
2488 * Concatenate the given meshes into one mesh
2490 //================================================================================
2492 SMESH::SMESH_Mesh_ptr
2493 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2494 CORBA::Boolean theUniteIdenticalGroups,
2495 CORBA::Boolean theMergeNodesAndElements,
2496 CORBA::Double theMergeTolerance,
2497 CORBA::Boolean theCommonGroups,
2498 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2499 throw ( SALOME::SALOME_Exception )
2501 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2502 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2504 // create mesh if theMeshToAppendTo not provided
2505 SMESH::SMESH_Mesh_var newMesh;
2506 if ( CORBA::is_nil( theMeshToAppendTo ))
2507 newMesh = CreateEmptyMesh();
2509 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2510 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2511 if ( !newImpl ) return newMesh._retn();
2514 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2515 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2517 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2518 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2519 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2520 TGroupsMap groupsMap;
2521 TListOfNewGroups listOfNewGroups;
2523 if ( !CORBA::is_nil( theMeshToAppendTo ))
2525 // fill groupsMap with existing groups
2526 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2527 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2529 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2530 if ( !group->_is_nil() )
2532 CORBA::String_var name = group->GetName();
2533 SMESH::ElementType type = group->GetType();
2534 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2539 ::SMESH_MeshEditor newEditor( &locMesh );
2540 ::SMESH_MeshEditor::ElemFeatures elemType;
2542 // loop on sub-meshes
2543 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2545 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2546 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2547 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2548 if ( !initImpl ) continue;
2549 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2553 // assure that IDs increment by one during iteration
2554 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2555 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2556 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2557 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2559 initMeshDS->Modified();
2560 initMeshDS->CompactMesh();
2563 // remember nb of elements before filling in
2564 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2568 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2569 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2570 while ( elemIt->more() )
2572 SMESH_NodeXYZ node = elemIt->next();
2573 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2578 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2579 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2581 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2582 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2583 while ( elemIt->more() )
2585 const SMDS_MeshElement* elem = elemIt->next();
2586 elemType.myNodes.resize( elem->NbNodes() );
2588 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2589 for ( int k = 0; itNodes->more(); k++)
2591 const SMDS_MeshNode* node = itNodes->next();
2592 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2595 // creates a corresponding element on existent nodes in new mesh
2596 newElems[ elem->GetID() ] =
2597 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2599 newEditor.ClearLastCreated(); // forget the history
2602 // create groups of just added elements
2603 SMESH::SMESH_Group_var newGroup;
2604 SMESH::ElementType groupType;
2605 if ( theCommonGroups )
2608 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2609 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2610 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2611 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2614 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2616 for( groupType = SMESH::NODE;
2617 groupType < SMESH::NB_ELEMENT_TYPES;
2618 groupType = (SMESH::ElementType)( groupType + 1 ))
2620 if ( curState[ groupType ] <= prevState[ groupType ])
2621 continue; // no elements of groupType added from the i-th mesh
2623 // make a group name
2624 std::string groupName = "Gr";
2625 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2627 CORBA::String_var name = meshSO->GetName();
2631 groupName += typeNames[ groupType ];
2633 // make and fill a group
2634 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2635 std::vector< const SMDS_MeshElement* > & elemVec =
2636 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2637 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2639 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2641 for ( size_t j = 0; j < elemVec.size(); ++j )
2643 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2644 grpDS->Add( elemVec[j] );
2648 listOfNewGroups.clear();
2649 listOfNewGroups.push_back( newGroup );
2650 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2655 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2659 SMESH::SMESH_GroupBase_ptr group;
2660 CORBA::String_var groupName;
2661 SMESH::long_array_var newIDs = new SMESH::long_array();
2663 // loop on groups of a source mesh
2664 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2665 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2667 group = listOfGroups[iG];
2668 groupType = group->GetType();
2669 groupName = group->GetName();
2670 std::string name = groupName.in();
2672 // convert a list of IDs
2673 newIDs->length( group->Size() );
2674 std::vector< const SMDS_MeshElement* > & elemVec =
2675 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2676 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2678 while ( itGrElems->more() )
2680 const SMDS_MeshElement* elem = itGrElems->next();
2681 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2683 newIDs[ nbElems++ ] = newElem->GetID();
2685 newIDs->length( nbElems );
2687 // check that a current group name and type don't have identical ones in final mesh
2688 listOfNewGroups.clear();
2689 TNameAndType nameAndType( name, groupType );
2690 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2691 if ( anIter == groupsMap.end() )
2693 // add a new group in the mesh
2694 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2695 newGroup->Add( newIDs );
2697 listOfNewGroups.push_back( newGroup );
2698 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2700 else if ( theUniteIdenticalGroups )
2702 // unite identical groups
2703 TListOfNewGroups& aNewGroups = anIter->second;
2704 aNewGroups.front()->Add( newIDs );
2708 // rename identical groups
2709 newGroup = newImpl->CreateGroup( groupType, groupName );
2710 newGroup->Add( newIDs );
2712 TListOfNewGroups& newGroups = anIter->second;
2713 std::string newGroupName;
2714 if ( newGroups.size() == 1 )
2716 newGroupName = name + "_1";
2717 newGroups.front()->SetName( newGroupName.c_str() );
2719 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2720 newGroup->SetName( newGroupName.c_str() );
2721 newGroups.push_back( newGroup );
2724 } // if an IDSource is a mesh
2727 if ( theMergeNodesAndElements ) // merge nodes
2729 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2730 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2731 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2732 /*SeparateCornersAndMedium=*/ false );
2733 newEditor.MergeNodes( groupsOfNodes );
2735 newEditor.MergeEqualElements();
2738 // Update Python script
2739 pythonDump << newMesh << " = " << this
2740 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2741 << theMeshesArray << ", "
2742 << theUniteIdenticalGroups << ", "
2743 << theMergeNodesAndElements << ", "
2744 << TVar( theMergeTolerance ) << ", "
2745 << theMeshToAppendTo << " )";
2747 pPythonDump.reset(); // enable python dump from GetGroups()
2749 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2750 if ( !newMesh->_is_nil() )
2752 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2755 // IPAL21468 Change icon of compound because it need not be computed.
2756 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2757 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2759 newMeshDS->Modified();
2761 return newMesh._retn();
2764 //================================================================================
2766 * \brief Create a mesh by copying a part of another mesh
2767 * \param meshPart - a part of mesh to copy
2768 * \param toCopyGroups - to create in the new mesh groups
2769 * the copied elements belongs to
2770 * \param toKeepIDs - to preserve IDs of the copied elements or not
2771 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2773 //================================================================================
2775 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2776 const char* meshName,
2777 CORBA::Boolean toCopyGroups,
2778 CORBA::Boolean toKeepIDs)
2779 throw ( SALOME::SALOME_Exception )
2781 Unexpect aCatch(SALOME_SalomeException);
2783 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2784 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2786 // 1. Get source mesh
2788 if ( CORBA::is_nil( meshPart ))
2789 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2791 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2792 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2794 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2796 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2798 // 2. Make a new mesh
2800 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2801 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2803 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2804 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2805 if ( !meshSO->_is_nil() )
2807 SetName( meshSO, meshName, "Mesh" );
2808 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2810 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2811 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2812 ::SMESH_MeshEditor::ElemFeatures elemType;
2814 // 3. Get elements to copy
2816 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2817 TIDSortedElemSet srcElems;
2818 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2819 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2822 srcElemIt = srcMeshDS->elementsIterator();
2823 srcNodeIt = srcMeshDS->nodesIterator();
2827 SMESH::long_array_var ids = meshPart->GetIDs();
2828 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2830 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2831 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2832 srcElems.insert( elem );
2836 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2837 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2838 srcElems.insert( elem );
2840 if ( srcElems.empty() )
2841 return newMesh._retn();
2843 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2844 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2849 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2850 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2851 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2853 const SMDS_MeshNode *nSrc, *nTgt;
2854 vector< const SMDS_MeshNode* > nodes;
2855 while ( srcElemIt->more() )
2857 const SMDS_MeshElement * elem = srcElemIt->next();
2859 nodes.resize( elem->NbNodes());
2860 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2862 for ( iN = 0; nIt->more(); ++iN )
2864 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2865 nTgt = newMeshDS->FindNode( nSrc->GetID());
2867 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2872 for ( iN = 0; nIt->more(); ++iN )
2874 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2875 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2877 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2878 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2882 if ( elem->GetType() != SMDSAbs_Node )
2884 elemType.Init( elem, /*basicOnly=*/false );
2885 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2887 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2888 if ( toCopyGroups && !toKeepIDs )
2889 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2891 } // while ( srcElemIt->more() )
2893 // 4(b). Copy free nodes
2895 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2897 while ( srcNodeIt->more() )
2899 nSrc = srcNodeIt->next();
2900 if ( nSrc->NbInverseElements() == 0 )
2903 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2905 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2912 int nbNewGroups = 0;
2915 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2916 while ( gIt->more() )
2918 SMESH_Group* group = gIt->next();
2919 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2921 // Check group type. We copy nodal groups containing nodes of copied element
2922 SMDSAbs_ElementType groupType = groupDS->GetType();
2923 if ( groupType != SMDSAbs_Node &&
2924 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2925 continue; // group type differs from types of meshPart
2927 // Find copied elements in the group
2928 vector< const SMDS_MeshElement* > groupElems;
2929 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2932 const SMDS_MeshElement* foundElem;
2933 if ( groupType == SMDSAbs_Node )
2935 while ( eIt->more() )
2936 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2937 groupElems.push_back( foundElem );
2941 while ( eIt->more() )
2942 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2943 groupElems.push_back( foundElem );
2948 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2949 if ( e2eMap.empty() ) continue;
2950 int minID = e2eMap.begin()->first->GetID();
2951 int maxID = e2eMap.rbegin()->first->GetID();
2952 TE2EMap::iterator e2e;
2953 while ( eIt->more() && groupElems.size() < e2eMap.size())
2955 const SMDS_MeshElement* e = eIt->next();
2956 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2957 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2958 groupElems.push_back( e2e->second );
2962 if ( !groupElems.empty() )
2964 SMESH::SMESH_Group_var newGroupObj =
2965 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2966 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2968 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2969 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2970 for ( unsigned i = 0; i < groupElems.size(); ++i )
2971 smdsGroup.Add( groupElems[i] );
2979 newMeshDS->Modified();
2981 *pyDump << newMesh << " = " << this
2982 << ".CopyMesh( " << meshPart << ", "
2983 << "'" << meshName << "', "
2984 << toCopyGroups << ", "
2985 << toKeepIDs << ")";
2987 pyDumpDeleter.reset(); // allow dump in GetGroups()
2989 if ( nbNewGroups > 0 ) // dump created groups
2990 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2992 return newMesh._retn();
2996 namespace // utils for CopyMeshWithGeom()
2998 typedef std::map< std::string, std::string > TStr2StrMap;
2999 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3000 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3001 typedef std::map< std::string, int > TName2IndexMap;
3003 //================================================================================
3005 * \brief Return a new sub-shape corresponding to an old one
3007 //================================================================================
3011 SMESH_Mesh_i* mySrcMesh_i;
3012 SMESH_Mesh_i* myNewMesh_i;
3013 SMESH_Gen_i* myGen_i;
3017 TStr2StrMap myOld2NewEntryMap; // map of study entries
3019 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3020 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3021 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3024 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3026 // not directly relating to shape search
3027 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3029 //================================================================================
3031 * \brief Constructor
3033 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3034 SMESH_Mesh_i* newMesh_i,
3035 SMESH_Gen_i* smeshGen_i )
3036 : mySrcMesh_i( srcMesh_i ),
3037 myNewMesh_i( newMesh_i ),
3038 myGen_i ( smeshGen_i ),
3039 myToPublish( smeshGen_i->IsEnablePublish() ),
3040 myGIPMapDone( false )
3042 // retrieve from the study shape mapping made thanks to
3043 // "Set presentation parameters and sub-shapes from arguments" option
3045 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3046 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3047 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3048 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3049 if ( newSO->_is_nil() )
3051 myToPublish = false;
3054 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3056 CORBA::String_var oldEntry = oldSO->GetID();
3057 CORBA::String_var newEntry = newSO->GetID();
3058 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3059 std::string( newEntry.in() )));
3060 std::string newMainEntry = newEntry.in();
3062 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3063 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3064 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3065 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3066 /*groupsOnly=*/false );
3067 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3069 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3070 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3071 bool refFound = false;
3072 for ( ; anIter->More(); anIter->Next() )
3074 SALOMEDS::SObject_wrap so = anIter->Value();
3075 if ( so->ReferencedObject( oldSO.inout() ))
3077 oldEntry = oldSO->GetID();
3078 newEntry = newSO->GetID();
3079 if (( refFound = ( newMainEntry != oldEntry.in() )))
3080 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3081 std::string( newEntry.in() )));
3086 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3087 if ( father->_is_equivalent( mainShapeNew ))
3089 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3090 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3091 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3092 CORBA::String_var name = newSO->GetName();
3094 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3100 //================================================================================
3102 * \brief Find a new sub-shape corresponding to an old one
3104 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3107 return GEOM::GEOM_Object::_duplicate( oldShape );
3109 GEOM::GEOM_Object_var newShape;
3111 if ( CORBA::is_nil( oldShape ))
3112 return newShape._retn();
3114 if ( !isChildOfOld( oldShape ))
3115 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3117 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3118 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3120 // try to find by entry or name
3123 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3124 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3125 if ( o2nID != myOld2NewEntryMap.end() )
3127 newShape = getShapeByEntry( o2nID->second );
3129 if ( newShape->_is_nil() )
3131 CORBA::String_var name = oldShape->GetName();
3132 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3133 if ( n2ind != myName2SubshapeIndex.end() )
3135 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3136 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3137 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3138 if ( oldIndices->length() == 0 ||
3139 newIndices->length() == 0 ||
3140 getShapeType( myNewMesh_i, newIndices[0] ) !=
3141 getShapeType( mySrcMesh_i, oldIndices[0] ))
3142 newShape = GEOM::GEOM_Object::_nil();
3147 if ( newShape->_is_nil() )
3149 // try to construct a new sub-shape using myGIPMap
3151 std::vector< int > newIndices;
3152 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3153 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3155 findNewIDs( oldIndices[i], newIndices );
3157 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3160 newShape = getInPlace( oldShape );
3162 if ( !newIndices.empty() && newShape->_is_nil() )
3164 // search for a sub-shape with same ids
3165 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3166 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3167 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3168 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3170 if ( newShape->_is_nil() )
3173 // create a new shape
3174 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3176 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3178 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3179 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3181 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3182 newIndicesList->length( newIndices.size() );
3183 for ( size_t i = 0; i < newIndices.size(); ++i )
3184 newIndicesList[ i ] = newIndices[ i ];
3185 grOp->UnionIDs( newShape, newIndicesList );
3189 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3190 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3199 if ( !newShape->_is_nil() && myToPublish )
3201 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3202 if ( !newEntry.in() || !newEntry.in()[0] )
3204 CORBA::String_var name = oldShape->GetName();
3205 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3206 newEntry = newShape->GetStudyEntry();
3207 oldEntry = oldShape->GetStudyEntry();
3208 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3209 std::string( newEntry.in() )));
3213 return newShape._retn();
3216 //================================================================================
3218 * \brief Return a study entry of a new shape by study entry of the old one
3220 std::string FindNew( const std::string & oldEntry )
3225 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3226 if ( o2nID != myOld2NewEntryMap.end() )
3227 return o2nID->second;
3229 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3230 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3233 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3234 if ( newShape->_is_nil() )
3235 return std::string();
3237 CORBA::String_var newEntry = newShape->GetStudyEntry();
3238 return newEntry.in();
3241 //================================================================================
3243 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3244 * Return zero if not found or there are more than one new ID
3246 int FindNew( int oldID )
3255 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3257 if ( myGIPMap[ oldID ].length() == 1 )
3259 newID = myGIPMap[ oldID ][ 0 ];
3261 else if ( myGIPMap[ oldID ].length() > 1 &&
3262 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3264 // select a meshed VERTEX
3265 SMESH_subMesh* newSM;
3266 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3267 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3268 ( !newSM->IsEmpty() ))
3269 newID = myGIPMap[ oldID ][ i ];
3275 //================================================================================
3277 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3278 * Return zero if the old shape is not kept as is in the new shape.
3280 int FindNewNotChanged( SMESH_subMesh* oldSM )
3283 return oldSM->GetId();
3285 int newID = FindNew( oldSM->GetId() );
3289 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3293 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3294 // one new sub-shape of the same type.
3296 if ( oldSM->DependsOn().size() !=
3297 newSM->DependsOn().size() )
3300 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3301 while ( srcSMIt->more() )
3303 oldSM = srcSMIt->next();
3304 int newSubID = FindNew( oldSM->GetId() );
3305 if ( getShapeType( myNewMesh_i, newSubID ) !=
3306 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3312 //================================================================================
3314 * \brief Return shape by study entry
3316 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3318 GEOM::GEOM_Object_var shape;
3319 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3320 if ( !so->_is_nil() )
3322 CORBA::Object_var obj = so->GetObject();
3323 shape = GEOM::GEOM_Object::_narrow( obj );
3325 return shape._retn();
3328 //================================================================================
3330 * \brief Fill myGIPMap by calling GetInPlaceMap()
3334 if ( !myGIPMapDone )
3336 myGIPMapDone = true;
3338 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3339 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3340 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3341 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3344 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3348 myGIPMap = new GEOM::ListOfListOfLong();
3353 //================================================================================
3355 * \brief Get new sub-shape by calling GetInPlace()
3357 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3359 GEOM::GEOM_Object_var newShape;
3361 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3362 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3363 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3366 newShape = op->GetInPlace( mainShapeNew, oldShape );
3371 return newShape._retn();
3374 //================================================================================
3376 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3377 * number of found IDs
3379 int findNewIDs( int oldID, std::vector< int >& newIDs )
3381 size_t prevNbIDs = newIDs.size();
3383 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3385 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3386 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3388 return newIDs.size() - prevNbIDs;
3391 //================================================================================
3393 * \brief Check if an object relates to the old shape
3395 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3397 if ( CORBA::is_nil( oldShape ))
3399 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3400 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3401 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3402 mainShapeOld1->_is_equivalent( oldShape ));
3405 //================================================================================
3407 * \brief Return shape type by shape ID
3409 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3411 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3412 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3413 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3416 //================================================================================
3418 * \brief Store a source sub-shape for which a counterpart not found and
3419 * a smesh object invalid due to that
3421 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3422 SALOMEDS::SObject_wrap smeshSO )
3424 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3425 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3427 CORBA::String_var smeshEntry = smeshSO->GetID();
3428 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3432 //================================================================================
3434 * \brief Store a source sub-shape for which a counterpart not found and
3435 * a smesh object invalid due to that
3437 void AddInvalid( std::string geomEntry,
3438 SALOMEDS::SObject_wrap smeshSO )
3440 if ( !geomEntry.empty() )
3442 CORBA::String_var smeshEntry = smeshSO->GetID();
3443 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3447 //================================================================================
3449 * \brief Store a source sub-shape for which a counterpart not found and
3450 * a smesh object invalid due to that
3452 void AddInvalid( int oldGeomID,
3453 SALOMEDS::SObject_wrap smeshSO )
3455 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3456 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3459 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3460 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3462 SMESH_Comment geomName( typeName[ shapeType ]);
3463 geomName << " #" << oldGeomID;
3465 CORBA::String_var smeshEntry = smeshSO->GetID();
3466 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3469 //================================================================================
3471 * \brief Return entries of a source sub-shape for which a counterpart not found and
3472 * of smesh objects invalid due to that
3474 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3475 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3478 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3479 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3481 nbSO += 1 + entry2entrySet->second.size();
3483 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3484 theInvalidEntries->length ( nbSO );
3485 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3487 entry2entrySet = myInvalidMap.begin();
3488 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3490 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3492 std::set< std::string > & entrySet = entry2entrySet->second;
3493 std::set< std::string >::iterator entry = entrySet.begin();
3494 for ( ; entry != entrySet.end(); ++entry )
3496 theInvalidEntries[ iEntry++ ] = entry->c_str();
3498 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3499 if ( !so->_is_nil() )
3500 theInvalidMeshSObjects[ iSO++ ] = so;
3505 }; // struct ShapeMapper
3507 //================================================================================
3509 * \brief Append an item to a CORBA sequence
3511 template < class CORBA_seq, class ITEM >
3512 void append( CORBA_seq& seq, ITEM item )
3514 if ( !CORBA::is_nil( item ))
3516 seq->length( 1 + seq->length() );
3517 seq[ seq->length() - 1 ] = item;
3520 } // namespace // utils for CopyMeshWithGeom()
3522 //================================================================================
3524 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3525 * \param [in] sourceMesh - a mesh to copy
3526 * \param [in] newGeometry - a new geometry
3527 * \param [in] toCopyGroups - to create groups in the new mesh
3528 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3529 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3530 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3531 * \param [out] newMesh - return a new mesh
3532 * \param [out] newGroups - return new groups
3533 * \param [out] newSubmeshes - return new sub-meshes
3534 * \param [out] newHypotheses - return new algorithms and hypotheses
3535 * \param [out] invalidEntries - return study entries of objects whose
3536 * counterparts are not found in the newGeometry, followed by entries
3537 * of mesh sub-objects that are invalid because they depend on a not found
3538 * preceding sub-shape
3539 * \return CORBA::Boolean - is a success
3541 //================================================================================
3543 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3544 GEOM::GEOM_Object_ptr theNewGeometry,
3545 const char* theMeshName,
3546 CORBA::Boolean theToCopyGroups,
3547 CORBA::Boolean theToReuseHypotheses,
3548 CORBA::Boolean theToCopyElements,
3549 SMESH::SMESH_Mesh_out theNewMesh,
3550 SMESH::ListOfGroups_out theNewGroups,
3551 SMESH::submesh_array_out theNewSubmeshes,
3552 SMESH::ListOfHypothesis_out theNewHypotheses,
3553 SMESH::string_array_out theInvalidEntries)
3554 throw ( SALOME::SALOME_Exception )
3556 if ( CORBA::is_nil( theSourceMesh ) ||
3557 CORBA::is_nil( theNewGeometry ))
3558 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3560 if ( !theSourceMesh->HasShapeToMesh() )
3561 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3566 TPythonDump pyDump; // prevent dump from CreateMesh()
3568 theNewMesh = CreateMesh( theNewGeometry );
3569 theNewGroups = new SMESH::ListOfGroups();
3570 theNewSubmeshes = new SMESH::submesh_array();
3571 theNewHypotheses = new SMESH::ListOfHypothesis();
3572 theInvalidEntries = new SMESH::string_array();
3574 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3576 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3577 GEOM::GEOM_Object_var geom, newGeom;
3578 SALOMEDS::SObject_wrap so;
3580 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3581 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3584 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3586 // treat hypotheses of mesh and sub-meshes
3587 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3588 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3590 bool isSubMesh = ( iSM < smList->length() );
3593 // create a new sub-mesh
3594 SMESH::SMESH_subMesh_var newSM;
3595 geom = smList[iSM]->GetSubShape();
3596 so = ObjectToSObject( smList[iSM] );
3597 CORBA::String_var name;
3598 if ( !so->_is_nil() )
3599 name = so->GetName();
3600 newGeom = shapeMapper.FindNew( geom );
3601 if ( newGeom->_is_nil() )
3603 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3604 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3609 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3611 append( theNewSubmeshes, newSM );
3613 if ( newGeom->_is_nil() )
3614 continue; // don't assign hypotheses
3618 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3620 so = ObjectToSObject( theNewMesh );
3621 SetName( so, theMeshName, "Mesh" );
3624 // assign hypotheses
3625 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3626 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3628 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3629 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3631 // get geometry hyp depends on
3632 std::vector< std::string > entryArray;
3633 std::vector< int > subIDArray;
3634 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3636 if ( !theToReuseHypotheses || dependsOnGeom )
3638 // create a new hypothesis
3639 CORBA::String_var type = hyp->GetName();
3640 CORBA::String_var lib = hyp->GetLibName();
3641 CORBA::String_var data = hyp_i->SaveTo();
3644 hyp = CreateHypothesis( type, lib );
3645 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3646 hyp_i->LoadFrom( data.in() );
3647 append( theNewHypotheses, hyp );
3651 // update geometry hyp depends on
3652 if ( dependsOnGeom )
3654 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3656 if ( !entryArray[ iGeo ].empty() )
3658 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3659 if ( newEntry.empty() )
3662 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3663 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3665 entryArray[ iGeo ] = newEntry;
3668 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3670 if ( subIDArray[ iGeo ] > 0 )
3672 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3676 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3677 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3679 subIDArray[ iGeo ] = newID;
3682 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3686 CORBA::String_var errorText;
3687 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3688 if ( errorText.in()[0] )
3691 } // loop on hypotheses
3692 } // loop on sub-meshes and mesh
3695 // copy mesh elements, keeping IDs
3696 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3697 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3699 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3700 ::SMESH_MeshEditor::ElemFeatures elemData;
3702 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3703 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3704 /*vertexLast=*/false);
3705 while ( srcSMIt->more() )
3707 SMESH_subMesh* srcSM = srcSMIt->next();
3708 if ( srcSM->IsEmpty() )
3709 continue; // not yet computed
3710 int newID = shapeMapper.FindNewNotChanged( srcSM );
3714 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3715 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3716 while ( nIt->more() )
3718 SMESH_NodeXYZ node( nIt->next() );
3719 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3721 const SMDS_PositionPtr pos = node->GetPosition();
3722 const double* uv = pos->GetParameters();
3723 switch ( pos->GetTypeOfPosition() )
3725 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3726 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3727 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3728 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3732 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3733 while( eIt->more() )
3735 const SMDS_MeshElement* e = eIt->next();
3736 elemData.Init( e, /*basicOnly=*/false );
3737 elemData.SetID( e->GetID() );
3738 elemData.myNodes.resize( e->NbNodes() );
3739 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3741 for ( iN = 0; nnIt->more(); ++iN )
3743 const SMDS_MeshNode* srcNode = nnIt->next();
3744 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3745 if ( !elemData.myNodes[ iN ])
3748 if ( iN == elemData.myNodes.size() )
3749 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3750 newMeshDS->SetMeshElementOnShape( newElem, newID );
3752 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3753 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3756 newMeshDS->Modified();
3762 TStr2StrMap old2newGroupMap;
3764 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3766 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3767 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3768 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3770 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3771 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3772 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3774 CORBA::String_var name = groups[ i ]->GetName();
3775 SMESH::ElementType elemType = groups[ i ]->GetType();
3777 SMESH::SMESH_GroupBase_var newGroup;
3779 if ( !stdlGroup->_is_nil() )
3781 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3783 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3784 const bool isElem = ( elemType != SMESH::NODE );
3785 CORBA::ULong iE = 0;
3786 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3787 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3789 if ( iE < elemIDs->length() )
3791 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3792 stdlGroup->Add( elemIDs );
3793 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3797 else if ( !geomGroup->_is_nil() )
3799 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3800 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3801 if ( newGeom->_is_nil() )
3803 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3804 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3809 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3812 else if ( !fltrGroup->_is_nil() )
3814 // replace geometry in a filter
3815 SMESH::Filter_var filter = fltrGroup->GetFilter();
3816 SMESH::Filter::Criteria_var criteria;
3817 filter->GetCriteria( criteria.out() );
3819 bool isMissingGroup = false;
3820 std::vector< std::string > badEntries;
3822 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3824 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3825 switch ( criteria[ iCr ].Type )
3827 case SMESH::FT_BelongToMeshGroup:
3829 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3830 btgg->SetGroupID( thresholdID );
3831 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3832 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3833 if ( refGroupSO->_is_nil() )
3835 CORBA::String_var refID = refGroupSO->GetID();
3836 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3837 if ( o2nID == old2newGroupMap.end() )
3839 isMissingGroup = true; // corresponding new group not yet created
3842 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3844 if ( o2nID->second.empty() ) // new referred group is invalid
3845 badEntries.push_back( refID.in() );
3848 case SMESH::FT_BelongToGeom:
3849 case SMESH::FT_BelongToPlane:
3850 case SMESH::FT_BelongToCylinder:
3851 case SMESH::FT_BelongToGenSurface:
3852 case SMESH::FT_LyingOnGeom:
3854 std::string newID = shapeMapper.FindNew( thresholdID );
3855 criteria[ iCr ].ThresholdID = newID.c_str();
3856 if ( newID.empty() )
3857 badEntries.push_back( thresholdID );
3860 case SMESH::FT_ConnectedElements:
3862 if ( thresholdID && thresholdID[0] )
3864 std::string newID = shapeMapper.FindNew( thresholdID );
3865 criteria[ iCr ].ThresholdID = newID.c_str();
3866 if ( newID.empty() )
3867 badEntries.push_back( thresholdID );
3873 } // loop on criteria
3875 if ( isMissingGroup && i < nbGroups )
3877 // to treat the group again
3878 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3882 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3883 newFilter->SetCriteria( criteria );
3885 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3886 newFilter->UnRegister();
3888 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3889 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3890 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3892 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3894 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3897 if ( !badEntries.empty() )
3900 } // treat a group on filter
3902 append( theNewGroups, newGroup );
3904 // fill old2newGroupMap
3905 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3906 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3907 if ( !srcSO->_is_nil() )
3909 CORBA::String_var srcID, newID("");
3910 srcID = srcSO->GetID();
3911 if ( !newSO->_is_nil() )
3912 newID = newSO->GetID();
3913 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3914 std::string( newID.in() )));
3917 if ( newGroup->_is_nil() )
3922 newMeshDS->CompactMesh();
3925 if ( !theMeshName || !theMeshName[0] )
3927 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3928 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3929 CORBA::String_var oldName = soOld->GetName();
3930 SetName( soNew, oldName.in(), "Mesh" );
3932 // mark invalid objects
3933 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3935 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3936 highLightInvalid( invalidSObjects[i].in(), true );
3939 << theNewMesh << ", "
3940 << theNewGroups << ", "
3941 << *theNewSubmeshes.ptr() << ", "
3942 << *theNewHypotheses.ptr() << ", "
3943 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3944 << theSourceMesh << ", "
3945 << theNewGeometry << ", "
3946 << "'" << theMeshName << "', "
3947 << theToCopyGroups << ", "
3948 << theToReuseHypotheses << ", "
3949 << theToCopyElements << " )";
3951 SMESH_CATCH( SMESH::throwCorbaException );
3956 //================================================================================
3958 * \brief Get version of MED format being used.
3960 //================================================================================
3962 char* SMESH_Gen_i::GetMEDFileVersion()
3964 MED::TInt majeur, mineur, release;
3965 majeur = mineur = release = 0;
3966 MED::GetVersionRelease(majeur, mineur, release);
3967 std::ostringstream version;
3968 version << majeur << "." << mineur << "." << release;
3969 return CORBA::string_dup( version.str().c_str() );
3972 //================================================================================
3974 * SMESH_Gen_i::GetMEDVersion
3976 * Get MED version of the file by its name
3978 //================================================================================
3979 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
3981 std::string version = MED::GetMEDVersion( theFileName );
3982 return CORBA::string_dup( version.c_str() );
3985 //================================================================================
3987 * SMESH_Gen_i::CheckCompatibility
3989 * Check compatibility of file with MED format being used, read only.
3991 //================================================================================
3992 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
3994 return MED::CheckCompatibility( theFileName );
3997 //================================================================================
3999 * SMESH_Gen_i::CheckWriteCompatibility
4001 * Check compatibility of file with MED format being used, for append on write.
4003 //================================================================================
4004 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4006 return MED::CheckCompatibility( theFileName, true );
4009 //================================================================================
4011 * SMESH_Gen_i::GetMeshNames
4013 * Get names of meshes defined in file with the specified name
4015 //================================================================================
4016 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4018 //MESSAGE("GetMeshNames " << theFileName);
4019 SMESH::string_array_var aResult = new SMESH::string_array();
4020 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4022 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4023 //MESSAGE("---" << aNbMeshes);
4025 aResult->length( aNbMeshes );
4026 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4027 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4028 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4031 return aResult._retn();
4034 //=============================================================================
4038 * Save SMESH module's data
4040 //=============================================================================
4041 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4046 Kernel_Utils::Localizer loc;
4048 if (!myStudyContext)
4051 // Store study contents as a set of python commands
4054 SALOMEDS::Study_var aStudy = getStudyServant();
4056 // Declare a byte stream
4057 SALOMEDS::TMPFile_var aStreamFile;
4059 // Obtain a temporary dir
4060 TCollection_AsciiString tmpDir =
4061 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4063 // Create a sequence of files processed
4064 SALOMEDS_Tool::ListOfFiles aFileSeq;
4065 aFileSeq.reserve( NUM_TMP_FILES );
4067 TCollection_AsciiString aStudyName( "" );
4069 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4071 // Set names of temporary files
4072 TCollection_AsciiString filename =
4073 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4074 TCollection_AsciiString meshfile =
4075 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4076 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4077 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4078 filename = tmpDir + filename;
4079 meshfile = tmpDir + meshfile;
4082 HDFdataset* aDataset;
4083 HDFgroup* aTopGroup;
4085 HDFgroup* aSubGroup;
4086 HDFgroup* aSubSubGroup;
4087 hdf_size aSize[ 1 ];
4090 //Remove the files if they exist: BugID: 11225
4091 #ifndef WIN32 /* unix functionality */
4092 TCollection_AsciiString cmd("rm -f \"");
4094 TCollection_AsciiString cmd("del /F \"");
4104 system(cmd.ToCString());
4106 // MED writer to be used by storage process
4107 DriverMED_W_SMESHDS_Mesh myWriter;
4108 myWriter.SetFile( meshfile.ToCString() );
4111 // SetStoreName() to groups before storing hypotheses to let them refer to
4112 // groups using "store name", which is "Group <group_persistent_id>"
4114 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4115 for ( ; itBig->More(); itBig->Next() ) {
4116 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4117 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4118 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4119 if ( !CORBA::is_nil( anObject ) ) {
4120 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4121 if ( !myMesh->_is_nil() ) {
4122 myMesh->Load(); // load from study file if not yet done
4123 TPythonDump pd; // not to dump GetGroups()
4124 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4125 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4127 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4130 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4131 int anId = myStudyContext->findId( string( objStr.in() ) );
4133 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4134 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4135 aGrpBaseDS->SetStoreName( grpName );
4145 // ---> create HDF file
4146 aFile = new HDFfile( (char*) filename.ToCString() );
4147 aFile->CreateOnDisk();
4149 // --> iterator for top-level objects
4150 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4151 for ( ; itBig->More(); itBig->Next() ) {
4152 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4154 // --> hypotheses root branch (only one for the study)
4155 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4156 // create hypotheses root HDF group
4157 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4158 aTopGroup->CreateOnDisk();
4160 // iterator for all hypotheses
4161 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4162 for ( ; it->More(); it->Next() ) {
4163 SALOMEDS::SObject_wrap mySObject = it->Value();
4164 CORBA::Object_var anObject = SObjectToObject( mySObject );
4165 if ( !CORBA::is_nil( anObject ) ) {
4166 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4167 if ( !myHyp->_is_nil() ) {
4168 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4170 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4171 std::string hypname = hn.in();
4172 std::string libname = ln.in();
4174 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4175 // WIN32 and ".so" for X-system) must be deleted
4176 int libname_len = libname.length();
4178 if( libname_len > 4 )
4179 libname.resize( libname_len - 4 );
4181 // PAL17753 (Regression: missing hypothesis in restored study)
4182 // "lib" also should be removed from the beginning
4183 //if( libname_len > 3 )
4184 //libname.resize( libname_len - 3 );
4185 if( libname_len > 6 )
4186 libname = libname.substr( 3, libname_len - 3 - 3 );
4188 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4189 CORBA::String_var hypdata = myImpl->SaveTo();
4190 int id = myStudyContext->findId( string( objStr.in() ));
4192 // for each hypothesis create HDF group basing on its id
4193 char hypGrpName[30];
4194 sprintf( hypGrpName, "Hypothesis %d", id );
4195 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4196 aGroup->CreateOnDisk();
4197 // --> type name of hypothesis
4198 aSize[ 0 ] = hypname.length() + 1;
4199 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4200 aDataset->CreateOnDisk();
4201 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4202 aDataset->CloseOnDisk();
4203 // --> server plugin library name of hypothesis
4204 aSize[ 0 ] = libname.length() + 1;
4205 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4206 aDataset->CreateOnDisk();
4207 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4208 aDataset->CloseOnDisk();
4209 // --> persistent data of hypothesis
4210 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4211 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4212 aDataset->CreateOnDisk();
4213 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4214 aDataset->CloseOnDisk();
4215 // close hypothesis HDF group
4216 aGroup->CloseOnDisk();
4221 // close hypotheses root HDF group
4222 aTopGroup->CloseOnDisk();
4224 // --> algorithms root branch (only one for the study)
4225 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4226 // create algorithms root HDF group
4227 aTopGroup = new HDFgroup( "Algorithms", aFile );
4228 aTopGroup->CreateOnDisk();
4230 // iterator for all algorithms
4231 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4232 for ( ; it->More(); it->Next() ) {
4233 SALOMEDS::SObject_wrap mySObject = it->Value();
4234 CORBA::Object_var anObject = SObjectToObject( mySObject );
4235 if ( !CORBA::is_nil( anObject ) ) {
4236 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4237 if ( !myHyp->_is_nil() ) {
4238 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4240 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4241 std::string hypname = hn.in();
4242 std::string libname = ln.in();
4244 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4245 // WIN32 and ".so" for X-system) must be deleted
4246 int libname_len = libname.length();
4248 if( libname_len > 4 )
4249 libname.resize( libname_len - 4 );
4251 // PAL17753 (Regression: missing hypothesis in restored study)
4252 // "lib" also should be removed from the beginning
4253 //if( libname_len > 3 )
4254 //libname.resize( libname_len - 3 );
4255 if( libname_len > 6 )
4256 libname = libname.substr( 3, libname_len - 3 - 3 );
4258 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4259 CORBA::String_var hypdata = myImpl->SaveTo();
4260 int id = myStudyContext->findId( string( objStr.in() ) );
4262 // for each algorithm create HDF group basing on its id
4263 char hypGrpName[30];
4264 sprintf( hypGrpName, "Algorithm %d", id );
4265 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4266 aGroup->CreateOnDisk();
4267 // --> type name of algorithm
4268 aSize[0] = hypname.length() + 1;
4269 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4270 aDataset->CreateOnDisk();
4271 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4272 aDataset->CloseOnDisk();
4273 // --> server plugin library name of hypothesis
4274 aSize[0] = libname.length() + 1;
4275 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4276 aDataset->CreateOnDisk();
4277 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4278 aDataset->CloseOnDisk();
4279 // --> persistent data of algorithm
4280 aSize[0] = strlen( hypdata.in() ) + 1;
4281 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4282 aDataset->CreateOnDisk();
4283 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4284 aDataset->CloseOnDisk();
4285 // close algorithm HDF group
4286 aGroup->CloseOnDisk();
4291 // close algorithms root HDF group
4292 aTopGroup->CloseOnDisk();
4294 // --> mesh objects roots branches
4295 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4296 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4297 if ( !CORBA::is_nil( anObject ) ) {
4298 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4299 if ( !myMesh->_is_nil() ) {
4300 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4302 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4303 int id = myStudyContext->findId( string( objStr.in() ) );
4304 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4305 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4306 bool hasShape = myLocMesh.HasShapeToMesh();
4308 // for each mesh open the HDF group basing on its id
4309 char meshGrpName[ 30 ];
4310 sprintf( meshGrpName, "Mesh %d", id );
4311 aTopGroup = new HDFgroup( meshGrpName, aFile );
4312 aTopGroup->CreateOnDisk();
4314 // --> put dataset to hdf file which is a flag that mesh has data
4315 string strHasData = "0";
4316 // check if the mesh is not empty
4317 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4318 // write mesh data to med file
4319 myWriter.SetMesh( mySMESHDSMesh );
4320 myWriter.SetMeshId( id );
4323 aSize[ 0 ] = strHasData.length() + 1;
4324 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4325 aDataset->CreateOnDisk();
4326 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4327 aDataset->CloseOnDisk();
4330 // for each mesh open the HDF group basing on its auto color parameter
4331 char meshAutoColorName[ 30 ];
4332 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4334 anAutoColor[0] = myImpl->GetAutoColor();
4336 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4337 aDataset->CreateOnDisk();
4338 aDataset->WriteOnDisk( anAutoColor );
4339 aDataset->CloseOnDisk();
4341 // issue 0020693. Store _isModified flag
4342 int isModified = myLocMesh.GetIsModified();
4344 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4345 aDataset->CreateOnDisk();
4346 aDataset->WriteOnDisk( &isModified );
4347 aDataset->CloseOnDisk();
4349 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4350 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4352 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4353 aDataset->CreateOnDisk();
4354 aDataset->WriteOnDisk( &meshPersistentId );
4355 aDataset->CloseOnDisk();
4357 // write reference on a shape if exists
4358 SALOMEDS::SObject_wrap myRef;
4359 bool shapeRefFound = false;
4360 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4362 SALOMEDS::SObject_wrap myShape;
4363 bool ok = myRef->ReferencedObject( myShape.inout() );
4365 CORBA::Object_var shapeObj = myShape->GetObject();
4366 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4367 CORBA::String_var myRefOnObject = myShape->GetID();
4368 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4369 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4370 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4371 aDataset->CreateOnDisk();
4372 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4373 aDataset->CloseOnDisk();
4379 std::string info = myImpl->FileInfoToString();
4380 if ( !info.empty() )
4382 aSize[ 0 ] = info.size();
4383 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4384 aDataset->CreateOnDisk();
4385 aDataset->WriteOnDisk( (char*) info.data() );
4386 aDataset->CloseOnDisk();
4389 // write applied hypotheses if exist
4390 SALOMEDS::SObject_wrap myHypBranch;
4391 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4392 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4393 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4395 if ( found && (shapeRefFound || !hasShape) ) {
4396 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4397 aGroup->CreateOnDisk();
4399 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4401 for ( ; it->More(); it->Next() ) {
4402 SALOMEDS::SObject_wrap mySObject = it->Value();
4403 SALOMEDS::SObject_wrap myRefOnHyp;
4404 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4406 // san - it is impossible to recover applied hypotheses
4407 // using their entries within Load() method,
4408 // for there are no AttributeIORs in the study when Load() is working.
4409 // Hence, it is better to store persistent IDs of hypotheses as references to them
4411 //string myRefOnObject = myRefOnHyp->GetID();
4412 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4413 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4414 int id = myStudyContext->findId( string( objStr.in() ) );
4415 //if ( myRefOnObject.length() > 0 ) {
4416 //aSize[ 0 ] = myRefOnObject.length() + 1;
4417 char hypName[ 30 ], hypId[ 30 ];
4418 sprintf( hypName, "Hyp %d", ++hypNb );
4419 sprintf( hypId, "%d", id );
4420 aSize[ 0 ] = strlen( hypId ) + 1;
4421 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4422 aDataset->CreateOnDisk();
4423 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4424 aDataset->WriteOnDisk( hypId );
4425 aDataset->CloseOnDisk();
4429 aGroup->CloseOnDisk();
4432 // write applied algorithms if exist
4433 SALOMEDS::SObject_wrap myAlgoBranch;
4434 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4435 myAlgoBranch.inout() );
4436 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4437 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4439 if ( found && (shapeRefFound || !hasShape)) {
4440 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4441 aGroup->CreateOnDisk();
4443 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4445 for ( ; it->More(); it->Next() ) {
4446 SALOMEDS::SObject_wrap mySObject = it->Value();
4447 SALOMEDS::SObject_wrap myRefOnAlgo;
4448 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4450 // san - it is impossible to recover applied algorithms
4451 // using their entries within Load() method,
4452 // for there are no AttributeIORs in the study when Load() is working.
4453 // Hence, it is better to store persistent IDs of algorithms as references to them
4455 //string myRefOnObject = myRefOnAlgo->GetID();
4456 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4457 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4458 int id = myStudyContext->findId( string( objStr.in() ) );
4459 //if ( myRefOnObject.length() > 0 ) {
4460 //aSize[ 0 ] = myRefOnObject.length() + 1;
4461 char algoName[ 30 ], algoId[ 30 ];
4462 sprintf( algoName, "Algo %d", ++algoNb );
4463 sprintf( algoId, "%d", id );
4464 aSize[ 0 ] = strlen( algoId ) + 1;
4465 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4466 aDataset->CreateOnDisk();
4467 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4468 aDataset->WriteOnDisk( algoId );
4469 aDataset->CloseOnDisk();
4473 aGroup->CloseOnDisk();
4476 // --> submesh objects sub-branches
4478 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4479 SALOMEDS::SObject_wrap mySubmeshBranch;
4480 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4482 if ( found ) // check if there is shape reference in submeshes
4484 bool hasShapeRef = false;
4485 SALOMEDS::ChildIterator_wrap itSM =
4486 aStudy->NewChildIterator( mySubmeshBranch );
4487 for ( ; itSM->More(); itSM->Next() ) {
4488 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4489 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4490 mySubRef->ReferencedObject( myShape.inout() );
4491 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4494 { // remove one submesh
4495 if ( shapeRefFound )
4496 { // unassign hypothesis
4497 SMESH::SMESH_subMesh_var mySubMesh =
4498 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4499 if ( !mySubMesh->_is_nil() ) {
4500 int shapeID = mySubMesh->GetId();
4501 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4502 const list<const SMESHDS_Hypothesis*>& hypList =
4503 mySMESHDSMesh->GetHypothesis( S );
4504 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4505 while ( hyp != hypList.end() ) {
4506 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4507 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4511 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4513 } // loop on submeshes of a type
4514 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4515 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4518 } // end check if there is shape reference in submeshes
4520 char name_meshgroup[ 30 ];
4521 if ( i == GetSubMeshOnVertexTag() )
4522 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4523 else if ( i == GetSubMeshOnEdgeTag() )
4524 strcpy( name_meshgroup, "SubMeshes On Edge" );
4525 else if ( i == GetSubMeshOnWireTag() )
4526 strcpy( name_meshgroup, "SubMeshes On Wire" );
4527 else if ( i == GetSubMeshOnFaceTag() )
4528 strcpy( name_meshgroup, "SubMeshes On Face" );
4529 else if ( i == GetSubMeshOnShellTag() )
4530 strcpy( name_meshgroup, "SubMeshes On Shell" );
4531 else if ( i == GetSubMeshOnSolidTag() )
4532 strcpy( name_meshgroup, "SubMeshes On Solid" );
4533 else if ( i == GetSubMeshOnCompoundTag() )
4534 strcpy( name_meshgroup, "SubMeshes On Compound" );
4536 // for each type of submeshes create container HDF group
4537 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4538 aGroup->CreateOnDisk();
4540 // iterator for all submeshes of given type
4541 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4542 for ( ; itSM->More(); itSM->Next() ) {
4543 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4544 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4545 if ( !CORBA::is_nil( anSubObject ))
4547 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4548 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4549 int subid = myStudyContext->findId( string( objStr.in() ) );
4551 // for each mesh open the HDF group basing on its id
4552 char submeshGrpName[ 30 ];
4553 sprintf( submeshGrpName, "SubMesh %d", subid );
4554 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4555 aSubGroup->CreateOnDisk();
4557 // write reference on a shape, already checked if it exists
4558 SALOMEDS::SObject_wrap mySubRef, myShape;
4559 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4560 mySubRef->ReferencedObject( myShape.inout() );
4561 string myRefOnObject = myShape->GetID();
4562 if ( myRefOnObject.length() > 0 ) {
4563 aSize[ 0 ] = myRefOnObject.length() + 1;
4564 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4565 aDataset->CreateOnDisk();
4566 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4567 aDataset->CloseOnDisk();
4570 // write applied hypotheses if exist
4571 SALOMEDS::SObject_wrap mySubHypBranch;
4572 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4573 mySubHypBranch.inout() );
4575 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4576 aSubSubGroup->CreateOnDisk();
4578 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4580 for ( ; it->More(); it->Next() ) {
4581 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4582 SALOMEDS::SObject_wrap myRefOnHyp;
4583 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4585 //string myRefOnObject = myRefOnHyp->GetID();
4586 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4587 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4588 int id = myStudyContext->findId( string( objStr.in() ) );
4589 //if ( myRefOnObject.length() > 0 ) {
4590 //aSize[ 0 ] = myRefOnObject.length() + 1;
4591 char hypName[ 30 ], hypId[ 30 ];
4592 sprintf( hypName, "Hyp %d", ++hypNb );
4593 sprintf( hypId, "%d", id );
4594 aSize[ 0 ] = strlen( hypId ) + 1;
4595 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4596 aDataset->CreateOnDisk();
4597 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4598 aDataset->WriteOnDisk( hypId );
4599 aDataset->CloseOnDisk();
4603 aSubSubGroup->CloseOnDisk();
4606 // write applied algorithms if exist
4607 SALOMEDS::SObject_wrap mySubAlgoBranch;
4608 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4609 mySubAlgoBranch.inout() );
4611 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4612 aSubSubGroup->CreateOnDisk();
4614 SALOMEDS::ChildIterator_wrap it =
4615 aStudy->NewChildIterator( mySubAlgoBranch );
4617 for ( ; it->More(); it->Next() ) {
4618 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4619 SALOMEDS::SObject_wrap myRefOnAlgo;
4620 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4622 //string myRefOnObject = myRefOnAlgo->GetID();
4623 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4624 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4625 int id = myStudyContext->findId( string( objStr.in() ) );
4626 //if ( myRefOnObject.length() > 0 ) {
4627 //aSize[ 0 ] = myRefOnObject.length() + 1;
4628 char algoName[ 30 ], algoId[ 30 ];
4629 sprintf( algoName, "Algo %d", ++algoNb );
4630 sprintf( algoId, "%d", id );
4631 aSize[ 0 ] = strlen( algoId ) + 1;
4632 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4633 aDataset->CreateOnDisk();
4634 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4635 aDataset->WriteOnDisk( algoId );
4636 aDataset->CloseOnDisk();
4640 aSubSubGroup->CloseOnDisk();
4642 // close submesh HDF group
4643 aSubGroup->CloseOnDisk();
4646 // close container of submeshes by type HDF group
4647 aGroup->CloseOnDisk();
4650 // All sub-meshes will be stored in MED file
4651 // .. will NOT (PAL 12992)
4652 //if ( shapeRefFound )
4653 //myWriter.AddAllSubMeshes();
4655 // store submesh order if any
4656 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4657 if ( theOrderIds.size() ) {
4658 char order_list[ 30 ];
4659 strcpy( order_list, "Mesh Order" );
4660 // count number of submesh ids
4662 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4663 for ( ; idIt != theOrderIds.end(); idIt++ )
4664 nbIDs += (*idIt).size();
4665 // number of values = number of IDs +
4666 // number of lists (for separators) - 1
4667 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4668 idIt = theOrderIds.begin();
4669 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4670 const TListOfInt& idList = *idIt;
4671 if (idIt != theOrderIds.begin()) // not first list
4672 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4673 // dump submesh ids from current list
4674 TListOfInt::const_iterator id_smId = idList.begin();
4675 for( ; id_smId != idList.end(); id_smId++ )
4676 smIDs[ i++ ] = *id_smId;
4679 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4681 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4682 aDataset->CreateOnDisk();
4683 aDataset->WriteOnDisk( smIDs );
4684 aDataset->CloseOnDisk();
4689 // groups root sub-branch
4690 SALOMEDS::SObject_wrap myGroupsBranch;
4691 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4692 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4694 char name_group[ 30 ];
4695 if ( i == GetNodeGroupsTag() )
4696 strcpy( name_group, "Groups of Nodes" );
4697 else if ( i == GetEdgeGroupsTag() )
4698 strcpy( name_group, "Groups of Edges" );
4699 else if ( i == GetFaceGroupsTag() )
4700 strcpy( name_group, "Groups of Faces" );
4701 else if ( i == GetVolumeGroupsTag() )
4702 strcpy( name_group, "Groups of Volumes" );
4703 else if ( i == Get0DElementsGroupsTag() )
4704 strcpy( name_group, "Groups of 0D Elements" );
4705 else if ( i == GetBallElementsGroupsTag() )
4706 strcpy( name_group, "Groups of Balls" );
4708 aGroup = new HDFgroup( name_group, aTopGroup );
4709 aGroup->CreateOnDisk();
4711 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4712 for ( ; it->More(); it->Next() ) {
4713 SALOMEDS::SObject_wrap mySObject = it->Value();
4714 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4715 if ( !CORBA::is_nil( aSubObject ) ) {
4716 SMESH_GroupBase_i* myGroupImpl =
4717 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4720 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4724 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4725 int anId = myStudyContext->findId( string( objStr.in() ) );
4727 // For each group, create a dataset named "Group <group_persistent_id>"
4728 // and store the group's user name into it
4729 const char* grpName = aGrpBaseDS->GetStoreName();
4730 CORBA::String_var aUserName = myGroupImpl->GetName();
4731 aSize[ 0 ] = strlen( aUserName ) + 1;
4733 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4734 aDataset->CreateOnDisk();
4735 aDataset->WriteOnDisk( aUserName );
4736 aDataset->CloseOnDisk();
4739 // For each group, create a dataset named "Group <group_persistent_id> Color"
4740 // and store the group's color into it
4741 char grpColorName[ 30 ];
4742 sprintf( grpColorName, "ColorGroup %d", anId );
4743 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4745 anRGB[ 0 ] = aColor.R;
4746 anRGB[ 1 ] = aColor.G;
4747 anRGB[ 2 ] = aColor.B;
4749 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4750 aDataset->CreateOnDisk();
4751 aDataset->WriteOnDisk( anRGB );
4752 aDataset->CloseOnDisk();
4754 // Pass SMESHDS_Group to MED writer
4755 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4757 myWriter.AddGroup( aGrpDS );
4759 // write reference on a shape if exists
4760 SMESHDS_GroupOnGeom* aGeomGrp =
4761 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4763 SALOMEDS::SObject_wrap mySubRef, myShape;
4764 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4765 mySubRef->ReferencedObject( myShape.inout() ) &&
4766 !CORBA::is_nil( myShape->GetObject() ))
4768 CORBA::String_var myRefOnObject = myShape->GetID();
4769 if ( myRefOnObject.in()[0] ) {
4770 char aRefName[ 30 ];
4771 sprintf( aRefName, "Ref on shape %d", anId);
4772 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4773 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4774 aDataset->CreateOnDisk();
4775 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4776 aDataset->CloseOnDisk();
4779 else // shape ref is invalid:
4781 // save a group on geometry as ordinary group
4782 myWriter.AddGroup( aGeomGrp );
4785 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4786 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4788 std::string str = aFilterGrp_i->FilterToString();
4789 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4790 aSize[ 0 ] = str.length() + 1;
4791 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4792 aDataset->CreateOnDisk();
4793 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4794 aDataset->CloseOnDisk();
4798 aGroup->CloseOnDisk();
4802 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4804 // Flush current mesh information into MED file
4807 // save info on nb of elements
4808 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4810 // maybe a shape was deleted in the study
4811 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4812 TopoDS_Shape nullShape;
4813 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4816 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4821 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4822 aGroup->CreateOnDisk();
4824 // each element belongs to one or none submesh,
4825 // so for each node/element, we store a submesh ID
4827 // Store submesh IDs
4828 for ( int isNode = 0; isNode < 2; ++isNode )
4830 SMDS_ElemIteratorPtr eIt =
4831 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4832 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4835 std::vector<int> smIDs; smIDs.reserve( nbElems );
4836 while ( eIt->more() )
4837 if ( const SMDS_MeshElement* e = eIt->next())
4838 smIDs.push_back( e->getshapeId() );
4840 aSize[ 0 ] = nbElems;
4841 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4842 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4843 aDataset->CreateOnDisk();
4844 aDataset->WriteOnDisk( & smIDs[0] );
4845 aDataset->CloseOnDisk();
4848 aGroup->CloseOnDisk();
4850 // Store node positions on sub-shapes (SMDS_Position):
4851 // ----------------------------------------------------
4853 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4854 aGroup->CreateOnDisk();
4856 // in aGroup, create 5 datasets to contain:
4857 // "Nodes on Edges" - ID of node on edge
4858 // "Edge positions" - U parameter on node on edge
4859 // "Nodes on Faces" - ID of node on face
4860 // "Face U positions" - U parameter of node on face
4861 // "Face V positions" - V parameter of node on face
4863 // Find out nb of nodes on edges and faces
4864 // Collect corresponding sub-meshes
4865 int nbEdgeNodes = 0, nbFaceNodes = 0;
4866 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4867 // loop on SMESHDS_SubMesh'es
4868 while ( smIt->more() )
4870 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4871 if ( aSubMesh->IsComplexSubmesh() )
4872 continue; // submesh containing other submeshs
4873 int nbNodes = aSubMesh->NbNodes();
4874 if ( nbNodes == 0 ) continue;
4876 int aShapeID = aSubMesh->GetID();
4877 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4879 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4880 // write only SMDS_FacePosition and SMDS_EdgePosition
4881 switch ( aShapeType ) {
4883 nbFaceNodes += nbNodes;
4884 aFaceSM.push_back( aSubMesh );
4887 nbEdgeNodes += nbNodes;
4888 aEdgeSM.push_back( aSubMesh );
4894 // Treat positions on edges or faces
4895 for ( int onFace = 0; onFace < 2; onFace++ )
4897 // Create arrays to store in datasets
4898 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4899 if (!nbNodes) continue;
4900 int* aNodeIDs = new int [ nbNodes ];
4901 double* aUPos = new double [ nbNodes ];
4902 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4905 // loop on sub-meshes
4906 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4907 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4908 for ( ; itSM != pListSM->end(); itSM++ )
4910 SMESHDS_SubMesh* aSubMesh = (*itSM);
4912 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4913 // loop on nodes in aSubMesh
4914 while ( itNode->more() )
4917 const SMDS_MeshNode* node = itNode->next();
4918 aNodeIDs [ iNode ] = node->GetID();
4921 const SMDS_PositionPtr pos = node->GetPosition();
4922 if ( onFace ) { // on FACE
4923 SMDS_FacePositionPtr fPos = pos;
4925 aUPos[ iNode ] = fPos->GetUParameter();
4926 aVPos[ iNode ] = fPos->GetVParameter();
4933 SMDS_EdgePositionPtr ePos = pos;
4935 aUPos[ iNode ] = ePos->GetUParameter();
4941 } // loop on nodes in aSubMesh
4942 } // loop on sub-meshes
4947 aSize[ 0 ] = nbNodes;
4949 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4950 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4951 aDataset->CreateOnDisk();
4952 aDataset->WriteOnDisk( aNodeIDs );
4953 aDataset->CloseOnDisk();
4956 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4957 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4958 aDataset->CreateOnDisk();
4959 aDataset->WriteOnDisk( aUPos );
4960 aDataset->CloseOnDisk();
4963 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4964 aDataset->CreateOnDisk();
4965 aDataset->WriteOnDisk( aVPos );
4966 aDataset->CloseOnDisk();
4971 if ( aVPos ) delete [] aVPos;
4973 } // treat positions on edges or faces
4975 // close "Node Positions" group
4976 aGroup->CloseOnDisk();
4978 } // if ( there are submeshes in SMESHDS_Mesh )
4981 // close mesh HDF group
4982 aTopGroup->CloseOnDisk();
4990 aFile->CloseOnDisk();
4993 // Convert temporary files to stream
4994 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
4996 // Remove temporary files and directory
4998 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5000 return aStreamFile._retn();
5003 //=============================================================================
5005 * SMESH_Gen_i::SaveASCII
5007 * Save SMESH module's data in ASCII format
5009 //=============================================================================
5011 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5013 bool isMultiFile ) {
5014 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5015 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5016 return aStreamFile._retn();
5018 //after usual saving needs to encipher binary to text string
5019 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5020 int size = aStreamFile.in().length();
5021 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5022 for ( int i = 0; i < size; i++ )
5023 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5025 buffer[size * 3] = '\0';
5027 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5029 return anAsciiStreamFile._retn();
5032 //=============================================================================
5034 * SMESH_Gen_i::loadGeomData
5036 * Load GEOM module data
5038 //=============================================================================
5040 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
5042 if ( theCompRoot->_is_nil() )
5045 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
5046 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
5049 //=============================================================================
5053 * Load SMESH module's data
5055 //=============================================================================
5057 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5058 const SALOMEDS::TMPFile& theStream,
5063 Kernel_Utils::Localizer loc;
5065 //if (!myStudyContext)
5067 SALOMEDS::Study_var aStudy = getStudyServant();
5068 /* if( !theComponent->_is_nil() )
5070 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
5071 loadGeomData( aStudy->FindComponent( "GEOM" ) );
5074 // Get temporary files location
5075 TCollection_AsciiString tmpDir =
5076 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5078 // Convert the stream into sequence of files to process
5079 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5082 TCollection_AsciiString aStudyName( "" );
5083 if ( isMultiFile ) {
5084 CORBA::WString_var url = aStudy->URL();
5085 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5087 // Set names of temporary files
5088 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5089 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5093 HDFdataset* aDataset;
5094 HDFgroup* aTopGroup;
5096 HDFgroup* aSubGroup;
5097 HDFgroup* aSubSubGroup;
5100 // ---> open HDF file
5101 aFile = new HDFfile( (char*) filename.ToCString() );
5103 aFile->OpenOnDisk( HDF_RDONLY );
5105 catch ( HDFexception ) {
5106 INFOS( "Load(): " << filename << " not found!" );
5110 TPythonDump pd; // prevent dump during loading
5112 // DriverMED_R_SMESHDS_Mesh myReader;
5113 // myReader.SetFile( meshfile.ToCString() );
5115 // For PAL13473 ("Repetitive mesh") implementation.
5116 // New dependencies between SMESH objects are established:
5117 // now hypotheses can refer to meshes, shapes and other hypotheses.
5118 // To keep data consistent, the following order of data restoration
5120 // 1. Create hypotheses
5121 // 2. Create all meshes
5122 // 3. Load hypotheses' data
5125 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5126 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5127 list< SMESH::Filter_var > filters;
5129 // get total number of top-level groups
5130 int aNbGroups = aFile->nInternalObjects();
5131 if ( aNbGroups > 0 ) {
5132 // --> in first turn we should read&create hypotheses
5133 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5134 // open hypotheses root HDF group
5135 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5136 aTopGroup->OpenOnDisk();
5138 // get number of hypotheses
5139 int aNbObjects = aTopGroup->nInternalObjects();
5140 for ( int j = 0; j < aNbObjects; j++ ) {
5141 // try to identify hypothesis
5142 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5143 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5145 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5146 // open hypothesis group
5147 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5148 aGroup->OpenOnDisk();
5150 // --> get hypothesis id
5151 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5156 // get number of datasets
5157 int aNbSubObjects = aGroup->nInternalObjects();
5158 for ( int k = 0; k < aNbSubObjects; k++ ) {
5160 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5161 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5162 // --> get hypothesis name
5163 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5164 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5165 aDataset->OpenOnDisk();
5166 size = aDataset->GetSize();
5167 char* hypname_str = new char[ size ];
5168 aDataset->ReadFromDisk( hypname_str );
5169 hypname = string( hypname_str );
5170 delete [] hypname_str;
5171 aDataset->CloseOnDisk();
5173 // --> get hypothesis plugin library name
5174 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5175 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5176 aDataset->OpenOnDisk();
5177 size = aDataset->GetSize();
5178 char* libname_str = new char[ size ];
5179 aDataset->ReadFromDisk( libname_str );
5180 if(MYDEBUG) SCRUTE( libname_str );
5181 libname = string( libname_str );
5182 delete [] libname_str;
5183 aDataset->CloseOnDisk();
5185 // --> get hypothesis data
5186 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5187 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5188 aDataset->OpenOnDisk();
5189 size = aDataset->GetSize();
5190 char* hypdata_str = new char[ size ];
5191 aDataset->ReadFromDisk( hypdata_str );
5192 hypdata = string( hypdata_str );
5193 delete [] hypdata_str;
5194 aDataset->CloseOnDisk();
5197 // close hypothesis HDF group
5198 aGroup->CloseOnDisk();
5200 // --> restore hypothesis from data
5201 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5202 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5203 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5204 SMESH::SMESH_Hypothesis_var myHyp;
5206 try { // protect persistence mechanism against exceptions
5207 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5210 INFOS( "Exception during hypothesis creation" );
5213 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5215 // myImpl->LoadFrom( hypdata.c_str() );
5216 hypDataList.push_back( make_pair( myImpl, hypdata ));
5217 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5218 int newId = myStudyContext->findId( iorString.in() );
5219 myStudyContext->mapOldToNew( id, newId );
5222 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5226 // close hypotheses root HDF group
5227 aTopGroup->CloseOnDisk();
5231 // --> then we should read&create algorithms
5232 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5233 // open algorithms root HDF group
5234 aTopGroup = new HDFgroup( "Algorithms", aFile );
5235 aTopGroup->OpenOnDisk();
5237 // get number of algorithms
5238 int aNbObjects = aTopGroup->nInternalObjects();
5239 for ( int j = 0; j < aNbObjects; j++ ) {
5240 // try to identify algorithm
5241 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5242 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5244 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5245 // open algorithm group
5246 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5247 aGroup->OpenOnDisk();
5249 // --> get algorithm id
5250 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5255 // get number of datasets
5256 int aNbSubObjects = aGroup->nInternalObjects();
5257 for ( int k = 0; k < aNbSubObjects; k++ ) {
5259 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5260 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5261 // --> get algorithm name
5262 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5263 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5264 aDataset->OpenOnDisk();
5265 size = aDataset->GetSize();
5266 char* hypname_str = new char[ size ];
5267 aDataset->ReadFromDisk( hypname_str );
5268 hypname = string( hypname_str );
5269 delete [] hypname_str;
5270 aDataset->CloseOnDisk();
5272 // --> get algorithm plugin library name
5273 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5274 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5275 aDataset->OpenOnDisk();
5276 size = aDataset->GetSize();
5277 char* libname_str = new char[ size ];
5278 aDataset->ReadFromDisk( libname_str );
5279 if(MYDEBUG) SCRUTE( libname_str );
5280 libname = string( libname_str );
5281 delete [] libname_str;
5282 aDataset->CloseOnDisk();
5284 // --> get algorithm data
5285 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5286 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5287 aDataset->OpenOnDisk();
5288 size = aDataset->GetSize();
5289 char* hypdata_str = new char[ size ];
5290 aDataset->ReadFromDisk( hypdata_str );
5291 if(MYDEBUG) SCRUTE( hypdata_str );
5292 hypdata = string( hypdata_str );
5293 delete [] hypdata_str;
5294 aDataset->CloseOnDisk();
5297 // close algorithm HDF group
5298 aGroup->CloseOnDisk();
5300 // --> restore algorithm from data
5301 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5302 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5303 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5304 SMESH::SMESH_Hypothesis_var myHyp;
5306 try { // protect persistence mechanism against exceptions
5307 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5309 catch( SALOME::SALOME_Exception& ex )
5311 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5314 INFOS( "Exception during hypothesis creation" );
5317 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5319 //myImpl->LoadFrom( hypdata.c_str() );
5320 hypDataList.push_back( make_pair( myImpl, hypdata ));
5321 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5322 int newId = myStudyContext->findId( iorString.in() );
5323 myStudyContext->mapOldToNew( id, newId );
5326 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5330 // close algorithms root HDF group
5331 aTopGroup->CloseOnDisk();
5335 // --> the rest groups should be meshes
5336 for ( int i = 0; i < aNbGroups; i++ ) {
5337 // identify next group
5338 char meshName[ HDF_NAME_MAX_LEN+1 ];
5339 aFile->InternalObjectIndentify( i, meshName );
5341 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5343 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5347 // open mesh HDF group
5348 aTopGroup = new HDFgroup( meshName, aFile );
5349 aTopGroup->OpenOnDisk();
5351 // get number of child HDF objects
5352 int aNbObjects = aTopGroup->nInternalObjects();
5353 if ( aNbObjects > 0 ) {
5355 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5356 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5357 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5358 if ( !myNewMeshImpl )
5360 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5362 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5363 int newId = myStudyContext->findId( iorString.in() );
5364 myStudyContext->mapOldToNew( id, newId );
5367 // try to read and set auto color flag
5368 char aMeshAutoColorName[ 30 ];
5369 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5370 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5372 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5373 aDataset->OpenOnDisk();
5374 size = aDataset->GetSize();
5375 int* anAutoColor = new int[ size ];
5376 aDataset->ReadFromDisk( anAutoColor );
5377 aDataset->CloseOnDisk();
5378 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5379 delete [] anAutoColor;
5382 // try to read and set reference to shape
5383 GEOM::GEOM_Object_var aShapeObject;
5384 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5385 // load mesh "Ref on shape" - it's an entry to SObject
5386 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5387 aDataset->OpenOnDisk();
5388 size = aDataset->GetSize();
5389 char* refFromFile = new char[ size ];
5390 aDataset->ReadFromDisk( refFromFile );
5391 aDataset->CloseOnDisk();
5392 if ( strlen( refFromFile ) > 0 ) {
5393 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5395 // Make sure GEOM data are loaded first
5396 //loadGeomData( shapeSO->GetFatherComponent() );
5398 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5399 if ( !CORBA::is_nil( shapeObject ) ) {
5400 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5401 if ( !aShapeObject->_is_nil() )
5402 myNewMeshImpl->SetShape( aShapeObject );
5405 delete [] refFromFile;
5408 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5409 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5411 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5412 aDataset->OpenOnDisk();
5413 size = aDataset->GetSize();
5414 int* meshPersistentId = new int[ size ];
5415 aDataset->ReadFromDisk( meshPersistentId );
5416 aDataset->CloseOnDisk();
5417 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5418 delete [] meshPersistentId;
5421 // Restore file info
5422 if ( aTopGroup->ExistInternalObject( "file info" ))
5424 aDataset = new HDFdataset( "file info", aTopGroup );
5425 aDataset->OpenOnDisk();
5426 size = aDataset->GetSize();
5427 std::string info( size, ' ');
5428 aDataset->ReadFromDisk( (char*) info.data() );
5429 aDataset->CloseOnDisk();
5430 myNewMeshImpl->FileInfoFromString( info );
5436 // As all object that can be referred by hypothesis are created,
5437 // we can restore hypothesis data
5439 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5440 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5442 SMESH_Hypothesis_i* hyp = hyp_data->first;
5443 string & data = hyp_data->second;
5444 hyp->LoadFrom( data.c_str() );
5447 // Restore the rest mesh data
5449 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5450 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5452 aTopGroup = meshi_group->second;
5453 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5454 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5455 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5457 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5458 bool hasData = false;
5461 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5462 int newId = myStudyContext->findId( iorString.in() );
5463 int meshOldId = myStudyContext->getOldId( newId );
5465 // try to find mesh data dataset
5466 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5467 // load mesh "has data" flag
5468 aDataset = new HDFdataset( "Has data", aTopGroup );
5469 aDataset->OpenOnDisk();
5470 size = aDataset->GetSize();
5471 char* strHasData = new char[ size ];
5472 aDataset->ReadFromDisk( strHasData );
5473 aDataset->CloseOnDisk();
5474 if ( strcmp( strHasData, "1") == 0 ) {
5477 delete [] strHasData;
5480 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5481 // nodes and elements are not yet put into sub-meshes)
5482 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5483 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5484 aGroup->OpenOnDisk();
5485 // get number of applied algorithms
5486 int aNbSubObjects = aGroup->nInternalObjects();
5487 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5488 for ( int j = 0; j < aNbSubObjects; j++ ) {
5489 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5490 aGroup->InternalObjectIndentify( j, name_dataset );
5491 // check if it is an algorithm
5492 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5493 aDataset = new HDFdataset( name_dataset, aGroup );
5494 aDataset->OpenOnDisk();
5495 size = aDataset->GetSize();
5496 char* refFromFile = new char[ size ];
5497 aDataset->ReadFromDisk( refFromFile );
5498 aDataset->CloseOnDisk();
5499 // san - it is impossible to recover applied algorithms using their entries within Load() method
5500 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5501 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5502 int id = atoi( refFromFile );
5503 delete [] refFromFile;
5504 string anIOR = myStudyContext->getIORbyOldId( id );
5505 if ( !anIOR.empty() ) {
5506 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5507 if ( !CORBA::is_nil( hypObject ) ) {
5508 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5509 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5510 || !myNewMeshImpl->HasShapeToMesh()) )
5511 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5516 aGroup->CloseOnDisk();
5519 // try to get applied hypotheses
5520 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5521 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5522 aGroup->OpenOnDisk();
5523 // get number of applied hypotheses
5524 int aNbSubObjects = aGroup->nInternalObjects();
5525 for ( int j = 0; j < aNbSubObjects; j++ ) {
5526 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5527 aGroup->InternalObjectIndentify( j, name_dataset );
5528 // check if it is a hypothesis
5529 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5530 aDataset = new HDFdataset( name_dataset, aGroup );
5531 aDataset->OpenOnDisk();
5532 size = aDataset->GetSize();
5533 char* refFromFile = new char[ size ];
5534 aDataset->ReadFromDisk( refFromFile );
5535 aDataset->CloseOnDisk();
5536 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5537 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5538 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5539 int id = atoi( refFromFile );
5540 delete [] refFromFile;
5541 string anIOR = myStudyContext->getIORbyOldId( id );
5542 if ( !anIOR.empty() ) {
5543 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5544 if ( !CORBA::is_nil( hypObject ) ) {
5545 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5546 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5547 || !myNewMeshImpl->HasShapeToMesh()) )
5548 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5553 aGroup->CloseOnDisk();
5556 // --> try to find SUB-MESHES containers for each type of submesh
5557 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5558 const char* name_meshgroup = 0;
5559 if ( j == GetSubMeshOnVertexTag() )
5560 name_meshgroup = "SubMeshes On Vertex";
5561 else if ( j == GetSubMeshOnEdgeTag() )
5562 name_meshgroup = "SubMeshes On Edge";
5563 else if ( j == GetSubMeshOnWireTag() )
5564 name_meshgroup = "SubMeshes On Wire";
5565 else if ( j == GetSubMeshOnFaceTag() )
5566 name_meshgroup = "SubMeshes On Face";
5567 else if ( j == GetSubMeshOnShellTag() )
5568 name_meshgroup = "SubMeshes On Shell";
5569 else if ( j == GetSubMeshOnSolidTag() )
5570 name_meshgroup = "SubMeshes On Solid";
5571 else if ( j == GetSubMeshOnCompoundTag() )
5572 name_meshgroup = "SubMeshes On Compound";
5574 // try to get submeshes container HDF group
5575 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5576 // open submeshes containers HDF group
5577 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5578 aGroup->OpenOnDisk();
5580 // get number of submeshes
5581 int aNbSubMeshes = aGroup->nInternalObjects();
5582 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5584 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5585 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5586 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5587 // --> get submesh id
5588 int subid = atoi( name_submeshgroup + 7 );
5591 // open submesh HDF group
5592 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5593 aSubGroup->OpenOnDisk();
5595 // try to read and set reference to subshape
5596 GEOM::GEOM_Object_var aSubShapeObject;
5597 SMESH::SMESH_subMesh_var aSubMesh;
5599 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5600 // load submesh "Ref on shape" - it's an entry to SObject
5601 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5602 aDataset->OpenOnDisk();
5603 size = aDataset->GetSize();
5604 char* refFromFile = new char[ size ];
5605 aDataset->ReadFromDisk( refFromFile );
5606 aDataset->CloseOnDisk();
5607 if ( strlen( refFromFile ) > 0 ) {
5608 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5609 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5610 if ( !CORBA::is_nil( subShapeObject ) ) {
5611 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5612 if ( !aSubShapeObject->_is_nil() )
5613 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5614 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5615 if ( aSubMesh->_is_nil() )
5617 string iorSubString = GetORB()->object_to_string( aSubMesh );
5618 int newSubId = myStudyContext->findId( iorSubString );
5619 myStudyContext->mapOldToNew( subid, newSubId );
5622 delete [] refFromFile;
5625 if ( aSubMesh->_is_nil() )
5628 // try to get applied algorithms
5629 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5630 // open "applied algorithms" HDF group
5631 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5632 aSubSubGroup->OpenOnDisk();
5633 // get number of applied algorithms
5634 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5635 for ( int l = 0; l < aNbSubObjects; l++ ) {
5636 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5637 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5638 // check if it is an algorithm
5639 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5640 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5641 aDataset->OpenOnDisk();
5642 size = aDataset->GetSize();
5643 char* refFromFile = new char[ size ];
5644 aDataset->ReadFromDisk( refFromFile );
5645 aDataset->CloseOnDisk();
5647 int id = atoi( refFromFile );
5648 string anIOR = myStudyContext->getIORbyOldId( id );
5649 if ( !anIOR.empty() ) {
5650 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5651 if ( !CORBA::is_nil( hypObject ) ) {
5652 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5653 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5654 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5657 delete [] refFromFile;
5660 // close "applied algorithms" HDF group
5661 aSubSubGroup->CloseOnDisk();
5664 // try to get applied hypotheses
5665 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5666 // open "applied hypotheses" HDF group
5667 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5668 aSubSubGroup->OpenOnDisk();
5669 // get number of applied hypotheses
5670 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5671 for ( int l = 0; l < aNbSubObjects; l++ ) {
5672 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5673 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5674 // check if it is a hypothesis
5675 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5676 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5677 aDataset->OpenOnDisk();
5678 size = aDataset->GetSize();
5679 char* refFromFile = new char[ size ];
5680 aDataset->ReadFromDisk( refFromFile );
5681 aDataset->CloseOnDisk();
5683 int id = atoi( refFromFile );
5684 string anIOR = myStudyContext->getIORbyOldId( id );
5685 if ( !anIOR.empty() ) {
5686 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5687 if ( !CORBA::is_nil( hypObject ) ) {
5688 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5689 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5690 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5693 delete [] refFromFile;
5696 // close "APPLIED HYPOTHESES" hdf group
5697 aSubSubGroup->CloseOnDisk();
5700 // close SUB-MESH hdf group
5701 aSubGroup->CloseOnDisk();
5704 // close SUB-MESHES containers hdf group
5705 aGroup->CloseOnDisk();
5709 // try to get GROUPS
5710 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5711 char name_group[ 30 ];
5712 if ( ii == GetNodeGroupsTag() )
5713 strcpy( name_group, "Groups of Nodes" );
5714 else if ( ii == GetEdgeGroupsTag() )
5715 strcpy( name_group, "Groups of Edges" );
5716 else if ( ii == GetFaceGroupsTag() )
5717 strcpy( name_group, "Groups of Faces" );
5718 else if ( ii == GetVolumeGroupsTag() )
5719 strcpy( name_group, "Groups of Volumes" );
5720 else if ( ii == Get0DElementsGroupsTag() )
5721 strcpy( name_group, "Groups of 0D Elements" );
5722 else if ( ii == GetBallElementsGroupsTag() )
5723 strcpy( name_group, "Groups of Balls" );
5725 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5726 aGroup = new HDFgroup( name_group, aTopGroup );
5727 aGroup->OpenOnDisk();
5728 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5729 // within aGroup->ExistInternalObject( name )
5730 std::vector< std::string > subNames;
5731 TColStd_MapOfAsciiString mapOfNames;
5732 aGroup->GetAllObjects( subNames );
5733 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5734 mapOfNames.Add( subNames[ iN ].c_str() );
5736 for ( size_t j = 0; j < subNames.size(); j++ ) {
5737 const std::string& name_dataset = subNames[ j ];
5738 // check if it is a group
5739 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5742 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5745 int groupID = -1; // group local ID (also persistent)
5747 groupID = atoi( endptr + 1 );
5748 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5749 aDataset->OpenOnDisk();
5751 // Retrieve actual group name
5752 size = aDataset->GetSize();
5753 char* nameFromFile = new char[ size ];
5754 aDataset->ReadFromDisk( nameFromFile );
5755 aDataset->CloseOnDisk();
5757 // Try to find a shape reference
5758 TopoDS_Shape aShape;
5759 char aRefName[ 30 ];
5760 sprintf( aRefName, "Ref on shape %d", subid);
5761 if ( mapOfNames.Contains( aRefName ))
5763 // load mesh "Ref on shape" - it's an entry to SObject
5764 aDataset = new HDFdataset( aRefName, aGroup );
5765 aDataset->OpenOnDisk();
5766 size = aDataset->GetSize();
5767 char* refFromFile = new char[ size ];
5768 aDataset->ReadFromDisk( refFromFile );
5769 aDataset->CloseOnDisk();
5770 if ( strlen( refFromFile ) > 0 ) {
5771 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5772 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5773 if ( !CORBA::is_nil( shapeObject ) ) {
5774 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5775 if ( !aShapeObject->_is_nil() )
5776 aShape = GeomObjectToShape( aShapeObject );
5779 delete [] refFromFile;
5781 // Try to read a filter of SMESH_GroupOnFilter
5782 SMESH::Filter_var filter;
5783 SMESH_PredicatePtr predicate;
5784 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5785 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5787 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5788 aDataset->OpenOnDisk();
5789 size = aDataset->GetSize();
5790 char* persistStr = new char[ size ];
5791 aDataset->ReadFromDisk( persistStr );
5792 aDataset->CloseOnDisk();
5793 if ( strlen( persistStr ) > 0 ) {
5794 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5795 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5796 filters.push_back( filter );
5798 delete [] persistStr;
5801 // Create group servant
5802 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5803 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5804 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5805 delete [] nameFromFile;
5806 // Obtain a SMESHDS_Group object
5807 if ( aNewGroup->_is_nil() )
5810 string iorSubString = GetORB()->object_to_string( aNewGroup );
5811 int newSubId = myStudyContext->findId( iorSubString );
5812 myStudyContext->mapOldToNew( subid, newSubId );
5814 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5818 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5819 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5821 aFilterGroup->SetFilter( filter );
5822 filter->UnRegister();
5824 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5825 if ( !aGroupBaseDS )
5828 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5831 // Read color of the group
5832 char aGroupColorName[ 30 ];
5833 sprintf( aGroupColorName, "ColorGroup %d", subid);
5834 if ( mapOfNames.Contains( aGroupColorName ))
5836 aDataset = new HDFdataset( aGroupColorName, aGroup );
5837 aDataset->OpenOnDisk();
5838 size = aDataset->GetSize();
5839 double* anRGB = new double[ size ];
5840 aDataset->ReadFromDisk( anRGB );
5841 aDataset->CloseOnDisk();
5842 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5843 aGroupBaseDS->SetColor( aColor );
5848 aGroup->CloseOnDisk();
5852 // instead of reading mesh data, we read only brief information of all
5853 // objects: mesh, groups, sub-meshes (issue 0021208)
5856 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5857 meshfile.ToCString(), filename.ToCString(),
5861 // read Sub-Mesh ORDER if any
5862 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5863 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5864 aDataset->OpenOnDisk();
5865 size = aDataset->GetSize();
5866 int* smIDs = new int[ size ];
5867 aDataset->ReadFromDisk( smIDs );
5868 aDataset->CloseOnDisk();
5869 TListOfListOfInt anOrderIds;
5870 anOrderIds.push_back( TListOfInt() );
5871 for ( int i = 0; i < size; i++ )
5872 if ( smIDs[ i ] < 0 ) // is separator
5873 anOrderIds.push_back( TListOfInt() );
5875 anOrderIds.back().push_back(smIDs[ i ]);
5877 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5882 // update hyps needing full mesh data restored (issue 20918)
5883 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5885 SMESH_Hypothesis_i* hyp = hyp_data->first;
5886 hyp->UpdateAsMeshesRestored();
5889 // notify algos on completed restoration to set sub-mesh event listeners
5890 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5892 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5893 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5895 TopoDS_Shape myLocShape;
5896 if(myLocMesh.HasShapeToMesh())
5897 myLocShape = myLocMesh.GetShapeToMesh();
5899 myLocShape = SMESH_Mesh::PseudoShape();
5901 myLocMesh.GetSubMesh(myLocShape)->
5902 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5905 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5906 list< SMESH::Filter_var >::iterator f = filters.begin();
5907 for ( ; f != filters.end(); ++f )
5908 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5909 fi->FindBaseObjects();
5914 aTopGroup->CloseOnDisk();
5917 aFile->CloseOnDisk();
5920 // Remove temporary files created from the stream
5923 SMESH_File meshFile( meshfile.ToCString() );
5924 if ( !meshFile ) // no meshfile exists
5926 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5930 Engines::Container_var container = GetContainerRef();
5931 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5933 container_i->registerTemporaryFile( filename.ToCString() );
5934 container_i->registerTemporaryFile( meshfile.ToCString() );
5935 container_i->registerTemporaryFile( tmpDir.ToCString() );
5939 pd << ""; // prevent optimizing pd out
5941 // creation of tree nodes for all data objects in the study
5942 // to support tree representation customization and drag-n-drop:
5943 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5944 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5945 useCaseBuilder->SetRootCurrent();
5946 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5947 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5948 for (it->InitEx(true); it->More(); it->Next()) {
5949 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5956 //=============================================================================
5958 * SMESH_Gen_i::LoadASCII
5960 * Load SMESH module's data in ASCII format
5962 //=============================================================================
5964 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5965 const SALOMEDS::TMPFile& theStream,
5967 bool isMultiFile ) {
5968 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5969 return Load( theComponent, theStream, theURL, isMultiFile );
5971 //before call main ::Load method it's need for decipher text format to
5972 //binary ( "|xx" => x' )
5973 int size = theStream.length();
5974 if ( int((size / 3 )*3) != size ) //error size of buffer
5977 int real_size = int(size / 3);
5979 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5982 unsigned int c = -1;
5983 for ( int i = 0; i < real_size; i++ )
5985 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5986 sscanf( tmp, "%x", &c );
5987 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5990 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5992 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5995 //=============================================================================
5997 * SMESH_Gen_i::Close
5999 * Clears study-connected data when it is closed
6001 //=============================================================================
6003 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6005 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6007 // Clear study contexts data
6008 myStudyContext->Clear();
6010 // remove the tmp files meshes are loaded from
6011 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6013 // Clean trace of API methods calls
6019 //=============================================================================
6021 * SMESH_Gen_i::ComponentDataType
6023 * Get component data type
6025 //=============================================================================
6027 char* SMESH_Gen_i::ComponentDataType()
6029 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6030 return CORBA::string_dup( "SMESH" );
6034 //=============================================================================
6036 * SMESH_Gen_i::IORToLocalPersistentID
6038 * Transform data from transient form to persistent
6040 //=============================================================================
6042 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6043 const char* IORString,
6044 CORBA::Boolean /*isMultiFile*/,
6045 CORBA::Boolean /*isASCII*/ )
6047 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6049 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6050 int anId = myStudyContext->findId( IORString );
6052 if(MYDEBUG) MESSAGE( "VSR " << anId )
6054 sprintf( strId, "%d", anId );
6055 return CORBA::string_dup( strId );
6058 return CORBA::string_dup( "" );
6061 //=============================================================================
6063 * SMESH_Gen_i::LocalPersistentIDToIOR
6065 * Transform data from persistent form to transient
6067 //=============================================================================
6069 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6070 const char* aLocalPersistentID,
6071 CORBA::Boolean /*isMultiFile*/,
6072 CORBA::Boolean /*isASCII*/ )
6074 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6076 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6077 int anId = atoi( aLocalPersistentID );
6078 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6080 return CORBA::string_dup( "" );
6083 //=======================================================================
6084 //function : RegisterObject
6086 //=======================================================================
6088 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6090 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6091 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6092 return myStudyContext->addObject( string( iorString.in() ) );
6097 //================================================================================
6099 * \brief Return id of registered object
6100 * \param theObject - the Object
6101 * \retval int - Object id
6103 //================================================================================
6105 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6107 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6108 string iorString = GetORB()->object_to_string( theObject );
6109 return myStudyContext->findId( iorString );
6114 //=============================================================================
6116 * SMESH_Gen_i::SetName
6118 * Set a new object name
6120 //=============================================================================
6121 void SMESH_Gen_i::SetName(const char* theIOR,
6122 const char* theName)
6124 if ( theIOR && strcmp( theIOR, "" ) ) {
6125 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6126 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6127 if ( !aSO->_is_nil() ) {
6128 SetName( aSO, theName );
6133 // Version information
6134 char* SMESH_Gen_i::getVersion()
6136 #if SMESH_DEVELOPMENT
6137 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6139 return CORBA::string_dup(SMESH_VERSION_STR);
6143 //=================================================================================
6144 // function : Move()
6145 // purpose : Moves objects to the specified position.
6146 // Is used in the drag-n-drop functionality.
6147 //=================================================================================
6148 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6149 SALOMEDS::SObject_ptr where,
6152 if ( CORBA::is_nil( where ) ) return;
6154 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6155 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6156 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6157 std::string dataType = father->ComponentDataType();
6158 if ( dataType != "SMESH" ) return; // not a SMESH component
6160 SALOMEDS::SObject_var objAfter;
6161 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6162 // insert at given row -> find insertion position
6163 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6165 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6166 if ( i == row && useCaseIt->More() ) {
6167 objAfter = useCaseIt->Value();
6171 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6172 SALOMEDS::SObject_var sobj = what[i];
6173 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6174 // insert the object to the use case tree
6175 if ( !CORBA::is_nil( objAfter ) )
6176 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6178 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6181 //================================================================================
6183 * \brief Returns true if algorithm can be used to mesh a given geometry
6184 * \param [in] theAlgoType - the algorithm type
6185 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6186 * \param [in] theGeomObject - the geometry to mesh
6187 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6188 * else, returns \c True if at least one shape is meshable
6189 * \return CORBA::Boolean - can or can't
6191 //================================================================================
6193 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6194 const char* theLibName,
6195 GEOM::GEOM_Object_ptr theGeomObject,
6196 CORBA::Boolean toCheckAll)
6200 std::string aPlatformLibName;
6201 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6202 GenericHypothesisCreator_i* aCreator =
6203 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6206 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6207 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6208 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6215 SMESH_CATCH( SMESH::doNothing );
6218 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6223 //=================================================================================
6224 // function : GetInsideSphere
6225 // purpose : Collect indices of elements, which are located inside the sphere
6226 //=================================================================================
6227 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6228 SMESH::ElementType theElemType,
6234 SMESH::long_array_var aResult = new SMESH::long_array();
6235 if ( meshPart->_is_nil() )
6236 return aResult._retn();
6238 // 1. Create geometrical object
6239 gp_Pnt aP( theX, theY, theZ );
6240 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6242 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6244 if ( lst.size() > 0 ) {
6245 aResult->length( lst.size() );
6246 for ( size_t i = 0; i < lst.size(); i++ ) {
6247 aResult[i] = lst[i];
6250 return aResult._retn();
6253 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6254 SMESH::ElementType theElemType,
6255 CORBA::Double theX1,
6256 CORBA::Double theY1,
6257 CORBA::Double theZ1,
6258 CORBA::Double theX2,
6259 CORBA::Double theY2,
6260 CORBA::Double theZ2) {
6261 SMESH::long_array_var aResult = new SMESH::long_array();
6262 if( meshPart->_is_nil() )
6263 return aResult._retn();
6265 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6267 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6269 if( lst.size() > 0 ) {
6270 aResult->length( lst.size() );
6271 for ( size_t i = 0; i < lst.size(); i++ ) {
6272 aResult[i] = lst[i];
6275 return aResult._retn();
6278 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6279 SMESH::ElementType theElemType,
6283 CORBA::Double theDX,
6284 CORBA::Double theDY,
6285 CORBA::Double theDZ,
6287 CORBA::Double theR ){
6288 SMESH::long_array_var aResult = new SMESH::long_array();
6289 if( meshPart->_is_nil() )
6290 return aResult._retn();
6292 gp_Pnt aP( theX, theY, theZ );
6293 gp_Vec aV( theDX, theDY, theDZ );
6294 gp_Ax2 anAxes (aP, aV);
6296 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6298 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6300 if( lst.size() > 0 ) {
6301 aResult->length( lst.size() );
6302 for ( size_t i = 0; i < lst.size(); i++ ) {
6303 aResult[i] = lst[i];
6306 return aResult._retn();
6309 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6310 SMESH::ElementType theElemType,
6311 GEOM::GEOM_Object_ptr theGeom,
6312 CORBA::Double theTolerance ) {
6313 SMESH::long_array_var aResult = new SMESH::long_array();
6314 if( meshPart->_is_nil() || theGeom->_is_nil() )
6315 return aResult._retn();
6317 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6319 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6321 if( lst.size() > 0 ) {
6322 aResult->length( lst.size() );
6323 for ( size_t i = 0; i < lst.size(); i++ ) {
6324 aResult[i] = lst[i];
6327 return aResult._retn();
6332 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6333 SMESH::ElementType theElemType,
6334 TopoDS_Shape& aShape,
6335 double* theTolerance) {
6337 std::vector<long> res;
6338 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6340 if ( mesh->_is_nil() )
6343 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6347 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6352 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6353 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6354 anElementsOnShape->SetAllNodes( true );
6355 anElementsOnShape->SetMesh( meshDS );
6356 anElementsOnShape->SetShape( aShape, aType );
6359 anElementsOnShape->SetTolerance(*theTolerance);
6361 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6362 if ( !msource->_is_nil() ) { // Mesh case
6363 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6365 while ( elemIt->more() ) {
6366 const SMDS_MeshElement* anElem = elemIt->next();
6367 long anId = anElem->GetID();
6368 if ( anElementsOnShape->IsSatisfy( anId ) )
6369 res.push_back( anId );
6373 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6374 if ( !gsource->_is_nil() ) {
6375 if(theElemType == SMESH::NODE) {
6376 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6377 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6378 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6379 long anId = node->GetID();
6380 if ( anElementsOnShape->IsSatisfy( anId ) )
6381 res.push_back( anId );
6384 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6385 SMESH::long_array_var elems = gsource->GetListOfID();
6386 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6387 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6388 long anId = elem->GetID();
6389 if ( anElementsOnShape->IsSatisfy( anId ) )
6390 res.push_back( anId );
6395 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6396 if ( !smsource->_is_nil() ) {
6397 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6398 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6399 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6401 long anId = elem->GetID();
6402 if ( anElementsOnShape->IsSatisfy( anId ) )
6403 res.push_back( anId );
6411 //=============================================================================
6413 * SMESHEngine_factory
6415 * C factory, accessible with dlsym, after dlopen
6417 //=============================================================================
6421 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6422 PortableServer::POA_ptr poa,
6423 PortableServer::ObjectId* contId,
6424 const char* instanceName,
6425 const char* interfaceName )
6427 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6428 if(MYDEBUG) SCRUTE(interfaceName);
6429 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6430 return aSMESHGen->getId() ;