1 // Copyright (C) 2007-2020 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;
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 //=============================================================================
262 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
264 if ( myLCC == NULL ) {
265 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
270 //=============================================================================
272 * GetGeomEngine [ static ]
274 * Get GEOM::GEOM_Gen reference
276 //=============================================================================
278 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( bool isShaper )
280 Engines::EngineComponent_ptr temp =
281 GetLCC()->FindOrLoad_Component( isShaper ? "FactoryServer" : "FactoryServer",
282 isShaper ? "SHAPERSTUDY" : "GEOM" );
283 myGeomGen = GEOM::GEOM_Gen::_narrow( temp );
288 //=============================================================================
290 * GetGeomEngine [ static ]
292 * Get GEOM::GEOM_Gen reference
294 //=============================================================================
296 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
298 GEOM::GEOM_Gen_ptr gen;
299 if ( !CORBA::is_nil( go ))
304 //=============================================================================
306 * SMESH_Gen_i::SMESH_Gen_i
308 * Default constructor: not for use
310 //=============================================================================
312 SMESH_Gen_i::SMESH_Gen_i()
316 //=============================================================================
318 * SMESH_Gen_i::SMESH_Gen_i
320 * Standard constructor, used with Container
322 //=============================================================================
324 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
325 PortableServer::POA_ptr poa,
326 PortableServer::ObjectId* contId,
327 const char* instanceName,
328 const char* interfaceName )
329 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
332 myOrb = CORBA::ORB::_duplicate(orb);
333 myPoa = PortableServer::POA::_duplicate(poa);
336 _id = myPoa->activate_object( _thisObj );
338 myStudyContext = new StudyContext;
340 myIsEmbeddedMode = false;
341 myIsEnablePublish = true;
342 myShapeReader = NULL; // shape reader
344 myIsHistoricalPythonDump = true;
345 myToForgetMeshDataOnHypModif = false;
347 // set it in standalone mode only
348 //OSD::SetSignal( true );
350 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
351 // find out mode (embedded or standalone) here else
352 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
353 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
354 if ( SALOME_NamingService* ns = GetNS() )
356 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
357 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
358 if ( !session->_is_nil() )
360 CORBA::String_var str_host = session->getHostname();
361 CORBA::Long s_pid = session->getPID();
362 string my_host = Kernel_Utils::GetHostname();
364 long my_pid = (long)_getpid();
366 long my_pid = (long) getpid();
368 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
373 //=============================================================================
375 * SMESH_Gen_i::~SMESH_Gen_i
379 //=============================================================================
381 SMESH_Gen_i::~SMESH_Gen_i()
383 // delete hypothesis creators
384 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
385 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
387 // same creator can be mapped under different names
388 GenericHypothesisCreator_i* creator = (*itHyp).second;
392 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
393 if ( creator == (*itHyp2).second )
394 (*itHyp2).second = 0;
396 myHypCreatorMap.clear();
398 // Clear study contexts data
399 delete myStudyContext;
401 // delete shape reader
403 delete myShapeReader;
406 //=============================================================================
408 * SMESH_Gen_i::getHypothesisCreator
410 * Get hypothesis creator
412 //=============================================================================
414 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
415 const char* theLibName,
416 std::string& thePlatformLibName)
419 std::string aPlatformLibName;
420 /* It's Need to translate lib name for WIN32 or X platform */
421 if ( theLibName && theLibName[0] != '\0' )
423 int libNameLen = strlen(theLibName);
424 //check for old format "libXXXXXXX.so"
425 if (libNameLen > 7 &&
426 !strncmp( theLibName, "lib", 3 ) &&
427 !strcmp( theLibName+libNameLen-3, ".so" ))
431 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
432 #elif defined(__APPLE__)
433 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
435 aPlatformLibName = theLibName;
440 //try to use new format
442 aPlatformLibName = theLibName;
443 aPlatformLibName += ".dll";
444 #elif defined(__APPLE__)
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
447 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
451 thePlatformLibName = aPlatformLibName;
453 Unexpect aCatch(SALOME_SalomeException);
454 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
456 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
457 GenericHypothesisCreator_i* aCreator;
460 // check, if creator for this hypothesis type already exists
461 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
463 // load plugin library
464 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
467 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
469 const char* path = aPlatformLibName.c_str();
472 const char* path = aPlatformLibName.c_str();
474 LibHandle libHandle = LoadLib( path );
475 #if defined(WIN32) && defined(UNICODE)
480 // report any error, if occurred
482 const char* anError = dlerror();
483 throw(SALOME_Exception( anError ));
485 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
486 << aPlatformLibName));
490 // get method, returning hypothesis creator
491 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
492 GetHypothesisCreator procHandle =
493 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
496 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
497 << aPlatformLibName ));
498 UnLoadLib(libHandle);
501 // get hypothesis creator
502 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
503 aCreator = procHandle(theHypName);
506 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
507 << aPlatformLibName));
509 // map hypothesis creator to a hypothesis name
510 myHypCreatorMap[string(theHypName)] = aCreator;
515 return myHypCreatorMap[string(theHypName)];
518 catch (SALOME_Exception& S_ex)
520 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
525 //=============================================================================
527 * SMESH_Gen_i::createHypothesis
529 * Create hypothesis of given type
531 //=============================================================================
533 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
534 const char* theLibName)
536 SMESH_Hypothesis_i* myHypothesis_i = 0;
537 SMESH::SMESH_Hypothesis_var hypothesis_i;
538 std::string aPlatformLibName;
539 GenericHypothesisCreator_i* aCreator =
540 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
542 // create a new hypothesis object, store its ref. in studyContext
543 myHypothesis_i = aCreator->Create(myPoa, &myGen);
546 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
547 CORBA::String_var hypName = myHypothesis_i->GetName();
548 myHypCreatorMap[ hypName.in() ] = aCreator;
550 // activate the CORBA servant of hypothesis
551 hypothesis_i = myHypothesis_i->_this();
552 int nextId = RegisterObject( hypothesis_i );
553 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
554 else { nextId = 0; } // avoid "unused variable" warning in release mode
556 return hypothesis_i._retn();
559 //=============================================================================
561 * SMESH_Gen_i::createMesh
563 * Create empty mesh on shape
565 //=============================================================================
567 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
570 Unexpect aCatch(SALOME_SalomeException);
571 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
573 // Get or create the GEOM_Client instance
575 // create a new mesh object servant, store it in a map in study context
576 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
577 // create a new mesh object
578 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
579 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
581 // activate the CORBA servant of Mesh
582 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
583 int nextId = RegisterObject( mesh );
584 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
585 else { nextId = 0; } // avoid "unused variable" warning in release mode
588 catch (SALOME_Exception& S_ex) {
589 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
591 return SMESH::SMESH_Mesh::_nil();
594 //=============================================================================
596 * SMESH_Gen_i::GetShapeReader
600 //=============================================================================
602 GEOM_Client* SMESH_Gen_i::GetShapeReader()
604 // create shape reader if necessary
605 if ( !myShapeReader )
606 myShapeReader = new GEOM_Client(GetContainerRef());
607 ASSERT( myShapeReader );
608 return myShapeReader;
611 //=============================================================================
613 * SMESH_Gen_i::SetGeomEngine
615 * Set GEOM::GEOM_Gen reference
617 //=============================================================================
619 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
621 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
624 //=============================================================================
626 * SMESH_Gen_i::SetEmbeddedMode
630 //=============================================================================
632 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
634 myIsEmbeddedMode = theMode;
636 if ( !myIsEmbeddedMode ) {
637 //PAL10867: disable signals catching with "noexcepthandler" option
638 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
639 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
644 char* envDisableFPE = getenv("DISABLE_FPE");
645 if (envDisableFPE && atoi(envDisableFPE))
650 OSD::SetSignal( raiseFPE );
652 // else OSD::SetSignal() is called in GUI
656 //=============================================================================
658 * SMESH_Gen_i::IsEmbeddedMode
662 //=============================================================================
664 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
666 return myIsEmbeddedMode;
669 //=============================================================================
671 * SMESH_Gen_i::SetEnablePublish
673 * Set enable publishing in the study
675 //=============================================================================
677 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
679 myIsEnablePublish = theIsEnablePublish;
682 //=============================================================================
684 * SMESH_Gen_i::IsEnablePublish
686 * Check enable publishing
688 //=============================================================================
690 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
692 return myIsEnablePublish;
695 //=============================================================================
697 * SMESH_Gen_i::UpdateStudy
699 * Update study (needed at switching GEOM->SMESH)
701 //=============================================================================
703 void SMESH_Gen_i::UpdateStudy()
705 if ( !myStudyContext )
706 myStudyContext = new StudyContext;
708 SALOMEDS::Study_var aStudy = getStudyServant();
709 if ( !CORBA::is_nil( aStudy ) )
711 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
713 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
714 if( !GEOM_var->_is_nil() )
715 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
717 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
718 if( !GEOM_var->_is_nil() )
719 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
721 // NPAL16168, issue 0020210
722 // Let meshes update their data depending on GEOM groups that could change
723 CORBA::String_var compDataType = ComponentDataType();
724 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
725 if ( !me->_is_nil() ) {
726 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
727 for ( ; anIter->More(); anIter->Next() ) {
728 SALOMEDS::SObject_wrap so = anIter->Value();
729 CORBA::Object_var ior = SObjectToObject( so );
730 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
731 mesh->CheckGeomModif();
737 //================================================================================
739 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
741 //================================================================================
743 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
745 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
746 SALOMEDS::GenericAttribute_wrap attr;
747 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
749 SALOMEDS::AttributePixMap_wrap pm = attr;
750 CORBA::String_var ico = pm->GetPixMap();
751 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
756 //=================================================================================
757 // function : hasObjectInfo()
758 // purpose : shows if module provides information for its objects
759 //=================================================================================
761 bool SMESH_Gen_i::hasObjectInfo()
766 //=================================================================================
767 // function : getObjectInfo()
768 // purpose : returns an information for a given object by its entry
769 //=================================================================================
771 char* SMESH_Gen_i::getObjectInfo( const char* entry )
773 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
774 // for the rest, "module 'SMESH', ID=0:1:2:*"
778 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
779 CORBA::Object_var obj = SObjectToObject( so );
780 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
781 if ( isGeomModifIcon( mesh ))
783 txt << "The geometry was changed and the mesh needs to be recomputed";
788 CORBA::String_var compType = ComponentDataType();
789 txt << "module '" << compType << "', ID=" << entry;
791 return CORBA::string_dup( txt );
794 //=============================================================================
796 * SMESH_Gen_i::GetStudyContext
800 //=============================================================================
802 StudyContext* SMESH_Gen_i::GetStudyContext()
804 return myStudyContext;
807 //=============================================================================
809 * SMESH_Gen_i::CreateHypothesis
811 * Create hypothesis/algorithm of given type and publish it in the study
813 //=============================================================================
815 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
816 const char* theLibName )
819 Unexpect aCatch(SALOME_SalomeException);
820 // Create hypothesis/algorithm
821 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
823 // Publish hypothesis/algorithm in the study
824 if ( CanPublishInStudy( hyp ) ) {
825 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
826 if ( !aSO->_is_nil() ) {
827 // Update Python script
828 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
829 << theHypName << "', '" << theLibName << "')";
836 //================================================================================
838 * \brief Return a hypothesis initialized by given average length.
839 * \param theHypType - hypothesis type name
840 * \param theLibName - plugin library name
841 * \param theAverageLength - average length
842 * \param theQuadDominated - is quad-dominated flag
843 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
845 //================================================================================
847 SMESH::SMESH_Hypothesis_ptr
848 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
849 const char* theLibName,
850 CORBA::Double theAverageLength,
851 CORBA::Boolean theQuadDominated)
854 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
855 theAverageLength, theQuadDominated };
857 SMESH::SMESH_Hypothesis_var hyp =
858 GetHypothesisParameterValues( theHypType, theLibName,
859 SMESH::SMESH_Mesh::_nil(),
860 GEOM::GEOM_Object::_nil(),
862 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
864 TPythonDump() << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
865 << theHypType << "', '"
866 << theLibName << "', "
867 << theAverageLength << ", "
868 << theQuadDominated << " )";
873 //================================================================================
875 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
876 * existing on the given geometry or to size of the geometry.
877 * \param theHypType - hypothesis type name
878 * \param theLibName - plugin library name
879 * \param theMesh - The mesh of interest
880 * \param theGeom - The shape to get parameter values from
881 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
882 * in a study and used to compute the mesh, or a temporary one created just to pass
885 //================================================================================
887 SMESH::SMESH_Hypothesis_ptr
888 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
889 const char* theLibName,
890 SMESH::SMESH_Mesh_ptr theMesh,
891 GEOM::GEOM_Object_ptr theGeom,
892 const SMESH::HypInitParams& theParams)
895 Unexpect aCatch(SALOME_SalomeException);
897 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
898 if ( byMesh && CORBA::is_nil( theMesh ) )
899 return SMESH::SMESH_Hypothesis::_nil();
900 if ( byMesh && CORBA::is_nil( theGeom ) )
901 return SMESH::SMESH_Hypothesis::_nil();
903 // -----------------------------------------------
904 // find hypothesis used to mesh theGeom
905 // -----------------------------------------------
907 // get mesh and shape
908 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
909 TopoDS_Shape shape = GeomObjectToShape( theGeom );
910 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
911 return SMESH::SMESH_Hypothesis::_nil();
912 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
914 // create a temporary hypothesis to know its dimension
915 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
916 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
918 return SMESH::SMESH_Hypothesis::_nil();
919 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
922 // look for a hypothesis of theHypType used to mesh the shape
923 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
926 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
927 int nbLocalHyps = aHypList->length();
928 for ( int i = 0; i < nbLocalHyps; i++ ) {
929 CORBA::String_var hypName = aHypList[i]->GetName();
930 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
931 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
933 // check super shapes
934 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
935 while ( nbLocalHyps == 0 && itShape.More() ) {
936 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
937 if ( ! CORBA::is_nil( geomObj )) {
938 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
939 nbLocalHyps = aHypList->length();
940 for ( int i = 0; i < nbLocalHyps; i++ )
941 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
942 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
948 // let the temporary hypothesis find out somehow parameter values by mesh
949 if ( hyp->SetParametersByMesh( mesh, shape ))
950 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
954 ::SMESH_Hypothesis::TDefaults dflts;
955 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
956 dflts._nbSegments = myGen.GetDefaultNbSegments();
957 dflts._elemLength = theParams.averageLength;
958 dflts._quadDominated = theParams.quadDominated;
959 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
962 dflts._diagonal = mesh->GetShapeDiagonalSize();
964 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
965 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
966 dflts._shape = &shape;
969 // let the hypothesis initialize it's values
970 if ( hyp->SetParametersByDefaults( dflts, mesh ))
971 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
974 return SMESH::SMESH_Hypothesis::_nil();
977 //=============================================================================
979 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
980 * \param [in] theHyp - the hypothesis of interest
981 * \param [out] theMesh - the sole mesh using \a theHyp
982 * \param [out] theShape - the sole geometry \a theHyp is assigned to
983 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
985 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
986 * considered as SAME sub-mesh => result is \c true.
987 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
988 * a shape to which an hyp being edited is assigned.
990 //=============================================================================
992 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
993 SMESH::SMESH_Mesh_out theMesh,
994 GEOM::GEOM_Object_out theShape)
996 if ( CORBA::is_nil( theHyp ))
999 // get Mesh component SO
1000 CORBA::String_var compDataType = ComponentDataType();
1001 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1002 if ( CORBA::is_nil( comp ))
1005 // look for child SO of meshes
1006 SMESH::SMESH_Mesh_var foundMesh;
1007 TopoDS_Shape foundShape;
1009 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1010 for ( ; meshIter->More() && isSole; meshIter->Next() )
1012 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1013 CORBA::Object_var obj = SObjectToObject( curSO );
1014 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1018 // look for a sole shape where theHyp is assigned
1019 bool isHypFound = false;
1020 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1021 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1022 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1024 const THypList& hyps = s2hypsIt.Value();
1025 THypList::const_iterator h = hyps.begin();
1026 for ( ; h != hyps.end(); ++h )
1027 if ( (*h)->GetID() == theHyp->GetId() )
1029 if ( h != hyps.end()) // theHyp found
1032 if ( ! foundShape.IsNull() &&
1033 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1035 foundShape.Nullify();
1039 foundShape = s2hypsIt.Key();
1041 } // loop on assigned hyps
1043 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1045 if ( !foundMesh->_is_nil() ) // not a sole mesh
1047 if ( !foundMesh->HasShapeToMesh() ||
1048 !mesh_i ->HasShapeToMesh() )
1050 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1054 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1055 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1056 isSole = s1->IsSame( s2 );
1059 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1065 ! foundMesh->_is_nil() &&
1066 ! foundShape.IsNull() )
1068 theMesh = foundMesh._retn();
1069 theShape = ShapeToGeomObject( foundShape );
1070 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1075 //=============================================================================
1077 * Set number of segments per diagonal of boundary box of geometry by which
1078 * default segment length of appropriate 1D hypotheses is defined
1080 //=============================================================================
1082 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1085 if ( theNbSegments > 0 )
1086 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1088 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1091 //=============================================================================
1093 * \brief Set default number of segments per edge
1095 //=============================================================================
1097 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1100 if ( theNbSegments > 0 )
1101 myGen.SetDefaultNbSegments( int(theNbSegments) );
1103 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1106 //=============================================================================
1108 * Set an option value
1110 //=============================================================================
1112 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1114 if ( name && value && strlen( value ) > 0 )
1117 if ( strcmp(name, "historical_python_dump") == 0 )
1119 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1120 msgToGUI = "preferences/SMESH/historical_python_dump/";
1121 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1123 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1125 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1126 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1127 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1129 else if ( strcmp(name, "default_grp_color") == 0 )
1133 // color must be presented as a string of following form:
1134 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1135 str = str.substr(1);
1136 for ( size_t i = 0; i < str.length()/2; i++ )
1137 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1138 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1140 else if ( value ) { // rgb color ("255,170,0", for example)
1141 string tempValue( value );
1142 char* colorValue = strtok( &tempValue[0], "," );
1143 while ( colorValue != NULL ) {
1144 int c_value = atoi( colorValue );
1145 if ( c_value >= 0 && c_value <= 255 )
1146 color.push_back( c_value );
1147 colorValue = strtok( NULL, "," );
1150 if ( color.size() == 3 ) { // color must have three valid component
1151 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1152 myDefaultGroupColor = value;
1153 msgToGUI = "preferences/SMESH/default_grp_color/";
1158 // update preferences in case if SetOption() is invoked from python console
1159 if ( !msgToGUI.empty() )
1161 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1162 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1163 if ( !CORBA::is_nil( session ) )
1164 session->emitMessageOneWay(msgToGUI.c_str());
1169 //=============================================================================
1171 * Return an option value
1173 //=============================================================================
1175 char* SMESH_Gen_i::GetOption(const char* name)
1179 if ( strcmp(name, "historical_python_dump") == 0 )
1181 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1183 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1185 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1187 if ( strcmp(name, "default_grp_color") == 0 )
1189 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1192 return CORBA::string_dup( "" );
1195 //=============================================================================
1197 * SMESH_Gen_i::CreateMesh
1199 * Create empty mesh on a shape and publish it in the study
1201 //=============================================================================
1203 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1206 Unexpect aCatch(SALOME_SalomeException);
1207 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1209 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1211 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1212 ASSERT( meshServant );
1213 meshServant->SetShape( theShapeObject );
1215 // publish mesh in the study
1216 if ( CanPublishInStudy( mesh ) ) {
1217 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1218 aStudyBuilder->NewCommand(); // There is a transaction
1219 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1220 aStudyBuilder->CommitCommand();
1221 if ( !aSO->_is_nil() ) {
1222 // Update Python script
1223 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1227 return mesh._retn();
1230 //=============================================================================
1232 * SMESH_Gen_i::CreateEmptyMesh
1236 //=============================================================================
1238 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1241 Unexpect aCatch(SALOME_SalomeException);
1242 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1244 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1246 // publish mesh in the study
1247 if ( CanPublishInStudy( mesh ) ) {
1248 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1249 aStudyBuilder->NewCommand(); // There is a transaction
1250 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1251 aStudyBuilder->CommitCommand();
1252 if ( !aSO->_is_nil() ) {
1253 // Update Python script
1254 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1258 return mesh._retn();
1263 //================================================================================
1265 * \brief Throw an exception in case if the file can't be read
1267 //================================================================================
1269 void checkFileReadable( const char* theFileName )
1271 SMESH_File f ( theFileName );
1274 if ( !f.error().empty() )
1275 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1277 THROW_SALOME_CORBA_EXCEPTION
1278 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1279 SALOME::BAD_PARAM );
1284 //=============================================================================
1286 * SMESH_Gen_i::CreateMeshFromUNV
1288 * Create mesh and import data from UNV file
1290 //=============================================================================
1292 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1295 Unexpect aCatch(SALOME_SalomeException);
1297 checkFileReadable( theFileName );
1299 SMESH::SMESH_Mesh_var aMesh = createMesh();
1301 // publish mesh in the study
1302 if ( CanPublishInStudy( aMesh ) ) {
1303 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1304 aStudyBuilder->NewCommand(); // There is a transaction
1305 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1306 aStudyBuilder->CommitCommand();
1307 if ( !aSO->_is_nil() ) {
1308 // Update Python script
1309 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1313 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1315 aServant->ImportUNVFile( theFileName );
1317 // Dump creation of groups
1318 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1320 aServant->GetImpl().GetMeshDS()->Modified();
1321 return aMesh._retn();
1324 //=============================================================================
1326 * SMESH_Gen_i::CreateMeshFromMED
1328 * Create mesh and import data from MED file
1330 //=============================================================================
1332 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1333 SMESH::DriverMED_ReadStatus& theStatus,
1334 const char* theCommandNameForPython,
1335 const char* theFileNameForPython)
1338 char bname[ _MAX_FNAME ];
1339 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1340 string aFileName = bname;
1342 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1344 // Retrieve mesh names from the file
1345 DriverMED_R_SMESHDS_Mesh myReader;
1346 myReader.SetFile( theFileName );
1347 myReader.SetMeshId( -1 );
1348 Driver_Mesh::Status aStatus;
1349 list<string> aNames = myReader.GetMeshNames(aStatus);
1350 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1351 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1353 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1356 TPythonDump aPythonDump;
1357 aPythonDump << "([";
1359 if (theStatus == SMESH::DRS_OK) {
1360 SALOMEDS::StudyBuilder_var aStudyBuilder;
1361 aStudyBuilder = getStudyServant()->NewBuilder();
1362 aStudyBuilder->NewCommand(); // There is a transaction
1364 aResult->length( aNames.size() );
1367 // Iterate through all meshes and create mesh objects
1368 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1371 if (i > 0) aPythonDump << ", ";
1374 SMESH::SMESH_Mesh_var mesh = createMesh();
1376 // publish mesh in the study
1377 SALOMEDS::SObject_wrap aSO;
1378 if ( CanPublishInStudy( mesh ) )
1379 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1380 // - as names of meshes are stored in MED file, we use them for data publishing
1381 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1382 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1385 if ( !aSO->_is_nil() ) {
1388 aPythonDump << "mesh_" << i;
1391 // Read mesh data (groups are published automatically by ImportMEDFile())
1392 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1393 ASSERT( meshServant );
1394 SMESH::DriverMED_ReadStatus status1 =
1395 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1396 if (status1 > theStatus)
1397 theStatus = status1;
1399 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1400 meshServant->GetImpl().GetMeshDS()->Modified();
1402 if ( !aStudyBuilder->_is_nil() )
1403 aStudyBuilder->CommitCommand();
1406 // Update Python script
1407 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1409 // Dump creation of groups
1410 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1411 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1413 return aResult._retn();
1416 //================================================================================
1418 * \brief Create meshes by reading a MED file
1420 //================================================================================
1422 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1423 SMESH::DriverMED_ReadStatus& theStatus)
1426 Unexpect aCatch(SALOME_SalomeException);
1427 checkFileReadable( theFileName );
1429 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1430 "CreateMeshesFromMED", theFileName);
1434 //=============================================================================
1436 * SMESH_Gen_i::CreateMeshFromSAUV
1438 * Create mesh and import data from SAUV file
1440 //=============================================================================
1442 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1443 SMESH::DriverMED_ReadStatus& theStatus)
1446 Unexpect aCatch(SALOME_SalomeException);
1447 checkFileReadable( theFileName );
1449 std::string sauvfilename(theFileName);
1450 std::string medfilename(theFileName);
1451 medfilename += ".med";
1454 cmd = "%PYTHONBIN% ";
1459 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1461 system(cmd.c_str());
1462 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1464 "CreateMeshesFromSAUV",
1465 sauvfilename.c_str());
1467 cmd = "%PYTHONBIN% ";
1472 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1474 system(cmd.c_str());
1478 //=============================================================================
1480 * SMESH_Gen_i::CreateMeshFromSTL
1482 * Create mesh and import data from STL file
1484 //=============================================================================
1486 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1489 Unexpect aCatch(SALOME_SalomeException);
1490 checkFileReadable( theFileName );
1492 SMESH::SMESH_Mesh_var aMesh = createMesh();
1495 char bname[ _MAX_FNAME ];
1496 _splitpath( theFileName, NULL, NULL, bname, NULL );
1497 string aFileName = bname;
1499 string aFileName = basename( const_cast<char *>(theFileName) );
1501 // publish mesh in the study
1502 if ( CanPublishInStudy( aMesh ) ) {
1503 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1504 aStudyBuilder->NewCommand(); // There is a transaction
1505 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1506 aStudyBuilder->CommitCommand();
1507 if ( !aSO->_is_nil() ) {
1508 // Update Python script
1509 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1513 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1515 aServant->ImportSTLFile( theFileName );
1516 aServant->GetImpl().GetMeshDS()->Modified();
1517 return aMesh._retn();
1520 //================================================================================
1522 * \brief Create meshes and import data from the CGSN file
1524 //================================================================================
1526 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1527 SMESH::DriverMED_ReadStatus& theStatus)
1530 Unexpect aCatch(SALOME_SalomeException);
1531 checkFileReadable( theFileName );
1533 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1536 // Retrieve nb meshes from the file
1537 DriverCGNS_Read myReader;
1538 myReader.SetFile( theFileName );
1539 Driver_Mesh::Status aStatus;
1540 int nbMeshes = myReader.GetNbMeshes(aStatus);
1541 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1543 aResult->length( nbMeshes );
1545 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1548 TPythonDump aPythonDump;
1549 aPythonDump << "([";
1551 if (theStatus == SMESH::DRS_OK)
1553 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1554 aStudyBuilder->NewCommand(); // There is a transaction
1558 // Iterate through all meshes and create mesh objects
1559 for ( ; i < nbMeshes; ++i )
1562 if (i > 0) aPythonDump << ", ";
1565 SMESH::SMESH_Mesh_var mesh = createMesh();
1566 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1568 // Read mesh data (groups are published automatically by ImportMEDFile())
1569 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1570 ASSERT( meshServant );
1572 SMESH::DriverMED_ReadStatus status1 =
1573 meshServant->ImportCGNSFile( theFileName, i, meshName );
1574 if (status1 > theStatus)
1575 theStatus = status1;
1577 meshServant->GetImpl().GetMeshDS()->Modified();
1578 // publish mesh in the study
1579 SALOMEDS::SObject_wrap aSO;
1580 if ( CanPublishInStudy( mesh ) )
1581 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1584 if ( !aSO->_is_nil() ) {
1588 aPythonDump << "mesh_" << i;
1591 aStudyBuilder->CommitCommand();
1594 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1596 // Dump creation of groups
1597 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1598 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1600 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1603 return aResult._retn();
1606 //================================================================================
1608 * \brief Create a mesh and import data from a GMF file
1610 //================================================================================
1612 SMESH::SMESH_Mesh_ptr
1613 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1614 CORBA::Boolean theMakeRequiredGroups,
1615 SMESH::ComputeError_out theError)
1618 Unexpect aCatch(SALOME_SalomeException);
1619 checkFileReadable( theFileName );
1621 SMESH::SMESH_Mesh_var aMesh = createMesh();
1623 char bname[ _MAX_FNAME ];
1624 _splitpath( theFileName, NULL, NULL, bname, NULL );
1625 string aFileName = bname;
1627 string aFileName = basename( const_cast<char *>(theFileName) );
1629 // publish mesh in the study
1630 if ( CanPublishInStudy( aMesh ) ) {
1631 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1632 aStudyBuilder->NewCommand(); // There is a transaction
1633 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1634 aStudyBuilder->CommitCommand();
1635 if ( !aSO->_is_nil() ) {
1636 // Update Python script
1637 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1638 << theFileName << "', "
1639 << theMakeRequiredGroups << " )";
1642 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1644 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1645 aServant->GetImpl().GetMeshDS()->Modified();
1646 return aMesh._retn();
1650 //=============================================================================
1652 * SMESH_Gen_i::IsReadyToCompute
1654 * Return true if mesh contains enough data to be computed
1656 //=============================================================================
1658 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1659 GEOM::GEOM_Object_ptr theShapeObject )
1662 Unexpect aCatch(SALOME_SalomeException);
1663 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1665 if ( CORBA::is_nil( theShapeObject ) )
1666 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1667 SALOME::BAD_PARAM );
1668 if ( CORBA::is_nil( theMesh ) )
1669 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1670 SALOME::BAD_PARAM );
1673 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1674 ASSERT( meshServant );
1675 if ( meshServant ) {
1676 // get local TopoDS_Shape
1677 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1678 // call implementation
1679 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1680 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1683 catch ( SALOME_Exception& S_ex ) {
1684 INFOS( "catch exception "<< S_ex.what() );
1689 //================================================================================
1691 * \brief Find SObject for an algo
1693 //================================================================================
1695 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1698 SALOMEDS::Study_var aStudy = getStudyServant();
1699 if ( !aStudy->_is_nil() ) {
1700 // find algo in the study
1701 CORBA::String_var compDataType = ComponentDataType();
1702 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1703 if ( !father->_is_nil() ) {
1704 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1705 for ( ; itBig->More(); itBig->Next() ) {
1706 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1707 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1708 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1709 for ( ; algoIt->More(); algoIt->Next() ) {
1710 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1711 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1712 if ( !CORBA::is_nil( algoIOR )) {
1713 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1714 if ( impl && impl->GetImpl() == algo )
1715 return algoSO._retn();
1717 } // loop on algo SO's
1720 } // SMESH component iterator
1724 return SALOMEDS::SObject::_nil();
1727 //================================================================================
1729 * \brief Return errors of mesh computation
1731 //================================================================================
1733 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1734 GEOM::GEOM_Object_ptr theSubObject )
1737 Unexpect aCatch(SALOME_SalomeException);
1738 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1740 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1741 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1743 if ( CORBA::is_nil( theMesh ) )
1744 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1746 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1748 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1751 if(theMesh->HasShapeToMesh())
1752 shape = GeomObjectToShape( theSubObject );
1754 shape = SMESH_Mesh::PseudoShape();
1756 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1758 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1761 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1762 const bool includeSelf = true, complexShapeFirst = true;
1763 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1765 while ( smIt->more() )
1768 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1770 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1771 if ( error && !error->IsOK() )
1773 if ( !( error->myAlgo ) &&
1774 !( error->myAlgo = sm->GetAlgo() ))
1776 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1777 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1778 errStruct.comment = error->myComment.c_str();
1779 errStruct.subShapeID = sm->GetId();
1780 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1781 if ( !algoSO->_is_nil() ) {
1782 CORBA::String_var algoName = algoSO->GetName();
1783 errStruct.algoName = algoName;
1786 errStruct.algoName = error->myAlgo->GetName();
1788 errStruct.hasBadMesh = error->HasBadElems();
1791 error_array->length( nbErr );
1794 catch ( SALOME_Exception& S_ex ) {
1795 INFOS( "catch exception "<< S_ex.what() );
1798 return error_array._retn();
1801 //================================================================================
1803 * \brief Return mesh elements preventing computation of a subshape
1805 //================================================================================
1807 SMESH::MeshPreviewStruct*
1808 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1809 CORBA::Short theSubShapeID )
1812 Unexpect aCatch(SALOME_SalomeException);
1813 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1815 if ( CORBA::is_nil( theMesh ) )
1816 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1818 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1821 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1823 // mesh implementation
1824 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1825 // submesh by subshape id
1826 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1829 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1830 if ( error && error->HasBadElems() )
1832 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1833 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1835 // get nodes of elements and count elements
1836 TNode2LocalIDMap mapNode2LocalID;
1837 list< TNodeLocalID > connectivity;
1838 int i, nbElements = 0, nbConnNodes = 0;
1840 const list<const SMDS_MeshElement*>& badElems =
1841 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1842 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1843 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1844 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1846 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1847 while ( nIt->more() )
1848 connectivity.push_back
1849 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1851 // fill node coords and assign local ids to the nodes
1852 int nbNodes = mapNode2LocalID.size();
1853 result->nodesXYZ.length( nbNodes );
1854 TNodeLocalID node2ID = mapNode2LocalID.begin();
1855 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1856 node2ID->second = i;
1857 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1858 result->nodesXYZ[i].x = node->X();
1859 result->nodesXYZ[i].y = node->Y();
1860 result->nodesXYZ[i].z = node->Z();
1862 // fill connectivity
1863 result->elementConnectivities.length( nbConnNodes );
1864 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1865 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1866 result->elementConnectivities[i] = (*connIt)->second;
1868 // fill element types
1869 result->elementTypes.length( nbElements );
1870 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1872 const SMDS_MeshElement* elem = *elemIt;
1873 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1874 result->elementTypes[i].isPoly = elem->IsPoly();
1875 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1881 catch ( SALOME_Exception& S_ex ) {
1882 INFOS( "catch exception "<< S_ex.what() );
1885 return result._retn();
1888 //================================================================================
1890 * \brief Create a group of elements preventing computation of a sub-shape
1892 //================================================================================
1894 SMESH::ListOfGroups*
1895 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1896 CORBA::Short theSubShapeID,
1897 const char* theGroupName )
1900 Unexpect aCatch(SALOME_SalomeException);
1902 SMESH::ListOfGroups_var groups;
1904 if ( CORBA::is_nil( theMesh ) )
1905 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1908 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1910 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1911 TPythonDump() << groups << " = " << this
1912 << ".MakeGroupsOfBadInputElements( "
1913 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1916 catch ( SALOME_Exception& S_ex ) {
1917 INFOS( "catch exception "<< S_ex.what() );
1919 return groups._retn();
1922 //================================================================================
1924 * \brief Returns errors of hypotheses definition
1925 * \param theMesh - the mesh
1926 * \param theSubObject - the main or sub- shape
1927 * \retval SMESH::algo_error_array* - sequence of errors
1929 //================================================================================
1931 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1932 GEOM::GEOM_Object_ptr theSubObject )
1935 Unexpect aCatch(SALOME_SalomeException);
1936 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1938 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1939 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1941 if ( CORBA::is_nil( theMesh ) )
1942 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1944 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1946 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1947 ASSERT( meshServant );
1948 if ( meshServant ) {
1949 TopoDS_Shape myLocShape;
1950 if(theMesh->HasShapeToMesh())
1951 myLocShape = GeomObjectToShape( theSubObject );
1953 myLocShape = SMESH_Mesh::PseudoShape();
1955 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1956 list< ::SMESH_Gen::TAlgoStateError > error_list;
1957 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1958 // call ::SMESH_Gen::GetAlgoState()
1959 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1960 error_array->length( error_list.size() );
1962 for ( error = error_list.begin(); error != error_list.end(); ++error )
1964 // fill AlgoStateError structure
1965 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1966 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1967 errStruct.algoDim = error->_algoDim;
1968 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1969 errStruct.algoName = "";
1970 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1971 if ( !algoSO->_is_nil() ) {
1972 CORBA::String_var algoName = algoSO->GetName();
1973 errStruct.algoName = algoName.in();
1978 catch ( SALOME_Exception& S_ex ) {
1979 INFOS( "catch exception "<< S_ex.what() );
1981 return error_array._retn();
1984 //=============================================================================
1986 * SMESH_Gen_i::GetSubShapesId
1988 * Get sub-shapes unique ID's list
1990 //=============================================================================
1993 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1994 const SMESH::object_array& theListOfSubShapeObject )
1997 Unexpect aCatch(SALOME_SalomeException);
1998 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
2000 SMESH::long_array_var shapesId = new SMESH::long_array;
2003 if ( CORBA::is_nil( theMainShapeObject ) )
2004 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2008 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
2009 TopTools_IndexedMapOfShape myIndexToShape;
2010 TopExp::MapShapes(myMainShape,myIndexToShape);
2012 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
2014 GEOM::GEOM_Object_var aShapeObject
2015 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
2016 if ( CORBA::is_nil( aShapeObject ) )
2017 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
2018 SALOME::BAD_PARAM );
2020 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
2021 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2023 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2024 setId.insert(myIndexToShape.FindIndex(F));
2025 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2027 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2029 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2030 setId.insert(myIndexToShape.FindIndex(E));
2031 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2033 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2035 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2036 setId.insert(myIndexToShape.FindIndex(V));
2037 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2040 shapesId->length(setId.size());
2041 set<int>::iterator iind;
2043 for (iind = setId.begin(); iind != setId.end(); iind++)
2045 if(MYDEBUG) SCRUTE((*iind));
2046 shapesId[i] = (*iind);
2047 if(MYDEBUG) SCRUTE(shapesId[i]);
2051 catch (SALOME_Exception& S_ex)
2053 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2056 return shapesId._retn();
2059 //=============================================================================
2061 * SMESH_Gen_i::Compute
2063 * Compute mesh on a shape
2065 //=============================================================================
2067 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2068 GEOM::GEOM_Object_ptr theShapeObject )
2072 Unexpect aCatch(SALOME_SalomeException);
2073 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2075 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2076 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2077 SALOME::BAD_PARAM );
2079 if ( CORBA::is_nil( theMesh ) )
2080 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2081 SALOME::BAD_PARAM );
2083 // Update Python script
2084 TPythonDump() << "isDone = " << this << ".Compute( "
2085 << theMesh << ", " << theShapeObject << ")";
2089 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2090 ASSERT( meshServant );
2091 if ( meshServant ) {
2092 if ( isGeomModifIcon( theMesh ))
2093 meshServant->Clear();
2095 meshServant->Load();
2096 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2097 meshServant->CheckGeomModif();
2098 // get local TopoDS_Shape
2099 TopoDS_Shape myLocShape;
2100 if(theMesh->HasShapeToMesh())
2101 myLocShape = GeomObjectToShape( theShapeObject );
2103 myLocShape = SMESH_Mesh::PseudoShape();
2104 // call implementation compute
2105 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2106 myGen.PrepareCompute( myLocMesh, myLocShape );
2107 int how = ::SMESH_Gen::COMPACT_MESH;
2108 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2109 how |= ::SMESH_Gen::SHAPE_ONLY;
2110 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2111 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2112 myLocMesh.GetMeshDS()->Modified();
2113 UpdateIcons( theMesh );
2115 HighLightInvalid( theMesh, /*isInvalid=*/false );
2119 catch ( std::bad_alloc ) {
2120 INFOS( "Compute(): lack of memory" );
2122 catch ( SALOME_Exception& S_ex ) {
2123 INFOS( "Compute(): catch exception "<< S_ex.what() );
2126 INFOS( "Compute(): unknown exception " );
2131 //=============================================================================
2133 * SMESH_Gen_i::CancelCompute
2135 * Cancel Compute mesh on a shape
2137 //=============================================================================
2139 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2140 GEOM::GEOM_Object_ptr theShapeObject )
2142 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2144 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2145 TopoDS_Shape myLocShape;
2146 if(theMesh->HasShapeToMesh())
2147 myLocShape = GeomObjectToShape( theShapeObject );
2149 myLocShape = SMESH_Mesh::PseudoShape();
2150 myGen.CancelCompute( myLocMesh, myLocShape);
2154 //=============================================================================
2156 * SMESH_Gen_i::Precompute
2158 * Compute mesh as preview till indicated dimension on shape
2160 //=============================================================================
2162 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2163 GEOM::GEOM_Object_ptr theShapeObject,
2164 SMESH::Dimension theDimension,
2165 SMESH::long_array& theShapesId)
2168 Unexpect aCatch(SALOME_SalomeException);
2169 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2171 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2172 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2173 SALOME::BAD_PARAM );
2175 if ( CORBA::is_nil( theMesh ) )
2176 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2177 SALOME::BAD_PARAM );
2179 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2182 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2183 meshServant->Load();
2184 ASSERT( meshServant );
2185 if ( meshServant ) {
2186 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2187 meshServant->CheckGeomModif();
2188 // get local TopoDS_Shape
2189 TopoDS_Shape myLocShape;
2190 if(theMesh->HasShapeToMesh())
2191 myLocShape = GeomObjectToShape( theShapeObject );
2193 return result._retn();
2195 // call implementation compute
2196 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2198 ::MeshDimension aDim = (MeshDimension)theDimension;
2199 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2201 int nbShapeId = shapeIds.size();
2202 theShapesId.length( nbShapeId );
2203 // iterates on shapes and collect mesh entities into mesh preview
2204 TSetOfInt::const_iterator idIt = shapeIds.begin();
2205 TSetOfInt::const_iterator idEnd = shapeIds.end();
2206 std::map< int, int > mapOfShIdNb;
2207 std::set< SMESH_TLink > setOfEdge;
2208 std::list< SMDSAbs_ElementType > listOfElemType;
2209 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2210 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2211 TNode2LocalIDMap mapNode2LocalID;
2212 list< TNodeLocalID > connectivity;
2213 int i, nbConnNodes = 0;
2214 std::set< const SMESH_subMesh* > setOfVSubMesh;
2215 // iterates on shapes
2216 for ( ; idIt != idEnd; idIt++ )
2218 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2220 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2221 if ( !sm || !sm->IsMeshComputed() )
2224 const TopoDS_Shape& aSh = sm->GetSubShape();
2225 const int shDim = myGen.GetShapeDim( aSh );
2226 if ( shDim < 1 || shDim > theDimension )
2229 mapOfShIdNb[ *idIt ] = 0;
2230 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2232 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2233 if ( !smDS ) continue;
2235 if ( theDimension == SMESH::DIM_2D )
2237 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2238 while ( faceIt->more() )
2240 const SMDS_MeshElement* face = faceIt->next();
2241 int aNbNode = face->NbNodes();
2243 aNbNode /= 2; // do not take into account additional middle nodes
2245 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2246 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2248 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2249 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2251 listOfElemType.push_back( SMDSAbs_Edge );
2252 connectivity.push_back
2253 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2254 connectivity.push_back
2255 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2261 else if ( theDimension == SMESH::DIM_1D )
2263 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2264 while ( nodeIt->more() )
2266 listOfElemType.push_back( SMDSAbs_Node );
2267 connectivity.push_back
2268 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2270 // add corner nodes by first vertex from edge
2271 SMESH_subMeshIteratorPtr edgeSmIt =
2272 sm->getDependsOnIterator(/*includeSelf*/false,
2273 /*complexShapeFirst*/false);
2274 while ( edgeSmIt->more() )
2276 SMESH_subMesh* vertexSM = edgeSmIt->next();
2277 // check that vertex is not already treated
2278 if ( !setOfVSubMesh.insert( vertexSM ).second )
2280 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2283 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2284 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2285 while ( nodeIt->more() )
2287 listOfElemType.push_back( SMDSAbs_Node );
2288 connectivity.push_back
2289 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2295 // fill node coords and assign local ids to the nodes
2296 int nbNodes = mapNode2LocalID.size();
2297 result->nodesXYZ.length( nbNodes );
2298 TNodeLocalID node2ID = mapNode2LocalID.begin();
2299 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2300 node2ID->second = i;
2301 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2302 result->nodesXYZ[i].x = node->X();
2303 result->nodesXYZ[i].y = node->Y();
2304 result->nodesXYZ[i].z = node->Z();
2306 // fill connectivity
2307 result->elementConnectivities.length( nbConnNodes );
2308 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2309 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2310 result->elementConnectivities[i] = (*connIt)->second;
2313 // fill element types
2314 result->elementTypes.length( listOfElemType.size() );
2315 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2316 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2317 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2319 SMDSAbs_ElementType elemType = *typeIt;
2320 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2321 result->elementTypes[i].isPoly = false;
2322 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2325 // correct number of shapes
2326 theShapesId.length( mapOfShIdNb.size() );
2330 catch ( std::bad_alloc ) {
2331 INFOS( "Precompute(): lack of memory" );
2333 catch ( SALOME_Exception& S_ex ) {
2334 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2337 INFOS( "Precompute(): unknown exception " );
2339 return result._retn();
2343 //=============================================================================
2345 * SMESH_Gen_i::Evaluate
2347 * Evaluate mesh on a shape
2349 //=============================================================================
2351 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2352 GEOM::GEOM_Object_ptr theShapeObject)
2353 // SMESH::long_array& theNbElems)
2356 Unexpect aCatch(SALOME_SalomeException);
2357 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2359 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2360 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2362 if ( CORBA::is_nil( theMesh ) )
2363 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2365 SMESH::long_array_var nbels = new SMESH::long_array;
2366 nbels->length(SMESH::Entity_Last);
2367 int i = SMESH::Entity_Node;
2368 for (; i < SMESH::Entity_Last; i++)
2371 // Update Python script
2372 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2373 << theMesh << ", " << theShapeObject << ")";
2377 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2378 ASSERT( meshServant );
2379 if ( meshServant ) {
2380 meshServant->Load();
2381 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2382 meshServant->CheckGeomModif();
2383 // get local TopoDS_Shape
2384 TopoDS_Shape myLocShape;
2385 if(theMesh->HasShapeToMesh())
2386 myLocShape = GeomObjectToShape( theShapeObject );
2388 myLocShape = SMESH_Mesh::PseudoShape();
2389 // call implementation compute
2390 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2391 MapShapeNbElems aResMap;
2392 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2393 MapShapeNbElemsItr anIt = aResMap.begin();
2394 for(; anIt!=aResMap.end(); anIt++) {
2395 const vector<int>& aVec = (*anIt).second;
2396 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2397 int nbElem = aVec[i];
2398 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2400 SMESH_subMesh* sm = anIt->first;
2401 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2402 const SMESH_Algo* algo = sm->GetAlgo();
2403 if ( (algo && !error.get()) || error->IsOK() )
2404 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2408 nbels[i] += aVec[i];
2412 return nbels._retn();
2415 catch ( std::bad_alloc ) {
2416 INFOS( "Evaluate(): lack of memory" );
2418 catch ( SALOME_Exception& S_ex ) {
2419 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2422 INFOS( "Evaluate(): unknown exception " );
2425 return nbels._retn();
2428 //================================================================================
2430 * \brief Return geometrical object the given element is built on
2431 * \param theMesh - the mesh the element is in
2432 * \param theElementID - the element ID
2433 * \param theGeomName - the name of the result geom object if it is not yet published
2434 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2436 //================================================================================
2438 GEOM::GEOM_Object_ptr
2439 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2440 CORBA::Long theElementID,
2441 const char* theGeomName)
2444 Unexpect aCatch(SALOME_SalomeException);
2446 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2447 if ( !geom->_is_nil() ) {
2448 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2449 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2451 // try to find the corresponding SObject
2452 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2453 if ( SObj->_is_nil() ) // submesh can be not found even if published
2455 // try to find published submesh
2456 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2457 if ( !geom->IsMainShape() && list->length() == 1 ) {
2458 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2459 SALOMEDS::ChildIterator_wrap it;
2460 if ( !mainSO->_is_nil() ) {
2461 it = getStudyServant()->NewChildIterator( mainSO );
2463 if ( !it->_is_nil() ) {
2464 for ( it->InitEx(true); it->More(); it->Next() ) {
2465 SALOMEDS::SObject_wrap so = it->Value();
2466 CORBA::Object_var obj = SObjectToObject( so );
2467 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2468 if ( !subGeom->_is_nil() ) {
2469 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2470 if ( subList->length() == 1 && list[0] == subList[0] ) {
2480 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2481 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2483 // return only published geometry
2484 if ( !SObj->_is_nil() ) {
2485 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2486 CORBA::Object_var obj = SObjectToObject( SObj );
2487 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2491 return GEOM::GEOM_Object::_nil();
2494 //================================================================================
2496 * \brief Return geometrical object the given element is built on.
2497 * \param theMesh - the mesh the element is in
2498 * \param theElementID - the element ID
2499 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2501 //================================================================================
2503 GEOM::GEOM_Object_ptr
2504 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2505 CORBA::Long theElementID)
2508 Unexpect aCatch(SALOME_SalomeException);
2509 if ( CORBA::is_nil( theMesh ) )
2510 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2512 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2513 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2515 // get a core mesh DS
2516 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2517 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2519 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2520 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2521 // find the element in mesh
2522 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2523 // find a shape id by the element
2524 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2525 // get a geom object by the shape id
2526 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2527 if ( geom->_is_nil() ) {
2528 // try to find a published sub-shape
2529 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2530 SALOMEDS::ChildIterator_wrap it;
2531 if ( !mainSO->_is_nil() ) {
2532 it = getStudyServant()->NewChildIterator( mainSO );
2534 if ( !it->_is_nil() ) {
2535 for ( it->InitEx(true); it->More(); it->Next() ) {
2536 SALOMEDS::SObject_wrap so = it->Value();
2537 CORBA::Object_var obj = SObjectToObject( so );
2538 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2539 if ( !subGeom->_is_nil() ) {
2540 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2541 if ( subList->length() == 1 && shapeID == subList[0] ) {
2549 if ( geom->_is_nil() ) {
2551 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2552 if ( !op->_is_nil() )
2553 geom = op->GetSubShape( mainShape, shapeID );
2558 if ( !geom->_is_nil() ) {
2559 GeomObjectToShape( geom ); // let geom client remember the found shape
2560 return geom._retn();
2565 return GEOM::GEOM_Object::_nil();
2568 //================================================================================
2570 * SMESH_Gen_i::Concatenate
2572 * Concatenate the given meshes into one mesh
2574 //================================================================================
2576 SMESH::SMESH_Mesh_ptr
2577 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2578 CORBA::Boolean theUniteIdenticalGroups,
2579 CORBA::Boolean theMergeNodesAndElements,
2580 CORBA::Double theMergeTolerance,
2581 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2584 return ConcatenateCommon(theMeshesArray,
2585 theUniteIdenticalGroups,
2586 theMergeNodesAndElements,
2592 //================================================================================
2594 * SMESH_Gen_i::ConcatenateWithGroups
2596 * Concatenate the given meshes into one mesh
2597 * Create the groups of all elements from initial meshes
2599 //================================================================================
2601 SMESH::SMESH_Mesh_ptr
2602 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2603 CORBA::Boolean theUniteIdenticalGroups,
2604 CORBA::Boolean theMergeNodesAndElements,
2605 CORBA::Double theMergeTolerance,
2606 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2609 return ConcatenateCommon(theMeshesArray,
2610 theUniteIdenticalGroups,
2611 theMergeNodesAndElements,
2617 //================================================================================
2619 * SMESH_Gen_i::ConcatenateCommon
2621 * Concatenate the given meshes into one mesh
2623 //================================================================================
2625 SMESH::SMESH_Mesh_ptr
2626 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2627 CORBA::Boolean theUniteIdenticalGroups,
2628 CORBA::Boolean theMergeNodesAndElements,
2629 CORBA::Double theMergeTolerance,
2630 CORBA::Boolean theCommonGroups,
2631 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2634 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2635 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2637 // create mesh if theMeshToAppendTo not provided
2638 SMESH::SMESH_Mesh_var newMesh;
2639 if ( CORBA::is_nil( theMeshToAppendTo ))
2640 newMesh = CreateEmptyMesh();
2642 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2643 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2644 if ( !newImpl ) return newMesh._retn();
2647 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2648 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2650 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2651 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2652 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2653 TGroupsMap groupsMap;
2654 TListOfNewGroups listOfNewGroups;
2656 if ( !CORBA::is_nil( theMeshToAppendTo ))
2658 // fill groupsMap with existing groups
2659 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2660 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2662 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2663 if ( !group->_is_nil() )
2665 CORBA::String_var name = group->GetName();
2666 SMESH::ElementType type = group->GetType();
2667 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2672 ::SMESH_MeshEditor newEditor( &locMesh );
2673 ::SMESH_MeshEditor::ElemFeatures elemType;
2675 // loop on sub-meshes
2676 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2678 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2679 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2680 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2681 if ( !initImpl ) continue;
2682 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2686 // assure that IDs increment by one during iteration
2687 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2688 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2689 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2690 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2692 initMeshDS->Modified();
2693 initMeshDS->CompactMesh();
2696 // remember nb of elements before filling in
2697 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2701 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2702 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2703 while ( elemIt->more() )
2705 SMESH_NodeXYZ node = elemIt->next();
2706 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2711 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2712 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2714 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2715 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2716 while ( elemIt->more() )
2718 const SMDS_MeshElement* elem = elemIt->next();
2719 elemType.myNodes.resize( elem->NbNodes() );
2721 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2722 for ( int k = 0; itNodes->more(); k++)
2724 const SMDS_MeshNode* node = itNodes->next();
2725 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2728 // creates a corresponding element on existent nodes in new mesh
2729 newElems[ elem->GetID() ] =
2730 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2732 newEditor.ClearLastCreated(); // forget the history
2735 // create groups of just added elements
2736 SMESH::SMESH_Group_var newGroup;
2737 SMESH::ElementType groupType;
2738 if ( theCommonGroups )
2741 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2742 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2743 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2744 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2747 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2749 for( groupType = SMESH::NODE;
2750 groupType < SMESH::NB_ELEMENT_TYPES;
2751 groupType = (SMESH::ElementType)( groupType + 1 ))
2753 if ( curState[ groupType ] <= prevState[ groupType ])
2754 continue; // no elements of groupType added from the i-th mesh
2756 // make a group name
2757 std::string groupName = "Gr";
2758 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2760 CORBA::String_var name = meshSO->GetName();
2764 groupName += typeNames[ groupType ];
2766 // make and fill a group
2767 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2768 std::vector< const SMDS_MeshElement* > & elemVec =
2769 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2770 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2772 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2774 for ( size_t j = 0; j < elemVec.size(); ++j )
2776 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2777 grpDS->Add( elemVec[j] );
2781 listOfNewGroups.clear();
2782 listOfNewGroups.push_back( newGroup );
2783 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2788 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2792 SMESH::SMESH_GroupBase_ptr group;
2793 CORBA::String_var groupName;
2794 SMESH::long_array_var newIDs = new SMESH::long_array();
2796 // loop on groups of a source mesh
2797 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2798 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2800 group = listOfGroups[iG];
2801 groupType = group->GetType();
2802 groupName = group->GetName();
2803 std::string name = groupName.in();
2805 // convert a list of IDs
2806 newIDs->length( group->Size() );
2807 std::vector< const SMDS_MeshElement* > & elemVec =
2808 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2809 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2811 while ( itGrElems->more() )
2813 const SMDS_MeshElement* elem = itGrElems->next();
2814 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2816 newIDs[ nbElems++ ] = newElem->GetID();
2818 newIDs->length( nbElems );
2820 // check that a current group name and type don't have identical ones in final mesh
2821 listOfNewGroups.clear();
2822 TNameAndType nameAndType( name, groupType );
2823 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2824 if ( anIter == groupsMap.end() )
2826 // add a new group in the mesh
2827 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2828 newGroup->Add( newIDs );
2830 listOfNewGroups.push_back( newGroup );
2831 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2833 else if ( theUniteIdenticalGroups )
2835 // unite identical groups
2836 TListOfNewGroups& aNewGroups = anIter->second;
2837 aNewGroups.front()->Add( newIDs );
2841 // rename identical groups
2842 newGroup = newImpl->CreateGroup( groupType, groupName );
2843 newGroup->Add( newIDs );
2845 TListOfNewGroups& newGroups = anIter->second;
2846 std::string newGroupName;
2847 if ( newGroups.size() == 1 )
2849 newGroupName = name + "_1";
2850 newGroups.front()->SetName( newGroupName.c_str() );
2852 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2853 newGroup->SetName( newGroupName.c_str() );
2854 newGroups.push_back( newGroup );
2857 } // if an IDSource is a mesh
2860 if ( theMergeNodesAndElements ) // merge nodes
2862 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2863 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2864 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2865 /*SeparateCornersAndMedium=*/ false );
2866 newEditor.MergeNodes( groupsOfNodes );
2868 newEditor.MergeEqualElements();
2871 // Update Python script
2872 pythonDump << newMesh << " = " << this
2873 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2874 << theMeshesArray << ", "
2875 << theUniteIdenticalGroups << ", "
2876 << theMergeNodesAndElements << ", "
2877 << TVar( theMergeTolerance ) << ", "
2878 << theMeshToAppendTo << " )";
2880 pPythonDump.reset(); // enable python dump from GetGroups()
2882 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2883 if ( !newMesh->_is_nil() )
2885 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2888 // IPAL21468 Change icon of compound because it need not be computed.
2889 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2890 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2892 newMeshDS->Modified();
2894 return newMesh._retn();
2897 //================================================================================
2899 * \brief Create a mesh by copying a part of another mesh
2900 * \param meshPart - a part of mesh to copy
2901 * \param toCopyGroups - to create in the new mesh groups
2902 * the copied elements belongs to
2903 * \param toKeepIDs - to preserve IDs of the copied elements or not
2904 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2906 //================================================================================
2908 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2909 const char* meshName,
2910 CORBA::Boolean toCopyGroups,
2911 CORBA::Boolean toKeepIDs)
2914 Unexpect aCatch(SALOME_SalomeException);
2916 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2917 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2919 // 1. Get source mesh
2921 if ( CORBA::is_nil( meshPart ))
2922 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2924 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2925 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2927 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2929 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2931 // 2. Make a new mesh
2933 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2934 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2936 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2937 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2938 if ( !meshSO->_is_nil() )
2940 SetName( meshSO, meshName, "Mesh" );
2941 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2943 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2944 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2945 ::SMESH_MeshEditor::ElemFeatures elemType;
2947 // 3. Get elements to copy
2949 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2950 TIDSortedElemSet srcElems;
2951 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2952 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2955 srcElemIt = srcMeshDS->elementsIterator();
2956 srcNodeIt = srcMeshDS->nodesIterator();
2960 SMESH::long_array_var ids = meshPart->GetIDs();
2961 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2963 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2964 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2965 srcElems.insert( elem );
2969 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2970 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2971 srcElems.insert( elem );
2973 if ( srcElems.empty() )
2974 return newMesh._retn();
2976 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2977 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2982 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2983 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2984 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2986 const SMDS_MeshNode *nSrc, *nTgt;
2987 vector< const SMDS_MeshNode* > nodes;
2988 while ( srcElemIt->more() )
2990 const SMDS_MeshElement * elem = srcElemIt->next();
2992 nodes.resize( elem->NbNodes());
2993 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2995 for ( iN = 0; nIt->more(); ++iN )
2997 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2998 nTgt = newMeshDS->FindNode( nSrc->GetID());
3000 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3005 for ( iN = 0; nIt->more(); ++iN )
3007 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3008 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3010 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3011 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3015 if ( elem->GetType() != SMDSAbs_Node )
3017 elemType.Init( elem, /*basicOnly=*/false );
3018 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3020 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3021 if ( toCopyGroups && !toKeepIDs )
3022 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3024 } // while ( srcElemIt->more() )
3026 // 4(b). Copy free nodes
3028 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3030 while ( srcNodeIt->more() )
3032 nSrc = srcNodeIt->next();
3033 if ( nSrc->NbInverseElements() == 0 )
3036 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3038 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3045 int nbNewGroups = 0;
3048 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3049 while ( gIt->more() )
3051 SMESH_Group* group = gIt->next();
3052 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3054 // Check group type. We copy nodal groups containing nodes of copied element
3055 SMDSAbs_ElementType groupType = groupDS->GetType();
3056 if ( groupType != SMDSAbs_Node &&
3057 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3058 continue; // group type differs from types of meshPart
3060 // Find copied elements in the group
3061 vector< const SMDS_MeshElement* > groupElems;
3062 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3065 const SMDS_MeshElement* foundElem;
3066 if ( groupType == SMDSAbs_Node )
3068 while ( eIt->more() )
3069 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3070 groupElems.push_back( foundElem );
3074 while ( eIt->more() )
3075 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3076 groupElems.push_back( foundElem );
3081 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3082 if ( e2eMap.empty() ) continue;
3083 int minID = e2eMap.begin()->first->GetID();
3084 int maxID = e2eMap.rbegin()->first->GetID();
3085 TE2EMap::iterator e2e;
3086 while ( eIt->more() && groupElems.size() < e2eMap.size())
3088 const SMDS_MeshElement* e = eIt->next();
3089 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3090 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3091 groupElems.push_back( e2e->second );
3095 if ( !groupElems.empty() )
3097 SMESH::SMESH_Group_var newGroupObj =
3098 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3099 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3101 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3102 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3103 for ( unsigned i = 0; i < groupElems.size(); ++i )
3104 smdsGroup.Add( groupElems[i] );
3112 newMeshDS->Modified();
3114 *pyDump << newMesh << " = " << this
3115 << ".CopyMesh( " << meshPart << ", "
3116 << "'" << meshName << "', "
3117 << toCopyGroups << ", "
3118 << toKeepIDs << ")";
3120 pyDumpDeleter.reset(); // allow dump in GetGroups()
3122 if ( nbNewGroups > 0 ) // dump created groups
3123 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3125 return newMesh._retn();
3129 namespace // utils for CopyMeshWithGeom()
3131 typedef std::map< std::string, std::string > TStr2StrMap;
3132 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3133 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3134 typedef std::map< std::string, int > TName2IndexMap;
3136 //================================================================================
3138 * \brief Return a new sub-shape corresponding to an old one
3140 //================================================================================
3144 SMESH_Mesh_i* mySrcMesh_i;
3145 SMESH_Mesh_i* myNewMesh_i;
3146 SMESH_Gen_i* myGen_i;
3150 TStr2StrMap myOld2NewEntryMap; // map of study entries
3152 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3153 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3154 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3157 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3159 // not directly relating to shape search
3160 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3162 //================================================================================
3164 * \brief Constructor
3166 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3167 SMESH_Mesh_i* newMesh_i,
3168 SMESH_Gen_i* smeshGen_i )
3169 : mySrcMesh_i( srcMesh_i ),
3170 myNewMesh_i( newMesh_i ),
3171 myGen_i ( smeshGen_i ),
3172 myToPublish( smeshGen_i->IsEnablePublish() ),
3173 myGIPMapDone( false )
3175 // retrieve from the study shape mapping made thanks to
3176 // "Set presentation parameters and sub-shapes from arguments" option
3178 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3179 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3180 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3181 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3182 if ( newSO->_is_nil() )
3184 myToPublish = false;
3187 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3189 CORBA::String_var oldEntry = oldSO->GetID();
3190 CORBA::String_var newEntry = newSO->GetID();
3191 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3192 std::string( newEntry.in() )));
3193 std::string newMainEntry = newEntry.in();
3195 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3196 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3197 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3198 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3199 /*groupsOnly=*/false );
3200 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3202 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3203 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3204 bool refFound = false;
3205 for ( ; anIter->More(); anIter->Next() )
3207 SALOMEDS::SObject_wrap so = anIter->Value();
3208 if ( so->ReferencedObject( oldSO.inout() ))
3210 oldEntry = oldSO->GetID();
3211 newEntry = newSO->GetID();
3212 if (( refFound = ( newMainEntry != oldEntry.in() )))
3213 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3214 std::string( newEntry.in() )));
3219 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3220 if ( father->_is_equivalent( mainShapeNew ))
3222 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3223 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3224 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3225 CORBA::String_var name = newSO->GetName();
3227 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3233 //================================================================================
3235 * \brief Find a new sub-shape corresponding to an old one
3237 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3240 return GEOM::GEOM_Object::_duplicate( oldShape );
3242 GEOM::GEOM_Object_var newShape;
3244 if ( CORBA::is_nil( oldShape ))
3245 return newShape._retn();
3247 if ( !isChildOfOld( oldShape ))
3248 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3250 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3251 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3253 // try to find by entry or name
3256 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3257 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3258 if ( o2nID != myOld2NewEntryMap.end() )
3260 newShape = getShapeByEntry( o2nID->second );
3262 if ( newShape->_is_nil() )
3264 CORBA::String_var name = oldShape->GetName();
3265 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3266 if ( n2ind != myName2SubshapeIndex.end() )
3268 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3269 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3270 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3271 if ( oldIndices->length() == 0 ||
3272 newIndices->length() == 0 ||
3273 getShapeType( myNewMesh_i, newIndices[0] ) !=
3274 getShapeType( mySrcMesh_i, oldIndices[0] ))
3275 newShape = GEOM::GEOM_Object::_nil();
3280 if ( newShape->_is_nil() )
3282 // try to construct a new sub-shape using myGIPMap
3284 std::vector< int > newIndices;
3285 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3286 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3288 findNewIDs( oldIndices[i], newIndices );
3290 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3293 newShape = getInPlace( oldShape );
3295 if ( !newIndices.empty() && newShape->_is_nil() )
3297 // search for a sub-shape with same ids
3298 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3299 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3300 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3301 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3303 if ( newShape->_is_nil() )
3306 // create a new shape
3307 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3309 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3311 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3312 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3314 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3315 newIndicesList->length( newIndices.size() );
3316 for ( size_t i = 0; i < newIndices.size(); ++i )
3317 newIndicesList[ i ] = newIndices[ i ];
3318 grOp->UnionIDs( newShape, newIndicesList );
3322 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3323 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3332 if ( !newShape->_is_nil() && myToPublish )
3334 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3335 if ( !newEntry.in() || !newEntry.in()[0] )
3337 CORBA::String_var name = oldShape->GetName();
3338 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3339 newEntry = newShape->GetStudyEntry();
3340 oldEntry = oldShape->GetStudyEntry();
3341 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3342 std::string( newEntry.in() )));
3346 return newShape._retn();
3349 //================================================================================
3351 * \brief Return a study entry of a new shape by study entry of the old one
3353 std::string FindNew( const std::string & oldEntry )
3358 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3359 if ( o2nID != myOld2NewEntryMap.end() )
3360 return o2nID->second;
3362 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3363 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3366 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3367 if ( newShape->_is_nil() )
3368 return std::string();
3370 CORBA::String_var newEntry = newShape->GetStudyEntry();
3371 return newEntry.in();
3374 //================================================================================
3376 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3377 * Return zero if not found or there are more than one new ID
3379 int FindNew( int oldID )
3388 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3390 if ( myGIPMap[ oldID ].length() == 1 )
3392 newID = myGIPMap[ oldID ][ 0 ];
3394 else if ( myGIPMap[ oldID ].length() > 1 &&
3395 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3397 // select a meshed VERTEX
3398 SMESH_subMesh* newSM;
3399 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3400 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3401 ( !newSM->IsEmpty() ))
3402 newID = myGIPMap[ oldID ][ i ];
3408 //================================================================================
3410 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3411 * Return zero if the old shape is not kept as is in the new shape.
3413 int FindNewNotChanged( SMESH_subMesh* oldSM )
3416 return oldSM->GetId();
3418 int newID = FindNew( oldSM->GetId() );
3422 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3426 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3427 // one new sub-shape of the same type.
3429 if ( oldSM->DependsOn().size() !=
3430 newSM->DependsOn().size() )
3433 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3434 while ( srcSMIt->more() )
3436 oldSM = srcSMIt->next();
3437 int newSubID = FindNew( oldSM->GetId() );
3438 if ( getShapeType( myNewMesh_i, newSubID ) !=
3439 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3445 //================================================================================
3447 * \brief Return shape by study entry
3449 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3451 GEOM::GEOM_Object_var shape;
3452 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3453 if ( !so->_is_nil() )
3455 CORBA::Object_var obj = so->GetObject();
3456 shape = GEOM::GEOM_Object::_narrow( obj );
3458 return shape._retn();
3461 //================================================================================
3463 * \brief Fill myGIPMap by calling GetInPlaceMap()
3467 if ( !myGIPMapDone )
3469 myGIPMapDone = true;
3471 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3472 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3473 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3474 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3477 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3481 myGIPMap = new GEOM::ListOfListOfLong();
3486 //================================================================================
3488 * \brief Get new sub-shape by calling GetInPlace()
3490 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3492 GEOM::GEOM_Object_var newShape;
3494 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3495 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3496 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3499 newShape = op->GetInPlace( mainShapeNew, oldShape );
3504 return newShape._retn();
3507 //================================================================================
3509 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3510 * number of found IDs
3512 int findNewIDs( int oldID, std::vector< int >& newIDs )
3514 size_t prevNbIDs = newIDs.size();
3516 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3518 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3519 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3521 return newIDs.size() - prevNbIDs;
3524 //================================================================================
3526 * \brief Check if an object relates to the old shape
3528 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3530 if ( CORBA::is_nil( oldShape ))
3532 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3533 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3534 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3535 mainShapeOld1->_is_equivalent( oldShape ));
3538 //================================================================================
3540 * \brief Return shape type by shape ID
3542 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3544 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3545 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3546 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3549 //================================================================================
3551 * \brief Store a source sub-shape for which a counterpart not found and
3552 * a smesh object invalid due to that
3554 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3555 SALOMEDS::SObject_wrap smeshSO )
3557 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3558 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3560 CORBA::String_var smeshEntry = smeshSO->GetID();
3561 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3565 //================================================================================
3567 * \brief Store a source sub-shape for which a counterpart not found and
3568 * a smesh object invalid due to that
3570 void AddInvalid( std::string geomEntry,
3571 SALOMEDS::SObject_wrap smeshSO )
3573 if ( !geomEntry.empty() )
3575 CORBA::String_var smeshEntry = smeshSO->GetID();
3576 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3580 //================================================================================
3582 * \brief Store a source sub-shape for which a counterpart not found and
3583 * a smesh object invalid due to that
3585 void AddInvalid( int oldGeomID,
3586 SALOMEDS::SObject_wrap smeshSO )
3588 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3589 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3592 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3593 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3595 SMESH_Comment geomName( typeName[ shapeType ]);
3596 geomName << " #" << oldGeomID;
3598 CORBA::String_var smeshEntry = smeshSO->GetID();
3599 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3602 //================================================================================
3604 * \brief Return entries of a source sub-shape for which a counterpart not found and
3605 * of smesh objects invalid due to that
3607 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3608 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3611 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3612 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3614 nbSO += 1 + entry2entrySet->second.size();
3616 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3617 theInvalidEntries->length ( nbSO );
3618 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3620 entry2entrySet = myInvalidMap.begin();
3621 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3623 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3625 std::set< std::string > & entrySet = entry2entrySet->second;
3626 std::set< std::string >::iterator entry = entrySet.begin();
3627 for ( ; entry != entrySet.end(); ++entry )
3629 theInvalidEntries[ iEntry++ ] = entry->c_str();
3631 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3632 if ( !so->_is_nil() )
3633 theInvalidMeshSObjects[ iSO++ ] = so;
3638 }; // struct ShapeMapper
3640 //================================================================================
3642 * \brief Append an item to a CORBA sequence
3644 template < class CORBA_seq, class ITEM >
3645 void append( CORBA_seq& seq, ITEM item )
3647 if ( !CORBA::is_nil( item ))
3649 seq->length( 1 + seq->length() );
3650 seq[ seq->length() - 1 ] = item;
3653 } // namespace // utils for CopyMeshWithGeom()
3655 //================================================================================
3657 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3658 * \param [in] sourceMesh - a mesh to copy
3659 * \param [in] newGeometry - a new geometry
3660 * \param [in] toCopyGroups - to create groups in the new mesh
3661 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3662 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3663 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3664 * \param [out] newMesh - return a new mesh
3665 * \param [out] newGroups - return new groups
3666 * \param [out] newSubmeshes - return new sub-meshes
3667 * \param [out] newHypotheses - return new algorithms and hypotheses
3668 * \param [out] invalidEntries - return study entries of objects whose
3669 * counterparts are not found in the newGeometry, followed by entries
3670 * of mesh sub-objects that are invalid because they depend on a not found
3671 * preceding sub-shape
3672 * \return CORBA::Boolean - is a success
3674 //================================================================================
3676 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3677 GEOM::GEOM_Object_ptr theNewGeometry,
3678 const char* theMeshName,
3679 CORBA::Boolean theToCopyGroups,
3680 CORBA::Boolean theToReuseHypotheses,
3681 CORBA::Boolean theToCopyElements,
3682 SMESH::SMESH_Mesh_out theNewMesh,
3683 SMESH::ListOfGroups_out theNewGroups,
3684 SMESH::submesh_array_out theNewSubmeshes,
3685 SMESH::ListOfHypothesis_out theNewHypotheses,
3686 SMESH::string_array_out theInvalidEntries)
3689 if ( CORBA::is_nil( theSourceMesh ) ||
3690 CORBA::is_nil( theNewGeometry ))
3691 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3693 if ( !theSourceMesh->HasShapeToMesh() )
3694 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3699 TPythonDump pyDump; // prevent dump from CreateMesh()
3701 theNewMesh = CreateMesh( theNewGeometry );
3702 theNewGroups = new SMESH::ListOfGroups();
3703 theNewSubmeshes = new SMESH::submesh_array();
3704 theNewHypotheses = new SMESH::ListOfHypothesis();
3705 theInvalidEntries = new SMESH::string_array();
3707 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3709 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3710 GEOM::GEOM_Object_var geom, newGeom;
3711 SALOMEDS::SObject_wrap so;
3713 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3714 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3717 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3719 // treat hypotheses of mesh and sub-meshes
3720 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3721 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3723 bool isSubMesh = ( iSM < smList->length() );
3726 // create a new sub-mesh
3727 SMESH::SMESH_subMesh_var newSM;
3728 geom = smList[iSM]->GetSubShape();
3729 so = ObjectToSObject( smList[iSM] );
3730 CORBA::String_var name;
3731 if ( !so->_is_nil() )
3732 name = so->GetName();
3733 newGeom = shapeMapper.FindNew( geom );
3734 if ( newGeom->_is_nil() )
3736 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3737 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3742 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3744 append( theNewSubmeshes, newSM );
3746 if ( newGeom->_is_nil() )
3747 continue; // don't assign hypotheses
3751 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3753 so = ObjectToSObject( theNewMesh );
3754 SetName( so, theMeshName, "Mesh" );
3757 // assign hypotheses
3758 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3759 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3761 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3762 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3764 // get geometry hyp depends on
3765 std::vector< std::string > entryArray;
3766 std::vector< int > subIDArray;
3767 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3769 if ( !theToReuseHypotheses || dependsOnGeom )
3771 // create a new hypothesis
3772 CORBA::String_var type = hyp->GetName();
3773 CORBA::String_var lib = hyp->GetLibName();
3774 CORBA::String_var data = hyp_i->SaveTo();
3777 hyp = CreateHypothesis( type, lib );
3778 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3779 hyp_i->LoadFrom( data.in() );
3780 append( theNewHypotheses, hyp );
3784 // update geometry hyp depends on
3785 if ( dependsOnGeom )
3787 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3789 if ( !entryArray[ iGeo ].empty() )
3791 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3792 if ( newEntry.empty() )
3795 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3796 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3798 entryArray[ iGeo ] = newEntry;
3801 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3803 if ( subIDArray[ iGeo ] > 0 )
3805 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3809 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3810 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3812 subIDArray[ iGeo ] = newID;
3815 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3819 CORBA::String_var errorText;
3820 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3821 if ( errorText.in()[0] )
3824 } // loop on hypotheses
3825 } // loop on sub-meshes and mesh
3828 // copy mesh elements, keeping IDs
3829 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3830 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3832 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3833 ::SMESH_MeshEditor::ElemFeatures elemData;
3835 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3836 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3837 /*vertexLast=*/false);
3838 while ( srcSMIt->more() )
3840 SMESH_subMesh* srcSM = srcSMIt->next();
3841 if ( srcSM->IsEmpty() )
3842 continue; // not yet computed
3843 int newID = shapeMapper.FindNewNotChanged( srcSM );
3847 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3848 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3849 while ( nIt->more() )
3851 SMESH_NodeXYZ node( nIt->next() );
3852 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3854 const SMDS_PositionPtr pos = node->GetPosition();
3855 const double* uv = pos->GetParameters();
3856 switch ( pos->GetTypeOfPosition() )
3858 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3859 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3860 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3861 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3865 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3866 while( eIt->more() )
3868 const SMDS_MeshElement* e = eIt->next();
3869 elemData.Init( e, /*basicOnly=*/false );
3870 elemData.SetID( e->GetID() );
3871 elemData.myNodes.resize( e->NbNodes() );
3872 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3874 for ( iN = 0; nnIt->more(); ++iN )
3876 const SMDS_MeshNode* srcNode = nnIt->next();
3877 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3878 if ( !elemData.myNodes[ iN ])
3881 if ( iN == elemData.myNodes.size() )
3882 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3883 newMeshDS->SetMeshElementOnShape( newElem, newID );
3885 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3886 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3889 newMeshDS->Modified();
3895 TStr2StrMap old2newGroupMap;
3897 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3899 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3900 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3901 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3903 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3904 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3905 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3907 CORBA::String_var name = groups[ i ]->GetName();
3908 SMESH::ElementType elemType = groups[ i ]->GetType();
3910 SMESH::SMESH_GroupBase_var newGroup;
3912 if ( !stdlGroup->_is_nil() )
3914 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3916 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3917 const bool isElem = ( elemType != SMESH::NODE );
3918 CORBA::ULong iE = 0;
3919 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3920 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3922 if ( iE < elemIDs->length() )
3924 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3925 stdlGroup->Add( elemIDs );
3926 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3930 else if ( !geomGroup->_is_nil() )
3932 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3933 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3934 if ( newGeom->_is_nil() )
3936 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3937 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3942 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3945 else if ( !fltrGroup->_is_nil() )
3947 // replace geometry in a filter
3948 SMESH::Filter_var filter = fltrGroup->GetFilter();
3949 SMESH::Filter::Criteria_var criteria;
3950 filter->GetCriteria( criteria.out() );
3952 bool isMissingGroup = false;
3953 std::vector< std::string > badEntries;
3955 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3957 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3958 switch ( criteria[ iCr ].Type )
3960 case SMESH::FT_BelongToMeshGroup:
3962 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3963 btgg->SetGroupID( thresholdID );
3964 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3965 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3966 if ( refGroupSO->_is_nil() )
3968 CORBA::String_var refID = refGroupSO->GetID();
3969 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3970 if ( o2nID == old2newGroupMap.end() )
3972 isMissingGroup = true; // corresponding new group not yet created
3975 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3977 if ( o2nID->second.empty() ) // new referred group is invalid
3978 badEntries.push_back( refID.in() );
3981 case SMESH::FT_BelongToGeom:
3982 case SMESH::FT_BelongToPlane:
3983 case SMESH::FT_BelongToCylinder:
3984 case SMESH::FT_BelongToGenSurface:
3985 case SMESH::FT_LyingOnGeom:
3987 std::string newID = shapeMapper.FindNew( thresholdID );
3988 criteria[ iCr ].ThresholdID = newID.c_str();
3989 if ( newID.empty() )
3990 badEntries.push_back( thresholdID );
3993 case SMESH::FT_ConnectedElements:
3995 if ( thresholdID && thresholdID[0] )
3997 std::string newID = shapeMapper.FindNew( thresholdID );
3998 criteria[ iCr ].ThresholdID = newID.c_str();
3999 if ( newID.empty() )
4000 badEntries.push_back( thresholdID );
4006 } // loop on criteria
4008 if ( isMissingGroup && i < nbGroups )
4010 // to treat the group again
4011 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4015 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4016 newFilter->SetCriteria( criteria );
4018 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4019 newFilter->UnRegister();
4021 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4022 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4023 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4025 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4027 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4030 if ( !badEntries.empty() )
4033 } // treat a group on filter
4035 append( theNewGroups, newGroup );
4037 // fill old2newGroupMap
4038 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4039 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4040 if ( !srcSO->_is_nil() )
4042 CORBA::String_var srcID, newID("");
4043 srcID = srcSO->GetID();
4044 if ( !newSO->_is_nil() )
4045 newID = newSO->GetID();
4046 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4047 std::string( newID.in() )));
4050 if ( newGroup->_is_nil() )
4055 newMeshDS->CompactMesh();
4058 if ( !theMeshName || !theMeshName[0] )
4060 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4061 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4062 CORBA::String_var oldName = soOld->GetName();
4063 SetName( soNew, oldName.in(), "Mesh" );
4065 // mark invalid objects
4066 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4068 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4069 highLightInvalid( invalidSObjects[i].in(), true );
4072 << theNewMesh << ", "
4073 << theNewGroups << ", "
4074 << *theNewSubmeshes.ptr() << ", "
4075 << *theNewHypotheses.ptr() << ", "
4076 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4077 << theSourceMesh << ", "
4078 << theNewGeometry << ", "
4079 << "'" << theMeshName << "', "
4080 << theToCopyGroups << ", "
4081 << theToReuseHypotheses << ", "
4082 << theToCopyElements << " )";
4084 SMESH_CATCH( SMESH::throwCorbaException );
4089 //================================================================================
4091 * \brief Get version of MED format being used.
4093 //================================================================================
4095 char* SMESH_Gen_i::GetMEDFileVersion()
4097 MED::TInt majeur, mineur, release;
4098 majeur = mineur = release = 0;
4099 MED::GetVersionRelease(majeur, mineur, release);
4100 std::ostringstream version;
4101 version << majeur << "." << mineur << "." << release;
4102 return CORBA::string_dup( version.str().c_str() );
4105 //================================================================================
4107 * SMESH_Gen_i::GetMEDVersion
4109 * Get MED version of the file by its name
4111 //================================================================================
4113 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4115 std::string version = MED::GetMEDVersion( theFileName );
4116 return CORBA::string_dup( version.c_str() );
4119 //================================================================================
4121 * SMESH_Gen_i::CheckCompatibility
4123 * Check compatibility of file with MED format being used, read only.
4125 //================================================================================
4127 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4129 return MED::CheckCompatibility( theFileName );
4132 //================================================================================
4134 * SMESH_Gen_i::CheckWriteCompatibility
4136 * Check compatibility of file with MED format being used, for append on write.
4138 //================================================================================
4140 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4142 return MED::CheckCompatibility( theFileName, true );
4145 //================================================================================
4147 * SMESH_Gen_i::GetMeshNames
4149 * Get names of meshes defined in file with the specified name
4151 //================================================================================
4152 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4155 SMESH::string_array_var aResult = new SMESH::string_array();
4156 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4158 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4160 aResult->length( aNbMeshes );
4161 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4162 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4163 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4166 return aResult._retn();
4169 //=============================================================================
4173 * Save SMESH module's data
4175 //=============================================================================
4177 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4182 Kernel_Utils::Localizer loc;
4184 if (!myStudyContext)
4187 // Store study contents as a set of python commands
4190 SALOMEDS::Study_var aStudy = getStudyServant();
4192 // Declare a byte stream
4193 SALOMEDS::TMPFile_var aStreamFile;
4195 // Obtain a temporary dir
4196 TCollection_AsciiString tmpDir =
4197 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4199 // Create a sequence of files processed
4200 SALOMEDS_Tool::ListOfFiles aFileSeq;
4201 aFileSeq.reserve( NUM_TMP_FILES );
4203 TCollection_AsciiString aStudyName( "" );
4205 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4207 // Set names of temporary files
4208 TCollection_AsciiString filename =
4209 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4210 TCollection_AsciiString meshfile =
4211 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4212 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4213 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4214 filename = tmpDir + filename;
4215 meshfile = tmpDir + meshfile;
4218 HDFdataset* aDataset;
4219 HDFgroup* aTopGroup;
4221 HDFgroup* aSubGroup;
4222 HDFgroup* aSubSubGroup;
4223 hdf_size aSize[ 1 ];
4226 //Remove the files if they exist: BugID: 11225
4227 #ifndef WIN32 /* unix functionality */
4228 TCollection_AsciiString cmd("rm -f \"");
4230 TCollection_AsciiString cmd("del /F \"");
4240 system(cmd.ToCString());
4242 // MED writer to be used by storage process
4243 DriverMED_W_SMESHDS_Mesh myWriter;
4244 myWriter.SetFile( meshfile.ToCString() );
4247 // SetStoreName() to groups before storing hypotheses to let them refer to
4248 // groups using "store name", which is "Group <group_persistent_id>"
4250 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4251 for ( ; itBig->More(); itBig->Next() ) {
4252 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4253 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4254 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4255 if ( !CORBA::is_nil( anObject ) ) {
4256 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4257 if ( !myMesh->_is_nil() ) {
4258 myMesh->Load(); // load from study file if not yet done
4259 TPythonDump pd; // not to dump GetGroups()
4260 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4261 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4263 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4266 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4267 int anId = myStudyContext->findId( string( objStr.in() ) );
4269 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4270 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4271 aGrpBaseDS->SetStoreName( grpName );
4281 // ---> create HDF file
4282 aFile = new HDFfile( (char*) filename.ToCString() );
4283 aFile->CreateOnDisk();
4285 // --> iterator for top-level objects
4286 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4287 for ( ; itBig->More(); itBig->Next() ) {
4288 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4290 // --> hypotheses root branch (only one for the study)
4291 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4292 // create hypotheses root HDF group
4293 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4294 aTopGroup->CreateOnDisk();
4296 // iterator for all hypotheses
4297 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4298 for ( ; it->More(); it->Next() ) {
4299 SALOMEDS::SObject_wrap mySObject = it->Value();
4300 CORBA::Object_var anObject = SObjectToObject( mySObject );
4301 if ( !CORBA::is_nil( anObject ) ) {
4302 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4303 if ( !myHyp->_is_nil() ) {
4304 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4306 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4307 std::string hypname = hn.in();
4308 std::string libname = ln.in();
4310 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4311 // WIN32 and ".so" for X-system) must be deleted
4312 int libname_len = libname.length();
4314 if( libname_len > 4 )
4315 libname.resize( libname_len - 4 );
4317 // PAL17753 (Regression: missing hypothesis in restored study)
4318 // "lib" also should be removed from the beginning
4319 if( libname_len > 6 )
4320 libname = libname.substr( 3, libname_len - 3 - 3 );
4322 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4323 CORBA::String_var hypdata = myImpl->SaveTo();
4324 int id = myStudyContext->findId( string( objStr.in() ));
4326 // for each hypothesis create HDF group basing on its id
4327 char hypGrpName[30];
4328 sprintf( hypGrpName, "Hypothesis %d", id );
4329 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4330 aGroup->CreateOnDisk();
4331 // --> type name of hypothesis
4332 aSize[ 0 ] = hypname.length() + 1;
4333 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4334 aDataset->CreateOnDisk();
4335 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4336 aDataset->CloseOnDisk();
4337 // --> server plugin library name of hypothesis
4338 aSize[ 0 ] = libname.length() + 1;
4339 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4340 aDataset->CreateOnDisk();
4341 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4342 aDataset->CloseOnDisk();
4343 // --> persistent data of hypothesis
4344 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4345 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4346 aDataset->CreateOnDisk();
4347 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4348 aDataset->CloseOnDisk();
4349 // close hypothesis HDF group
4350 aGroup->CloseOnDisk();
4355 // close hypotheses root HDF group
4356 aTopGroup->CloseOnDisk();
4358 // --> algorithms root branch (only one for the study)
4359 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4360 // create algorithms root HDF group
4361 aTopGroup = new HDFgroup( "Algorithms", aFile );
4362 aTopGroup->CreateOnDisk();
4364 // iterator for all algorithms
4365 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4366 for ( ; it->More(); it->Next() ) {
4367 SALOMEDS::SObject_wrap mySObject = it->Value();
4368 CORBA::Object_var anObject = SObjectToObject( mySObject );
4369 if ( !CORBA::is_nil( anObject ) ) {
4370 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4371 if ( !myHyp->_is_nil() ) {
4372 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4374 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4375 std::string hypname = hn.in();
4376 std::string libname = ln.in();
4378 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4379 // WIN32 and ".so" for X-system) must be deleted
4380 int libname_len = libname.length();
4382 if( libname_len > 4 )
4383 libname.resize( libname_len - 4 );
4385 // PAL17753 (Regression: missing hypothesis in restored study)
4386 // "lib" also should be removed from the beginning
4387 if( libname_len > 6 )
4388 libname = libname.substr( 3, libname_len - 3 - 3 );
4390 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4391 CORBA::String_var hypdata = myImpl->SaveTo();
4392 int id = myStudyContext->findId( string( objStr.in() ) );
4394 // for each algorithm create HDF group basing on its id
4395 char hypGrpName[30];
4396 sprintf( hypGrpName, "Algorithm %d", id );
4397 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4398 aGroup->CreateOnDisk();
4399 // --> type name of algorithm
4400 aSize[0] = hypname.length() + 1;
4401 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4402 aDataset->CreateOnDisk();
4403 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4404 aDataset->CloseOnDisk();
4405 // --> server plugin library name of hypothesis
4406 aSize[0] = libname.length() + 1;
4407 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4408 aDataset->CreateOnDisk();
4409 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4410 aDataset->CloseOnDisk();
4411 // --> persistent data of algorithm
4412 aSize[0] = strlen( hypdata.in() ) + 1;
4413 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4414 aDataset->CreateOnDisk();
4415 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4416 aDataset->CloseOnDisk();
4417 // close algorithm HDF group
4418 aGroup->CloseOnDisk();
4423 // close algorithms root HDF group
4424 aTopGroup->CloseOnDisk();
4426 // --> mesh objects roots branches
4427 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4428 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4429 if ( !CORBA::is_nil( anObject ) ) {
4430 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4431 if ( !myMesh->_is_nil() ) {
4432 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4434 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4435 int id = myStudyContext->findId( string( objStr.in() ) );
4436 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4437 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4438 bool hasShape = myLocMesh.HasShapeToMesh();
4440 // for each mesh open the HDF group basing on its id
4441 char meshGrpName[ 30 ];
4442 sprintf( meshGrpName, "Mesh %d", id );
4443 aTopGroup = new HDFgroup( meshGrpName, aFile );
4444 aTopGroup->CreateOnDisk();
4446 // --> put dataset to hdf file which is a flag that mesh has data
4447 string strHasData = "0";
4448 // check if the mesh is not empty
4449 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4450 // write mesh data to med file
4451 myWriter.SetMesh( mySMESHDSMesh );
4452 myWriter.SetMeshId( id );
4455 aSize[ 0 ] = strHasData.length() + 1;
4456 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4457 aDataset->CreateOnDisk();
4458 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4459 aDataset->CloseOnDisk();
4462 // for each mesh open the HDF group basing on its auto color parameter
4463 char meshAutoColorName[ 30 ];
4464 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4466 anAutoColor[0] = myImpl->GetAutoColor();
4468 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4469 aDataset->CreateOnDisk();
4470 aDataset->WriteOnDisk( anAutoColor );
4471 aDataset->CloseOnDisk();
4473 // issue 0020693. Store _isModified flag
4474 int isModified = myLocMesh.GetIsModified();
4476 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4477 aDataset->CreateOnDisk();
4478 aDataset->WriteOnDisk( &isModified );
4479 aDataset->CloseOnDisk();
4481 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4482 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4484 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4485 aDataset->CreateOnDisk();
4486 aDataset->WriteOnDisk( &meshPersistentId );
4487 aDataset->CloseOnDisk();
4489 // Store SMESH_Mesh_i::_mainShapeTick
4490 int shapeTick = myImpl->MainShapeTick();
4492 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4493 aDataset->CreateOnDisk();
4494 aDataset->WriteOnDisk( &shapeTick );
4495 aDataset->CloseOnDisk();
4497 // write reference on a shape if exists
4498 SALOMEDS::SObject_wrap myRef;
4499 bool shapeRefFound = false;
4500 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4502 SALOMEDS::SObject_wrap myShape;
4503 bool ok = myRef->ReferencedObject( myShape.inout() );
4505 CORBA::Object_var shapeObj = myShape->GetObject();
4506 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4507 CORBA::String_var myRefOnObject = myShape->GetID();
4508 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4509 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4510 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4511 aDataset->CreateOnDisk();
4512 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4513 aDataset->CloseOnDisk();
4519 std::string info = myImpl->FileInfoToString();
4520 if ( !info.empty() )
4522 aSize[ 0 ] = info.size();
4523 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4524 aDataset->CreateOnDisk();
4525 aDataset->WriteOnDisk( (char*) info.data() );
4526 aDataset->CloseOnDisk();
4529 // write applied hypotheses if exist
4530 SALOMEDS::SObject_wrap myHypBranch;
4531 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4532 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4533 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4535 if ( found && (shapeRefFound || !hasShape) ) {
4536 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4537 aGroup->CreateOnDisk();
4539 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4541 for ( ; it->More(); it->Next() ) {
4542 SALOMEDS::SObject_wrap mySObject = it->Value();
4543 SALOMEDS::SObject_wrap myRefOnHyp;
4544 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4546 // san - it is impossible to recover applied hypotheses
4547 // using their entries within Load() method,
4548 // for there are no AttributeIORs in the study when Load() is working.
4549 // Hence, it is better to store persistent IDs of hypotheses as references to them
4551 //string myRefOnObject = myRefOnHyp->GetID();
4552 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4553 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4554 int id = myStudyContext->findId( string( objStr.in() ) );
4555 //if ( myRefOnObject.length() > 0 ) {
4556 //aSize[ 0 ] = myRefOnObject.length() + 1;
4557 char hypName[ 30 ], hypId[ 30 ];
4558 sprintf( hypName, "Hyp %d", ++hypNb );
4559 sprintf( hypId, "%d", id );
4560 aSize[ 0 ] = strlen( hypId ) + 1;
4561 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4562 aDataset->CreateOnDisk();
4563 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4564 aDataset->WriteOnDisk( hypId );
4565 aDataset->CloseOnDisk();
4569 aGroup->CloseOnDisk();
4572 // write applied algorithms if exist
4573 SALOMEDS::SObject_wrap myAlgoBranch;
4574 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4575 myAlgoBranch.inout() );
4576 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4577 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4579 if ( found && (shapeRefFound || !hasShape)) {
4580 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4581 aGroup->CreateOnDisk();
4583 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4585 for ( ; it->More(); it->Next() ) {
4586 SALOMEDS::SObject_wrap mySObject = it->Value();
4587 SALOMEDS::SObject_wrap myRefOnAlgo;
4588 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4590 // san - it is impossible to recover applied algorithms
4591 // using their entries within Load() method,
4592 // for there are no AttributeIORs in the study when Load() is working.
4593 // Hence, it is better to store persistent IDs of algorithms as references to them
4595 //string myRefOnObject = myRefOnAlgo->GetID();
4596 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4597 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4598 int id = myStudyContext->findId( string( objStr.in() ) );
4599 //if ( myRefOnObject.length() > 0 ) {
4600 //aSize[ 0 ] = myRefOnObject.length() + 1;
4601 char algoName[ 30 ], algoId[ 30 ];
4602 sprintf( algoName, "Algo %d", ++algoNb );
4603 sprintf( algoId, "%d", id );
4604 aSize[ 0 ] = strlen( algoId ) + 1;
4605 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4606 aDataset->CreateOnDisk();
4607 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4608 aDataset->WriteOnDisk( algoId );
4609 aDataset->CloseOnDisk();
4613 aGroup->CloseOnDisk();
4616 // --> submesh objects sub-branches
4618 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4619 SALOMEDS::SObject_wrap mySubmeshBranch;
4620 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4622 if ( found ) // check if there is shape reference in submeshes
4624 bool hasShapeRef = false;
4625 SALOMEDS::ChildIterator_wrap itSM =
4626 aStudy->NewChildIterator( mySubmeshBranch );
4627 for ( ; itSM->More(); itSM->Next() ) {
4628 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4629 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4630 mySubRef->ReferencedObject( myShape.inout() );
4631 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4634 { // remove one submesh
4635 if ( shapeRefFound )
4636 { // unassign hypothesis
4637 SMESH::SMESH_subMesh_var mySubMesh =
4638 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4639 if ( !mySubMesh->_is_nil() ) {
4640 int shapeID = mySubMesh->GetId();
4641 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4642 const list<const SMESHDS_Hypothesis*>& hypList =
4643 mySMESHDSMesh->GetHypothesis( S );
4644 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4645 while ( hyp != hypList.end() ) {
4646 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4647 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4651 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4653 } // loop on submeshes of a type
4654 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4655 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4658 } // end check if there is shape reference in submeshes
4660 char name_meshgroup[ 30 ];
4661 if ( i == GetSubMeshOnVertexTag() )
4662 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4663 else if ( i == GetSubMeshOnEdgeTag() )
4664 strcpy( name_meshgroup, "SubMeshes On Edge" );
4665 else if ( i == GetSubMeshOnWireTag() )
4666 strcpy( name_meshgroup, "SubMeshes On Wire" );
4667 else if ( i == GetSubMeshOnFaceTag() )
4668 strcpy( name_meshgroup, "SubMeshes On Face" );
4669 else if ( i == GetSubMeshOnShellTag() )
4670 strcpy( name_meshgroup, "SubMeshes On Shell" );
4671 else if ( i == GetSubMeshOnSolidTag() )
4672 strcpy( name_meshgroup, "SubMeshes On Solid" );
4673 else if ( i == GetSubMeshOnCompoundTag() )
4674 strcpy( name_meshgroup, "SubMeshes On Compound" );
4676 // for each type of submeshes create container HDF group
4677 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4678 aGroup->CreateOnDisk();
4680 // iterator for all submeshes of given type
4681 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4682 for ( ; itSM->More(); itSM->Next() ) {
4683 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4684 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4685 if ( !CORBA::is_nil( anSubObject ))
4687 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4688 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4689 int subid = myStudyContext->findId( string( objStr.in() ) );
4691 // for each mesh open the HDF group basing on its id
4692 char submeshGrpName[ 30 ];
4693 sprintf( submeshGrpName, "SubMesh %d", subid );
4694 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4695 aSubGroup->CreateOnDisk();
4697 // write reference on a shape, already checked if it exists
4698 SALOMEDS::SObject_wrap mySubRef, myShape;
4699 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4700 mySubRef->ReferencedObject( myShape.inout() );
4701 string myRefOnObject = myShape->GetID();
4702 if ( myRefOnObject.length() > 0 ) {
4703 aSize[ 0 ] = myRefOnObject.length() + 1;
4704 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4705 aDataset->CreateOnDisk();
4706 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4707 aDataset->CloseOnDisk();
4710 // write applied hypotheses if exist
4711 SALOMEDS::SObject_wrap mySubHypBranch;
4712 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4713 mySubHypBranch.inout() );
4715 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4716 aSubSubGroup->CreateOnDisk();
4718 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4720 for ( ; it->More(); it->Next() ) {
4721 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4722 SALOMEDS::SObject_wrap myRefOnHyp;
4723 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4725 //string myRefOnObject = myRefOnHyp->GetID();
4726 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4727 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4728 int id = myStudyContext->findId( string( objStr.in() ) );
4729 //if ( myRefOnObject.length() > 0 ) {
4730 //aSize[ 0 ] = myRefOnObject.length() + 1;
4731 char hypName[ 30 ], hypId[ 30 ];
4732 sprintf( hypName, "Hyp %d", ++hypNb );
4733 sprintf( hypId, "%d", id );
4734 aSize[ 0 ] = strlen( hypId ) + 1;
4735 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4736 aDataset->CreateOnDisk();
4737 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4738 aDataset->WriteOnDisk( hypId );
4739 aDataset->CloseOnDisk();
4743 aSubSubGroup->CloseOnDisk();
4746 // write applied algorithms if exist
4747 SALOMEDS::SObject_wrap mySubAlgoBranch;
4748 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4749 mySubAlgoBranch.inout() );
4751 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4752 aSubSubGroup->CreateOnDisk();
4754 SALOMEDS::ChildIterator_wrap it =
4755 aStudy->NewChildIterator( mySubAlgoBranch );
4757 for ( ; it->More(); it->Next() ) {
4758 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4759 SALOMEDS::SObject_wrap myRefOnAlgo;
4760 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4762 //string myRefOnObject = myRefOnAlgo->GetID();
4763 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4764 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4765 int id = myStudyContext->findId( string( objStr.in() ) );
4766 //if ( myRefOnObject.length() > 0 ) {
4767 //aSize[ 0 ] = myRefOnObject.length() + 1;
4768 char algoName[ 30 ], algoId[ 30 ];
4769 sprintf( algoName, "Algo %d", ++algoNb );
4770 sprintf( algoId, "%d", id );
4771 aSize[ 0 ] = strlen( algoId ) + 1;
4772 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4773 aDataset->CreateOnDisk();
4774 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4775 aDataset->WriteOnDisk( algoId );
4776 aDataset->CloseOnDisk();
4780 aSubSubGroup->CloseOnDisk();
4782 // close submesh HDF group
4783 aSubGroup->CloseOnDisk();
4786 // close container of submeshes by type HDF group
4787 aGroup->CloseOnDisk();
4791 // store submesh order if any
4792 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4793 if ( theOrderIds.size() ) {
4794 char order_list[ 30 ];
4795 strcpy( order_list, "Mesh Order" );
4796 // count number of submesh ids
4798 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4799 for ( ; idIt != theOrderIds.end(); idIt++ )
4800 nbIDs += (*idIt).size();
4801 // number of values = number of IDs +
4802 // number of lists (for separators) - 1
4803 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4804 idIt = theOrderIds.begin();
4805 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4806 const TListOfInt& idList = *idIt;
4807 if (idIt != theOrderIds.begin()) // not first list
4808 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4809 // dump submesh ids from current list
4810 TListOfInt::const_iterator id_smId = idList.begin();
4811 for( ; id_smId != idList.end(); id_smId++ )
4812 smIDs[ i++ ] = *id_smId;
4815 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4817 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4818 aDataset->CreateOnDisk();
4819 aDataset->WriteOnDisk( smIDs );
4820 aDataset->CloseOnDisk();
4825 // groups root sub-branch
4826 SALOMEDS::SObject_wrap myGroupsBranch;
4827 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4828 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4830 char name_group[ 30 ];
4831 if ( i == GetNodeGroupsTag() )
4832 strcpy( name_group, "Groups of Nodes" );
4833 else if ( i == GetEdgeGroupsTag() )
4834 strcpy( name_group, "Groups of Edges" );
4835 else if ( i == GetFaceGroupsTag() )
4836 strcpy( name_group, "Groups of Faces" );
4837 else if ( i == GetVolumeGroupsTag() )
4838 strcpy( name_group, "Groups of Volumes" );
4839 else if ( i == Get0DElementsGroupsTag() )
4840 strcpy( name_group, "Groups of 0D Elements" );
4841 else if ( i == GetBallElementsGroupsTag() )
4842 strcpy( name_group, "Groups of Balls" );
4844 aGroup = new HDFgroup( name_group, aTopGroup );
4845 aGroup->CreateOnDisk();
4847 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4848 for ( ; it->More(); it->Next() ) {
4849 SALOMEDS::SObject_wrap mySObject = it->Value();
4850 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4851 if ( !CORBA::is_nil( aSubObject ) ) {
4852 SMESH_GroupBase_i* myGroupImpl =
4853 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4856 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4860 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4861 int anId = myStudyContext->findId( string( objStr.in() ) );
4863 // For each group, create a dataset named "Group <group_persistent_id>"
4864 // and store the group's user name into it
4865 const char* grpName = aGrpBaseDS->GetStoreName();
4866 CORBA::String_var aUserName = myGroupImpl->GetName();
4867 aSize[ 0 ] = strlen( aUserName ) + 1;
4869 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4870 aDataset->CreateOnDisk();
4871 aDataset->WriteOnDisk( aUserName );
4872 aDataset->CloseOnDisk();
4875 // For each group, create a dataset named "Group <group_persistent_id> Color"
4876 // and store the group's color into it
4877 char grpColorName[ 30 ];
4878 sprintf( grpColorName, "ColorGroup %d", anId );
4879 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4881 anRGB[ 0 ] = aColor.R;
4882 anRGB[ 1 ] = aColor.G;
4883 anRGB[ 2 ] = aColor.B;
4885 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4886 aDataset->CreateOnDisk();
4887 aDataset->WriteOnDisk( anRGB );
4888 aDataset->CloseOnDisk();
4890 // Pass SMESHDS_Group to MED writer
4891 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4893 myWriter.AddGroup( aGrpDS );
4895 // write reference on a shape if exists
4896 SMESHDS_GroupOnGeom* aGeomGrp =
4897 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4899 SALOMEDS::SObject_wrap mySubRef, myShape;
4900 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4901 mySubRef->ReferencedObject( myShape.inout() ) &&
4902 !CORBA::is_nil( myShape->GetObject() ))
4904 CORBA::String_var myRefOnObject = myShape->GetID();
4905 if ( myRefOnObject.in()[0] ) {
4906 char aRefName[ 30 ];
4907 sprintf( aRefName, "Ref on shape %d", anId);
4908 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4909 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4910 aDataset->CreateOnDisk();
4911 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4912 aDataset->CloseOnDisk();
4915 else // shape ref is invalid:
4917 // save a group on geometry as ordinary group
4918 myWriter.AddGroup( aGeomGrp );
4921 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4922 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4924 std::string str = aFilterGrp_i->FilterToString();
4925 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4926 aSize[ 0 ] = str.length() + 1;
4927 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4928 aDataset->CreateOnDisk();
4929 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4930 aDataset->CloseOnDisk();
4934 aGroup->CloseOnDisk();
4938 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4940 // Flush current mesh information into MED file
4943 // save info on nb of elements
4944 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4946 // maybe a shape was deleted in the study
4947 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4948 TopoDS_Shape nullShape;
4949 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4952 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4957 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4958 aGroup->CreateOnDisk();
4960 // each element belongs to one or none submesh,
4961 // so for each node/element, we store a submesh ID
4963 // Store submesh IDs
4964 for ( int isNode = 0; isNode < 2; ++isNode )
4966 SMDS_ElemIteratorPtr eIt =
4967 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4968 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4971 std::vector<int> smIDs; smIDs.reserve( nbElems );
4972 while ( eIt->more() )
4973 if ( const SMDS_MeshElement* e = eIt->next())
4974 smIDs.push_back( e->getshapeId() );
4976 aSize[ 0 ] = nbElems;
4977 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4978 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4979 aDataset->CreateOnDisk();
4980 aDataset->WriteOnDisk( & smIDs[0] );
4981 aDataset->CloseOnDisk();
4984 aGroup->CloseOnDisk();
4986 // Store node positions on sub-shapes (SMDS_Position):
4987 // ----------------------------------------------------
4989 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4990 aGroup->CreateOnDisk();
4992 // in aGroup, create 5 datasets to contain:
4993 // "Nodes on Edges" - ID of node on edge
4994 // "Edge positions" - U parameter on node on edge
4995 // "Nodes on Faces" - ID of node on face
4996 // "Face U positions" - U parameter of node on face
4997 // "Face V positions" - V parameter of node on face
4999 // Find out nb of nodes on edges and faces
5000 // Collect corresponding sub-meshes
5001 int nbEdgeNodes = 0, nbFaceNodes = 0;
5002 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5003 // loop on SMESHDS_SubMesh'es
5004 while ( smIt->more() )
5006 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5007 if ( aSubMesh->IsComplexSubmesh() )
5008 continue; // submesh containing other submeshs
5009 int nbNodes = aSubMesh->NbNodes();
5010 if ( nbNodes == 0 ) continue;
5012 int aShapeID = aSubMesh->GetID();
5013 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5015 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5016 // write only SMDS_FacePosition and SMDS_EdgePosition
5017 switch ( aShapeType ) {
5019 nbFaceNodes += nbNodes;
5020 aFaceSM.push_back( aSubMesh );
5023 nbEdgeNodes += nbNodes;
5024 aEdgeSM.push_back( aSubMesh );
5030 // Treat positions on edges or faces
5031 for ( int onFace = 0; onFace < 2; onFace++ )
5033 // Create arrays to store in datasets
5034 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5035 if (!nbNodes) continue;
5036 int* aNodeIDs = new int [ nbNodes ];
5037 double* aUPos = new double [ nbNodes ];
5038 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5041 // loop on sub-meshes
5042 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5043 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5044 for ( ; itSM != pListSM->end(); itSM++ )
5046 SMESHDS_SubMesh* aSubMesh = (*itSM);
5048 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5049 // loop on nodes in aSubMesh
5050 while ( itNode->more() )
5053 const SMDS_MeshNode* node = itNode->next();
5054 aNodeIDs [ iNode ] = node->GetID();
5057 const SMDS_PositionPtr pos = node->GetPosition();
5058 if ( onFace ) { // on FACE
5059 SMDS_FacePositionPtr fPos = pos;
5061 aUPos[ iNode ] = fPos->GetUParameter();
5062 aVPos[ iNode ] = fPos->GetVParameter();
5069 SMDS_EdgePositionPtr ePos = pos;
5071 aUPos[ iNode ] = ePos->GetUParameter();
5077 } // loop on nodes in aSubMesh
5078 } // loop on sub-meshes
5083 aSize[ 0 ] = nbNodes;
5085 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5086 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5087 aDataset->CreateOnDisk();
5088 aDataset->WriteOnDisk( aNodeIDs );
5089 aDataset->CloseOnDisk();
5092 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5093 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5094 aDataset->CreateOnDisk();
5095 aDataset->WriteOnDisk( aUPos );
5096 aDataset->CloseOnDisk();
5099 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5100 aDataset->CreateOnDisk();
5101 aDataset->WriteOnDisk( aVPos );
5102 aDataset->CloseOnDisk();
5107 if ( aVPos ) delete [] aVPos;
5109 } // treat positions on edges or faces
5111 // close "Node Positions" group
5112 aGroup->CloseOnDisk();
5114 } // if ( there are submeshes in SMESHDS_Mesh )
5117 // close mesh HDF group
5118 aTopGroup->CloseOnDisk();
5126 aFile->CloseOnDisk();
5129 // Convert temporary files to stream
5130 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5132 // Remove temporary files and directory
5134 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5136 return aStreamFile._retn();
5139 //=============================================================================
5141 * SMESH_Gen_i::SaveASCII
5143 * Save SMESH module's data in ASCII format
5145 //=============================================================================
5147 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5149 bool isMultiFile ) {
5150 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5151 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5152 return aStreamFile._retn();
5154 //after usual saving needs to encipher binary to text string
5155 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5156 int size = aStreamFile.in().length();
5157 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5158 for ( int i = 0; i < size; i++ )
5159 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5161 buffer[size * 3] = '\0';
5163 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5165 return anAsciiStreamFile._retn();
5168 //=============================================================================
5172 * Load SMESH module's data
5174 //=============================================================================
5176 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5177 const SALOMEDS::TMPFile& theStream,
5181 UpdateStudy(); // load geom data
5182 Kernel_Utils::Localizer loc;
5184 SALOMEDS::Study_var aStudy = getStudyServant();
5186 // Get temporary files location
5187 TCollection_AsciiString tmpDir =
5188 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5190 // Convert the stream into sequence of files to process
5191 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5194 TCollection_AsciiString aStudyName( "" );
5195 if ( isMultiFile ) {
5196 CORBA::WString_var url = aStudy->URL();
5197 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5199 // Set names of temporary files
5200 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5201 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5205 HDFdataset* aDataset;
5206 HDFgroup* aTopGroup;
5208 HDFgroup* aSubGroup;
5209 HDFgroup* aSubSubGroup;
5212 // ---> open HDF file
5213 aFile = new HDFfile( (char*) filename.ToCString() );
5215 aFile->OpenOnDisk( HDF_RDONLY );
5217 catch ( HDFexception ) {
5218 INFOS( "Load(): " << filename << " not found!" );
5222 TPythonDump pd; // prevent dump during loading
5224 // For PAL13473 ("Repetitive mesh") implementation.
5225 // New dependencies between SMESH objects are established:
5226 // now hypotheses can refer to meshes, shapes and other hypotheses.
5227 // To keep data consistent, the following order of data restoration
5229 // 1. Create hypotheses
5230 // 2. Create all meshes
5231 // 3. Load hypotheses' data
5234 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5235 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5236 list< SMESH::Filter_var > filters;
5238 // get total number of top-level groups
5239 int aNbGroups = aFile->nInternalObjects();
5240 if ( aNbGroups > 0 ) {
5241 // --> in first turn we should read&create hypotheses
5242 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5243 // open hypotheses root HDF group
5244 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5245 aTopGroup->OpenOnDisk();
5247 // get number of hypotheses
5248 int aNbObjects = aTopGroup->nInternalObjects();
5249 for ( int j = 0; j < aNbObjects; j++ ) {
5250 // try to identify hypothesis
5251 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5252 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5254 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5255 // open hypothesis group
5256 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5257 aGroup->OpenOnDisk();
5259 // --> get hypothesis id
5260 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5265 // get number of datasets
5266 int aNbSubObjects = aGroup->nInternalObjects();
5267 for ( int k = 0; k < aNbSubObjects; k++ ) {
5269 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5270 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5271 // --> get hypothesis name
5272 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5273 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5274 aDataset->OpenOnDisk();
5275 size = aDataset->GetSize();
5276 char* hypname_str = new char[ size ];
5277 aDataset->ReadFromDisk( hypname_str );
5278 hypname = string( hypname_str );
5279 delete [] hypname_str;
5280 aDataset->CloseOnDisk();
5282 // --> get hypothesis plugin library name
5283 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5284 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5285 aDataset->OpenOnDisk();
5286 size = aDataset->GetSize();
5287 char* libname_str = new char[ size ];
5288 aDataset->ReadFromDisk( libname_str );
5289 if(MYDEBUG) SCRUTE( libname_str );
5290 libname = string( libname_str );
5291 delete [] libname_str;
5292 aDataset->CloseOnDisk();
5294 // --> get hypothesis data
5295 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5296 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5297 aDataset->OpenOnDisk();
5298 size = aDataset->GetSize();
5299 char* hypdata_str = new char[ size ];
5300 aDataset->ReadFromDisk( hypdata_str );
5301 hypdata = string( hypdata_str );
5302 delete [] hypdata_str;
5303 aDataset->CloseOnDisk();
5306 // close hypothesis HDF group
5307 aGroup->CloseOnDisk();
5309 // --> restore hypothesis from data
5310 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5311 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5312 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5313 SMESH::SMESH_Hypothesis_var myHyp;
5315 try { // protect persistence mechanism against exceptions
5316 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5319 INFOS( "Exception during hypothesis creation" );
5322 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5324 // myImpl->LoadFrom( hypdata.c_str() );
5325 hypDataList.push_back( make_pair( myImpl, hypdata ));
5326 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5327 int newId = myStudyContext->findId( iorString.in() );
5328 myStudyContext->mapOldToNew( id, newId );
5331 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5335 // close hypotheses root HDF group
5336 aTopGroup->CloseOnDisk();
5340 // --> then we should read&create algorithms
5341 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5342 // open algorithms root HDF group
5343 aTopGroup = new HDFgroup( "Algorithms", aFile );
5344 aTopGroup->OpenOnDisk();
5346 // get number of algorithms
5347 int aNbObjects = aTopGroup->nInternalObjects();
5348 for ( int j = 0; j < aNbObjects; j++ ) {
5349 // try to identify algorithm
5350 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5351 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5353 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5354 // open algorithm group
5355 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5356 aGroup->OpenOnDisk();
5358 // --> get algorithm id
5359 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5364 // get number of datasets
5365 int aNbSubObjects = aGroup->nInternalObjects();
5366 for ( int k = 0; k < aNbSubObjects; k++ ) {
5368 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5369 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5370 // --> get algorithm name
5371 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5372 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5373 aDataset->OpenOnDisk();
5374 size = aDataset->GetSize();
5375 char* hypname_str = new char[ size ];
5376 aDataset->ReadFromDisk( hypname_str );
5377 hypname = string( hypname_str );
5378 delete [] hypname_str;
5379 aDataset->CloseOnDisk();
5381 // --> get algorithm plugin library name
5382 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5383 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5384 aDataset->OpenOnDisk();
5385 size = aDataset->GetSize();
5386 char* libname_str = new char[ size ];
5387 aDataset->ReadFromDisk( libname_str );
5388 if(MYDEBUG) SCRUTE( libname_str );
5389 libname = string( libname_str );
5390 delete [] libname_str;
5391 aDataset->CloseOnDisk();
5393 // --> get algorithm data
5394 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5395 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5396 aDataset->OpenOnDisk();
5397 size = aDataset->GetSize();
5398 char* hypdata_str = new char[ size ];
5399 aDataset->ReadFromDisk( hypdata_str );
5400 if(MYDEBUG) SCRUTE( hypdata_str );
5401 hypdata = string( hypdata_str );
5402 delete [] hypdata_str;
5403 aDataset->CloseOnDisk();
5406 // close algorithm HDF group
5407 aGroup->CloseOnDisk();
5409 // --> restore algorithm from data
5410 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5411 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5412 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5413 SMESH::SMESH_Hypothesis_var myHyp;
5415 try { // protect persistence mechanism against exceptions
5416 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5418 catch( SALOME::SALOME_Exception& ex )
5420 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5423 INFOS( "Exception during hypothesis creation" );
5426 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5428 //myImpl->LoadFrom( hypdata.c_str() );
5429 hypDataList.push_back( make_pair( myImpl, hypdata ));
5430 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5431 int newId = myStudyContext->findId( iorString.in() );
5432 myStudyContext->mapOldToNew( id, newId );
5435 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5439 // close algorithms root HDF group
5440 aTopGroup->CloseOnDisk();
5444 // --> the rest groups should be meshes
5445 for ( int i = 0; i < aNbGroups; i++ ) {
5446 // identify next group
5447 char meshName[ HDF_NAME_MAX_LEN+1 ];
5448 aFile->InternalObjectIndentify( i, meshName );
5450 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5452 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5456 // open mesh HDF group
5457 aTopGroup = new HDFgroup( meshName, aFile );
5458 aTopGroup->OpenOnDisk();
5460 // get number of child HDF objects
5461 int aNbObjects = aTopGroup->nInternalObjects();
5462 if ( aNbObjects > 0 ) {
5464 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5465 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5466 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5467 if ( !myNewMeshImpl )
5469 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5471 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5472 int newId = myStudyContext->findId( iorString.in() );
5473 myStudyContext->mapOldToNew( id, newId );
5476 // try to read and set auto color flag
5477 char aMeshAutoColorName[ 30 ];
5478 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5479 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5481 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5482 aDataset->OpenOnDisk();
5483 size = aDataset->GetSize();
5484 int* anAutoColor = new int[ size ];
5485 aDataset->ReadFromDisk( anAutoColor );
5486 aDataset->CloseOnDisk();
5487 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5488 delete [] anAutoColor;
5491 // try to read and set reference to shape
5492 GEOM::GEOM_Object_var aShapeObject;
5493 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5494 // load mesh "Ref on shape" - it's an entry to SObject
5495 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5496 aDataset->OpenOnDisk();
5497 size = aDataset->GetSize();
5498 char* refFromFile = new char[ size ];
5499 aDataset->ReadFromDisk( refFromFile );
5500 aDataset->CloseOnDisk();
5501 if ( strlen( refFromFile ) > 0 ) {
5502 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5503 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5504 if ( !CORBA::is_nil( shapeObject ) ) {
5505 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5506 if ( !aShapeObject->_is_nil() )
5507 myNewMeshImpl->SetShape( aShapeObject );
5510 delete [] refFromFile;
5513 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5514 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5516 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5517 aDataset->OpenOnDisk();
5518 size = aDataset->GetSize();
5519 int* meshPersistentId = new int[ size ];
5520 aDataset->ReadFromDisk( meshPersistentId );
5521 aDataset->CloseOnDisk();
5522 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5523 delete [] meshPersistentId;
5526 // Restore SMESH_Mesh_i::_mainShapeTick
5527 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5529 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5530 aDataset->OpenOnDisk();
5531 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5532 aDataset->ReadFromDisk( shapeTick );
5533 aDataset->CloseOnDisk();
5536 // Restore file info
5537 if ( aTopGroup->ExistInternalObject( "file info" ))
5539 aDataset = new HDFdataset( "file info", aTopGroup );
5540 aDataset->OpenOnDisk();
5541 size = aDataset->GetSize();
5542 std::string info( size, ' ');
5543 aDataset->ReadFromDisk( (char*) info.data() );
5544 aDataset->CloseOnDisk();
5545 myNewMeshImpl->FileInfoFromString( info );
5551 // As all object that can be referred by hypothesis are created,
5552 // we can restore hypothesis data
5554 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5555 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5557 SMESH_Hypothesis_i* hyp = hyp_data->first;
5558 string & data = hyp_data->second;
5559 hyp->LoadFrom( data.c_str() );
5562 // Restore the rest mesh data
5564 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5565 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5567 aTopGroup = meshi_group->second;
5568 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5570 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5571 bool hasData = false;
5574 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5575 int newId = myStudyContext->findId( iorString.in() );
5576 int meshOldId = myStudyContext->getOldId( newId );
5578 // try to find mesh data dataset
5579 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5580 // load mesh "has data" flag
5581 aDataset = new HDFdataset( "Has data", aTopGroup );
5582 aDataset->OpenOnDisk();
5583 size = aDataset->GetSize();
5584 char* strHasData = new char[ size ];
5585 aDataset->ReadFromDisk( strHasData );
5586 aDataset->CloseOnDisk();
5587 if ( strcmp( strHasData, "1") == 0 ) {
5590 delete [] strHasData;
5593 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5594 // nodes and elements are not yet put into sub-meshes)
5595 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5596 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5597 aGroup->OpenOnDisk();
5598 // get number of applied algorithms
5599 int aNbSubObjects = aGroup->nInternalObjects();
5600 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5601 for ( int j = 0; j < aNbSubObjects; j++ ) {
5602 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5603 aGroup->InternalObjectIndentify( j, name_dataset );
5604 // check if it is an algorithm
5605 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5606 aDataset = new HDFdataset( name_dataset, aGroup );
5607 aDataset->OpenOnDisk();
5608 size = aDataset->GetSize();
5609 char* refFromFile = new char[ size ];
5610 aDataset->ReadFromDisk( refFromFile );
5611 aDataset->CloseOnDisk();
5612 // san - it is impossible to recover applied algorithms using their entries within Load() method
5613 int id = atoi( refFromFile );
5614 delete [] refFromFile;
5615 string anIOR = myStudyContext->getIORbyOldId( id );
5616 if ( !anIOR.empty() ) {
5617 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5618 if ( !CORBA::is_nil( hypObject ) ) {
5619 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5620 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5621 || !myNewMeshImpl->HasShapeToMesh()) )
5622 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5627 aGroup->CloseOnDisk();
5630 // try to get applied hypotheses
5631 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5632 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5633 aGroup->OpenOnDisk();
5634 // get number of applied hypotheses
5635 int aNbSubObjects = aGroup->nInternalObjects();
5636 for ( int j = 0; j < aNbSubObjects; j++ ) {
5637 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5638 aGroup->InternalObjectIndentify( j, name_dataset );
5639 // check if it is a hypothesis
5640 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5641 aDataset = new HDFdataset( name_dataset, aGroup );
5642 aDataset->OpenOnDisk();
5643 size = aDataset->GetSize();
5644 char* refFromFile = new char[ size ];
5645 aDataset->ReadFromDisk( refFromFile );
5646 aDataset->CloseOnDisk();
5647 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5648 int id = atoi( refFromFile );
5649 delete [] refFromFile;
5650 string anIOR = myStudyContext->getIORbyOldId( id );
5651 if ( !anIOR.empty() ) {
5652 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5653 if ( !CORBA::is_nil( hypObject ) ) {
5654 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5655 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5656 || !myNewMeshImpl->HasShapeToMesh()) )
5657 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5662 aGroup->CloseOnDisk();
5665 // --> try to find SUB-MESHES containers for each type of submesh
5666 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5667 const char* name_meshgroup = 0;
5668 if ( j == GetSubMeshOnVertexTag() )
5669 name_meshgroup = "SubMeshes On Vertex";
5670 else if ( j == GetSubMeshOnEdgeTag() )
5671 name_meshgroup = "SubMeshes On Edge";
5672 else if ( j == GetSubMeshOnWireTag() )
5673 name_meshgroup = "SubMeshes On Wire";
5674 else if ( j == GetSubMeshOnFaceTag() )
5675 name_meshgroup = "SubMeshes On Face";
5676 else if ( j == GetSubMeshOnShellTag() )
5677 name_meshgroup = "SubMeshes On Shell";
5678 else if ( j == GetSubMeshOnSolidTag() )
5679 name_meshgroup = "SubMeshes On Solid";
5680 else if ( j == GetSubMeshOnCompoundTag() )
5681 name_meshgroup = "SubMeshes On Compound";
5683 // try to get submeshes container HDF group
5684 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5685 // open submeshes containers HDF group
5686 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5687 aGroup->OpenOnDisk();
5689 // get number of submeshes
5690 int aNbSubMeshes = aGroup->nInternalObjects();
5691 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5693 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5694 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5695 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5696 // --> get submesh id
5697 int subid = atoi( name_submeshgroup + 7 );
5700 // open submesh HDF group
5701 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5702 aSubGroup->OpenOnDisk();
5704 // try to read and set reference to subshape
5705 GEOM::GEOM_Object_var aSubShapeObject;
5706 SMESH::SMESH_subMesh_var aSubMesh;
5708 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5709 // load submesh "Ref on shape" - it's an entry to SObject
5710 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5711 aDataset->OpenOnDisk();
5712 size = aDataset->GetSize();
5713 char* refFromFile = new char[ size ];
5714 aDataset->ReadFromDisk( refFromFile );
5715 aDataset->CloseOnDisk();
5716 if ( strlen( refFromFile ) > 0 ) {
5717 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5718 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5719 if ( !CORBA::is_nil( subShapeObject ) ) {
5720 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5721 if ( !aSubShapeObject->_is_nil() )
5722 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5723 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5724 if ( aSubMesh->_is_nil() )
5726 string iorSubString = GetORB()->object_to_string( aSubMesh );
5727 int newSubId = myStudyContext->findId( iorSubString );
5728 myStudyContext->mapOldToNew( subid, newSubId );
5731 delete [] refFromFile;
5734 if ( aSubMesh->_is_nil() )
5737 // try to get applied algorithms
5738 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5739 // open "applied algorithms" HDF group
5740 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5741 aSubSubGroup->OpenOnDisk();
5742 // get number of applied algorithms
5743 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5744 for ( int l = 0; l < aNbSubObjects; l++ ) {
5745 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5746 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5747 // check if it is an algorithm
5748 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5749 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5750 aDataset->OpenOnDisk();
5751 size = aDataset->GetSize();
5752 char* refFromFile = new char[ size ];
5753 aDataset->ReadFromDisk( refFromFile );
5754 aDataset->CloseOnDisk();
5756 int id = atoi( refFromFile );
5757 string anIOR = myStudyContext->getIORbyOldId( id );
5758 if ( !anIOR.empty() ) {
5759 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5760 if ( !CORBA::is_nil( hypObject ) ) {
5761 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5762 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5763 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5766 delete [] refFromFile;
5769 // close "applied algorithms" HDF group
5770 aSubSubGroup->CloseOnDisk();
5773 // try to get applied hypotheses
5774 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5775 // open "applied hypotheses" HDF group
5776 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5777 aSubSubGroup->OpenOnDisk();
5778 // get number of applied hypotheses
5779 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5780 for ( int l = 0; l < aNbSubObjects; l++ ) {
5781 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5782 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5783 // check if it is a hypothesis
5784 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5785 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5786 aDataset->OpenOnDisk();
5787 size = aDataset->GetSize();
5788 char* refFromFile = new char[ size ];
5789 aDataset->ReadFromDisk( refFromFile );
5790 aDataset->CloseOnDisk();
5792 int id = atoi( refFromFile );
5793 string anIOR = myStudyContext->getIORbyOldId( id );
5794 if ( !anIOR.empty() ) {
5795 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5796 if ( !CORBA::is_nil( hypObject ) ) {
5797 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5798 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5799 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5802 delete [] refFromFile;
5805 // close "APPLIED HYPOTHESES" hdf group
5806 aSubSubGroup->CloseOnDisk();
5809 // close SUB-MESH hdf group
5810 aSubGroup->CloseOnDisk();
5813 // close SUB-MESHES containers hdf group
5814 aGroup->CloseOnDisk();
5818 // try to get GROUPS
5819 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5820 char name_group[ 30 ];
5821 if ( ii == GetNodeGroupsTag() )
5822 strcpy( name_group, "Groups of Nodes" );
5823 else if ( ii == GetEdgeGroupsTag() )
5824 strcpy( name_group, "Groups of Edges" );
5825 else if ( ii == GetFaceGroupsTag() )
5826 strcpy( name_group, "Groups of Faces" );
5827 else if ( ii == GetVolumeGroupsTag() )
5828 strcpy( name_group, "Groups of Volumes" );
5829 else if ( ii == Get0DElementsGroupsTag() )
5830 strcpy( name_group, "Groups of 0D Elements" );
5831 else if ( ii == GetBallElementsGroupsTag() )
5832 strcpy( name_group, "Groups of Balls" );
5834 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5835 aGroup = new HDFgroup( name_group, aTopGroup );
5836 aGroup->OpenOnDisk();
5837 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5838 // within aGroup->ExistInternalObject( name )
5839 std::vector< std::string > subNames;
5840 TColStd_MapOfAsciiString mapOfNames;
5841 aGroup->GetAllObjects( subNames );
5842 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5843 mapOfNames.Add( subNames[ iN ].c_str() );
5845 for ( size_t j = 0; j < subNames.size(); j++ ) {
5846 const std::string& name_dataset = subNames[ j ];
5847 // check if it is a group
5848 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5851 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5854 int groupID = -1; // group local ID (also persistent)
5856 groupID = atoi( endptr + 1 );
5857 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5858 aDataset->OpenOnDisk();
5860 // Retrieve actual group name
5861 size = aDataset->GetSize();
5862 char* nameFromFile = new char[ size ];
5863 aDataset->ReadFromDisk( nameFromFile );
5864 aDataset->CloseOnDisk();
5866 // Try to find a shape reference
5867 TopoDS_Shape aShape;
5868 char aRefName[ 30 ];
5869 sprintf( aRefName, "Ref on shape %d", subid);
5870 if ( mapOfNames.Contains( aRefName ))
5872 // load mesh "Ref on shape" - it's an entry to SObject
5873 aDataset = new HDFdataset( aRefName, aGroup );
5874 aDataset->OpenOnDisk();
5875 size = aDataset->GetSize();
5876 char* refFromFile = new char[ size ];
5877 aDataset->ReadFromDisk( refFromFile );
5878 aDataset->CloseOnDisk();
5879 if ( strlen( refFromFile ) > 0 ) {
5880 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5881 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5882 if ( !CORBA::is_nil( shapeObject ) ) {
5883 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5884 if ( !aShapeObject->_is_nil() )
5885 aShape = GeomObjectToShape( aShapeObject );
5888 delete [] refFromFile;
5890 // Try to read a filter of SMESH_GroupOnFilter
5891 SMESH::Filter_var filter;
5892 SMESH_PredicatePtr predicate;
5893 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5894 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5896 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5897 aDataset->OpenOnDisk();
5898 size = aDataset->GetSize();
5899 char* persistStr = new char[ size ];
5900 aDataset->ReadFromDisk( persistStr );
5901 aDataset->CloseOnDisk();
5902 if ( strlen( persistStr ) > 0 ) {
5903 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5904 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5905 filters.push_back( filter );
5907 delete [] persistStr;
5910 // Create group servant
5911 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5912 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5913 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5914 delete [] nameFromFile;
5915 // Obtain a SMESHDS_Group object
5916 if ( aNewGroup->_is_nil() )
5919 string iorSubString = GetORB()->object_to_string( aNewGroup );
5920 int newSubId = myStudyContext->findId( iorSubString );
5921 myStudyContext->mapOldToNew( subid, newSubId );
5923 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5927 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5928 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5930 aFilterGroup->SetFilter( filter );
5931 filter->UnRegister();
5933 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5934 if ( !aGroupBaseDS )
5937 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5940 // Read color of the group
5941 char aGroupColorName[ 30 ];
5942 sprintf( aGroupColorName, "ColorGroup %d", subid);
5943 if ( mapOfNames.Contains( aGroupColorName ))
5945 aDataset = new HDFdataset( aGroupColorName, aGroup );
5946 aDataset->OpenOnDisk();
5947 size = aDataset->GetSize();
5948 double* anRGB = new double[ size ];
5949 aDataset->ReadFromDisk( anRGB );
5950 aDataset->CloseOnDisk();
5951 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5952 aGroupBaseDS->SetColor( aColor );
5957 aGroup->CloseOnDisk();
5961 // instead of reading mesh data, we read only brief information of all
5962 // objects: mesh, groups, sub-meshes (issue 0021208)
5965 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5966 meshfile.ToCString(), filename.ToCString(),
5970 // read Sub-Mesh ORDER if any
5971 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5972 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5973 aDataset->OpenOnDisk();
5974 size = aDataset->GetSize();
5975 int* smIDs = new int[ size ];
5976 aDataset->ReadFromDisk( smIDs );
5977 aDataset->CloseOnDisk();
5978 TListOfListOfInt anOrderIds;
5979 anOrderIds.push_back( TListOfInt() );
5980 for ( int i = 0; i < size; i++ )
5981 if ( smIDs[ i ] < 0 ) // is separator
5982 anOrderIds.push_back( TListOfInt() );
5984 anOrderIds.back().push_back(smIDs[ i ]);
5986 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5991 // update hyps needing full mesh data restored (issue 20918)
5992 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5994 SMESH_Hypothesis_i* hyp = hyp_data->first;
5995 hyp->UpdateAsMeshesRestored();
5998 // notify algos on completed restoration to set sub-mesh event listeners
5999 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6001 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6002 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6004 TopoDS_Shape myLocShape;
6005 if(myLocMesh.HasShapeToMesh())
6006 myLocShape = myLocMesh.GetShapeToMesh();
6008 myLocShape = SMESH_Mesh::PseudoShape();
6010 myLocMesh.GetSubMesh(myLocShape)->
6011 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6014 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6015 list< SMESH::Filter_var >::iterator f = filters.begin();
6016 for ( ; f != filters.end(); ++f )
6017 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6018 fi->FindBaseObjects();
6023 aTopGroup->CloseOnDisk();
6026 aFile->CloseOnDisk();
6029 // Remove temporary files created from the stream
6032 SMESH_File meshFile( meshfile.ToCString() );
6033 if ( !meshFile ) // no meshfile exists
6035 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6039 Engines::Container_var container = GetContainerRef();
6040 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6042 container_i->registerTemporaryFile( filename.ToCString() );
6043 container_i->registerTemporaryFile( meshfile.ToCString() );
6044 container_i->registerTemporaryFile( tmpDir.ToCString() );
6048 pd << ""; // prevent optimizing pd out
6050 // creation of tree nodes for all data objects in the study
6051 // to support tree representation customization and drag-n-drop:
6052 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6053 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6054 useCaseBuilder->SetRootCurrent();
6055 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6056 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6057 for (it->InitEx(true); it->More(); it->Next()) {
6058 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6065 //=============================================================================
6067 * SMESH_Gen_i::LoadASCII
6069 * Load SMESH module's data in ASCII format
6071 //=============================================================================
6073 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6074 const SALOMEDS::TMPFile& theStream,
6076 bool isMultiFile ) {
6077 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6078 return Load( theComponent, theStream, theURL, isMultiFile );
6080 //before call main ::Load method it's need for decipher text format to
6081 //binary ( "|xx" => x' )
6082 int size = theStream.length();
6083 if ( int((size / 3 )*3) != size ) //error size of buffer
6086 int real_size = int(size / 3);
6088 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6091 unsigned int c = -1;
6092 for ( int i = 0; i < real_size; i++ )
6094 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6095 sscanf( tmp, "%x", &c );
6096 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6099 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6101 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6104 //=============================================================================
6106 * SMESH_Gen_i::Close
6108 * Clears study-connected data when it is closed
6110 //=============================================================================
6112 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6114 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6116 // Clear study contexts data
6117 myStudyContext->Clear();
6119 // remove the tmp files meshes are loaded from
6120 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6122 // Clean trace of API methods calls
6128 //=============================================================================
6130 * SMESH_Gen_i::ComponentDataType
6132 * Get component data type
6134 //=============================================================================
6136 char* SMESH_Gen_i::ComponentDataType()
6138 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6139 return CORBA::string_dup( "SMESH" );
6143 //=============================================================================
6145 * SMESH_Gen_i::IORToLocalPersistentID
6147 * Transform data from transient form to persistent
6149 //=============================================================================
6151 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6152 const char* IORString,
6153 CORBA::Boolean /*isMultiFile*/,
6154 CORBA::Boolean /*isASCII*/ )
6156 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6158 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6159 int anId = myStudyContext->findId( IORString );
6161 if(MYDEBUG) MESSAGE( "VSR " << anId )
6163 sprintf( strId, "%d", anId );
6164 return CORBA::string_dup( strId );
6167 return CORBA::string_dup( "" );
6170 //=============================================================================
6172 * SMESH_Gen_i::LocalPersistentIDToIOR
6174 * Transform data from persistent form to transient
6176 //=============================================================================
6178 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6179 const char* aLocalPersistentID,
6180 CORBA::Boolean /*isMultiFile*/,
6181 CORBA::Boolean /*isASCII*/ )
6183 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6185 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6186 int anId = atoi( aLocalPersistentID );
6187 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6189 return CORBA::string_dup( "" );
6192 //=======================================================================
6193 //function : RegisterObject
6195 //=======================================================================
6197 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6199 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6200 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6201 return myStudyContext->addObject( string( iorString.in() ) );
6206 //================================================================================
6208 * \brief Return id of registered object
6209 * \param theObject - the Object
6210 * \retval int - Object id
6212 //================================================================================
6214 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6216 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6217 string iorString = GetORB()->object_to_string( theObject );
6218 return myStudyContext->findId( iorString );
6223 //=============================================================================
6225 * SMESH_Gen_i::SetName
6227 * Set a new object name
6229 //=============================================================================
6231 void SMESH_Gen_i::SetName(const char* theIOR,
6232 const char* theName)
6234 if ( theIOR && strcmp( theIOR, "" ) ) {
6235 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6236 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6237 if ( !aSO->_is_nil() ) {
6238 SetName( aSO, theName );
6243 // Version information
6244 char* SMESH_Gen_i::getVersion()
6246 #if SMESH_DEVELOPMENT
6247 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6249 return CORBA::string_dup(SMESH_VERSION_STR);
6253 //=================================================================================
6254 // function : Move()
6255 // purpose : Moves objects to the specified position.
6256 // Is used in the drag-n-drop functionality.
6257 //=================================================================================
6259 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6260 SALOMEDS::SObject_ptr where,
6263 if ( CORBA::is_nil( where ) ) return;
6265 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6266 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6267 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6268 std::string dataType = father->ComponentDataType();
6269 if ( dataType != "SMESH" ) return; // not a SMESH component
6271 SALOMEDS::SObject_var objAfter;
6272 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6273 // insert at given row -> find insertion position
6274 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6276 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6277 if ( i == row && useCaseIt->More() ) {
6278 objAfter = useCaseIt->Value();
6282 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6283 SALOMEDS::SObject_var sobj = what[i];
6284 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6285 // insert the object to the use case tree
6286 if ( !CORBA::is_nil( objAfter ) )
6287 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6289 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6292 //================================================================================
6294 * \brief Returns true if algorithm can be used to mesh a given geometry
6295 * \param [in] theAlgoType - the algorithm type
6296 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6297 * \param [in] theGeomObject - the geometry to mesh
6298 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6299 * else, returns \c True if at least one shape is meshable
6300 * \return CORBA::Boolean - can or can't
6302 //================================================================================
6304 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6305 const char* theLibName,
6306 GEOM::GEOM_Object_ptr theGeomObject,
6307 CORBA::Boolean toCheckAll)
6311 std::string aPlatformLibName;
6312 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6313 GenericHypothesisCreator_i* aCreator =
6314 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6317 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6318 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6319 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6326 SMESH_CATCH( SMESH::doNothing );
6329 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6334 //================================================================================
6336 * \brief Collect indices of elements, which are located inside the sphere
6338 //================================================================================
6340 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6341 SMESH::ElementType theElemType,
6347 SMESH::long_array_var aResult = new SMESH::long_array();
6348 if ( meshPart->_is_nil() )
6349 return aResult._retn();
6351 // 1. Create geometrical object
6352 gp_Pnt aP( theX, theY, theZ );
6353 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6355 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6357 if ( lst.size() > 0 ) {
6358 aResult->length( lst.size() );
6359 for ( size_t i = 0; i < lst.size(); i++ ) {
6360 aResult[i] = lst[i];
6363 return aResult._retn();
6366 //================================================================================
6368 * \brief Collect indices of elements, which are located inside the box
6370 //================================================================================
6372 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6373 SMESH::ElementType theElemType,
6374 CORBA::Double theX1,
6375 CORBA::Double theY1,
6376 CORBA::Double theZ1,
6377 CORBA::Double theX2,
6378 CORBA::Double theY2,
6379 CORBA::Double theZ2)
6381 SMESH::long_array_var aResult = new SMESH::long_array();
6382 if( meshPart->_is_nil() )
6383 return aResult._retn();
6385 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6386 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6388 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6390 if( lst.size() > 0 ) {
6391 aResult->length( lst.size() );
6392 for ( size_t i = 0; i < lst.size(); i++ ) {
6393 aResult[i] = lst[i];
6396 return aResult._retn();
6399 //================================================================================
6401 * \brief Collect indices of elements, which are located inside the cylinder
6403 //================================================================================
6405 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6406 SMESH::ElementType theElemType,
6410 CORBA::Double theDX,
6411 CORBA::Double theDY,
6412 CORBA::Double theDZ,
6414 CORBA::Double theR )
6416 SMESH::long_array_var aResult = new SMESH::long_array();
6417 if( meshPart->_is_nil() )
6418 return aResult._retn();
6420 gp_Pnt aP( theX, theY, theZ );
6421 gp_Vec aV( theDX, theDY, theDZ );
6422 gp_Ax2 anAxes (aP, aV);
6424 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6426 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6428 if( lst.size() > 0 ) {
6429 aResult->length( lst.size() );
6430 for ( size_t i = 0; i < lst.size(); i++ ) {
6431 aResult[i] = lst[i];
6434 return aResult._retn();
6437 //================================================================================
6439 * \brief Collect indices of elements, which are located inside the geom object
6441 //================================================================================
6443 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6444 SMESH::ElementType theElemType,
6445 GEOM::GEOM_Object_ptr theGeom,
6446 CORBA::Double theTolerance )
6448 SMESH::long_array_var aResult = new SMESH::long_array();
6449 if( meshPart->_is_nil() || theGeom->_is_nil() )
6450 return aResult._retn();
6452 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6454 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6456 if( lst.size() > 0 ) {
6457 aResult->length( lst.size() );
6458 for ( size_t i = 0; i < lst.size(); i++ ) {
6459 aResult[i] = lst[i];
6462 return aResult._retn();
6465 //================================================================================
6467 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6469 //================================================================================
6471 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6472 SMESH::ElementType theElemType,
6473 const TopoDS_Shape& theShape,
6474 double* theTolerance) {
6476 std::vector<long> res;
6477 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6479 if ( mesh->_is_nil() )
6482 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6486 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6491 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6492 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6493 anElementsOnShape->SetAllNodes( true );
6494 anElementsOnShape->SetMesh( meshDS );
6495 anElementsOnShape->SetShape( theShape, aType );
6498 anElementsOnShape->SetTolerance(*theTolerance);
6500 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6501 if ( !msource->_is_nil() ) { // Mesh case
6502 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6504 while ( elemIt->more() ) {
6505 const SMDS_MeshElement* anElem = elemIt->next();
6506 long anId = anElem->GetID();
6507 if ( anElementsOnShape->IsSatisfy( anId ) )
6508 res.push_back( anId );
6512 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6513 if ( !gsource->_is_nil() ) {
6514 if(theElemType == SMESH::NODE) {
6515 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6516 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6517 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6518 long anId = node->GetID();
6519 if ( anElementsOnShape->IsSatisfy( anId ) )
6520 res.push_back( anId );
6523 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6524 SMESH::long_array_var elems = gsource->GetListOfID();
6525 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6526 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6527 long anId = elem->GetID();
6528 if ( anElementsOnShape->IsSatisfy( anId ) )
6529 res.push_back( anId );
6534 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6535 if ( !smsource->_is_nil() ) {
6536 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6537 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6538 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6540 long anId = elem->GetID();
6541 if ( anElementsOnShape->IsSatisfy( anId ) )
6542 res.push_back( anId );
6549 //=============================================================================
6551 * SMESHEngine_factory
6553 * C factory, accessible with dlsym, after dlopen
6555 //=============================================================================
6559 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6560 PortableServer::POA_ptr poa,
6561 PortableServer::ObjectId* contId,
6562 const char* instanceName,
6563 const char* interfaceName )
6565 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6566 if(MYDEBUG) SCRUTE(interfaceName);
6567 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6568 return aSMESHGen->getId() ;