1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
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;
405 //=============================================================================
407 * SMESH_Gen_i::getHypothesisCreator
409 * Get hypothesis creator
411 //=============================================================================
412 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
413 const char* theLibName,
414 std::string& thePlatformLibName)
415 throw (SALOME::SALOME_Exception)
417 std::string aPlatformLibName;
418 /* It's Need to translate lib name for WIN32 or X platform */
419 if ( theLibName && theLibName[0] != '\0' )
421 int libNameLen = strlen(theLibName);
422 //check for old format "libXXXXXXX.so"
423 if (libNameLen > 7 &&
424 !strncmp( theLibName, "lib", 3 ) &&
425 !strcmp( theLibName+libNameLen-3, ".so" ))
429 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
430 #elif defined(__APPLE__)
431 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
433 aPlatformLibName = theLibName;
438 //try to use new format
440 aPlatformLibName = theLibName;
441 aPlatformLibName += ".dll";
442 #elif defined(__APPLE__)
443 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
449 thePlatformLibName = aPlatformLibName;
451 Unexpect aCatch(SALOME_SalomeException);
452 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
454 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
455 GenericHypothesisCreator_i* aCreator;
458 // check, if creator for this hypothesis type already exists
459 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
461 // load plugin library
462 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
465 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
467 const char* path = aPlatformLibName.c_str();
470 const char* path = aPlatformLibName.c_str();
472 LibHandle libHandle = LoadLib( path );
473 #if defined(WIN32) && defined(UNICODE)
478 // report any error, if occurred
480 const char* anError = dlerror();
481 throw(SALOME_Exception( anError ));
483 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
484 << aPlatformLibName));
488 // get method, returning hypothesis creator
489 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
490 GetHypothesisCreator procHandle =
491 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
494 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
495 << aPlatformLibName ));
496 UnLoadLib(libHandle);
499 // get hypothesis creator
500 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
501 aCreator = procHandle(theHypName);
504 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
505 << aPlatformLibName));
507 // map hypothesis creator to a hypothesis name
508 myHypCreatorMap[string(theHypName)] = aCreator;
513 return myHypCreatorMap[string(theHypName)];
516 catch (SALOME_Exception& S_ex)
518 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
523 //=============================================================================
525 * SMESH_Gen_i::createHypothesis
527 * Create hypothesis of given type
529 //=============================================================================
530 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
531 const char* theLibName)
533 SMESH_Hypothesis_i* myHypothesis_i = 0;
534 SMESH::SMESH_Hypothesis_var hypothesis_i;
535 std::string aPlatformLibName;
536 GenericHypothesisCreator_i* aCreator =
537 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
539 // create a new hypothesis object, store its ref. in studyContext
540 myHypothesis_i = aCreator->Create(myPoa, &myGen);
543 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
544 CORBA::String_var hypName = myHypothesis_i->GetName();
545 myHypCreatorMap[ hypName.in() ] = aCreator;
547 // activate the CORBA servant of hypothesis
548 hypothesis_i = myHypothesis_i->_this();
549 int nextId = RegisterObject( hypothesis_i );
550 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
551 else { nextId = 0; } // avoid "unused variable" warning in release mode
553 return hypothesis_i._retn();
556 //=============================================================================
558 * SMESH_Gen_i::createMesh
560 * Create empty mesh on shape
562 //=============================================================================
563 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
564 throw ( SALOME::SALOME_Exception )
566 Unexpect aCatch(SALOME_SalomeException);
567 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
569 // Get or create the GEOM_Client instance
571 // create a new mesh object servant, store it in a map in study context
572 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
573 // create a new mesh object
574 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
575 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
577 // activate the CORBA servant of Mesh
578 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
579 int nextId = RegisterObject( mesh );
580 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
581 else { nextId = 0; } // avoid "unused variable" warning in release mode
584 catch (SALOME_Exception& S_ex) {
585 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
587 return SMESH::SMESH_Mesh::_nil();
590 //=============================================================================
592 * SMESH_Gen_i::GetShapeReader
596 //=============================================================================
597 GEOM_Client* SMESH_Gen_i::GetShapeReader()
599 // create shape reader if necessary
600 if ( !myShapeReader )
601 myShapeReader = new GEOM_Client(GetContainerRef());
602 ASSERT( myShapeReader );
603 return myShapeReader;
606 //=============================================================================
608 * SMESH_Gen_i::SetGeomEngine
610 * Set GEOM::GEOM_Gen reference
612 //=============================================================================
613 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
614 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
616 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
617 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
618 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
622 //=============================================================================
624 * SMESH_Gen_i::SetEmbeddedMode
628 //=============================================================================
630 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
632 myIsEmbeddedMode = theMode;
634 if ( !myIsEmbeddedMode ) {
635 //PAL10867: disable signals catching with "noexcepthandler" option
636 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
637 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
642 char* envDisableFPE = getenv("DISABLE_FPE");
643 if (envDisableFPE && atoi(envDisableFPE))
648 OSD::SetSignal( raiseFPE );
650 // else OSD::SetSignal() is called in GUI
654 //=============================================================================
656 * SMESH_Gen_i::IsEmbeddedMode
660 //=============================================================================
662 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
664 return myIsEmbeddedMode;
667 //=============================================================================
669 * SMESH_Gen_i::SetEnablePublish
671 * Set enable publishing in the study
673 //=============================================================================
674 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
676 myIsEnablePublish = theIsEnablePublish;
679 //=============================================================================
681 * SMESH_Gen_i::IsEnablePublish
683 * Check enable publishing
685 //=============================================================================
687 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
689 return myIsEnablePublish;
692 //=============================================================================
694 * SMESH_Gen_i::UpdateStudy
696 * Update study (needed at switching GEOM->SMESH)
698 //=============================================================================
700 void SMESH_Gen_i::UpdateStudy()
702 if ( !myStudyContext )
703 myStudyContext = new StudyContext;
705 SALOMEDS::Study_var aStudy = getStudyServant();
706 if ( !CORBA::is_nil( aStudy ) )
708 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
710 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
711 if( !GEOM_var->_is_nil() )
712 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
714 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
715 if( !GEOM_var->_is_nil() )
716 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
718 // NPAL16168, issue 0020210
719 // Let meshes update their data depending on GEOM groups that could change
720 CORBA::String_var compDataType = ComponentDataType();
721 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
722 if ( !me->_is_nil() ) {
723 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
724 for ( ; anIter->More(); anIter->Next() ) {
725 SALOMEDS::SObject_wrap so = anIter->Value();
726 CORBA::Object_var ior = SObjectToObject( so );
727 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
728 mesh->CheckGeomModif();
734 //=============================================================================
736 * SMESH_Gen_i::GetStudyContext
740 //=============================================================================
741 StudyContext* SMESH_Gen_i::GetStudyContext()
743 return myStudyContext;
746 //=============================================================================
748 * SMESH_Gen_i::CreateHypothesis
750 * Create hypothesis/algorithm of given type and publish it in the study
752 //=============================================================================
754 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
755 const char* theLibName )
756 throw ( SALOME::SALOME_Exception )
758 Unexpect aCatch(SALOME_SalomeException);
759 // Create hypothesis/algorithm
760 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
762 // Publish hypothesis/algorithm in the study
763 if ( CanPublishInStudy( hyp ) ) {
764 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
765 if ( !aSO->_is_nil() ) {
766 // Update Python script
767 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
768 << theHypName << "', '" << theLibName << "')";
775 //================================================================================
777 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
778 * existing on the given geometry or to size of the geometry.
779 * \param theHypType - hypothesis type name
780 * \param theLibName - plugin library name
781 * \param theMesh - The mesh of interest
782 * \param theGeom - The shape to get parameter values from
783 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
784 * in a study and used to compute the mesh, or a temporary one created just to pass
787 //================================================================================
789 SMESH::SMESH_Hypothesis_ptr
790 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
791 const char* theLibName,
792 SMESH::SMESH_Mesh_ptr theMesh,
793 GEOM::GEOM_Object_ptr theGeom,
794 CORBA::Boolean byMesh)
795 throw ( SALOME::SALOME_Exception )
797 Unexpect aCatch(SALOME_SalomeException);
798 if ( byMesh && CORBA::is_nil( theMesh ) )
799 return SMESH::SMESH_Hypothesis::_nil();
800 if ( byMesh && CORBA::is_nil( theGeom ) )
801 return SMESH::SMESH_Hypothesis::_nil();
803 // -----------------------------------------------
804 // find hypothesis used to mesh theGeom
805 // -----------------------------------------------
807 // get mesh and shape
808 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
809 TopoDS_Shape shape = GeomObjectToShape( theGeom );
810 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
811 return SMESH::SMESH_Hypothesis::_nil();
812 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
814 // create a temporary hypothesis to know its dimension
815 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
816 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
818 return SMESH::SMESH_Hypothesis::_nil();
819 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
822 // look for a hypothesis of theHypType used to mesh the shape
823 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
826 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
827 int nbLocalHyps = aHypList->length();
828 for ( int i = 0; i < nbLocalHyps; i++ ) {
829 CORBA::String_var hypName = aHypList[i]->GetName();
830 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
831 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
833 // check super shapes
834 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
835 while ( nbLocalHyps == 0 && itShape.More() ) {
836 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
837 if ( ! CORBA::is_nil( geomObj )) {
838 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
839 nbLocalHyps = aHypList->length();
840 for ( int i = 0; i < nbLocalHyps; i++ )
841 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
842 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
848 // let the temporary hypothesis find out somehow parameter values by mesh
849 if ( hyp->SetParametersByMesh( mesh, shape ))
850 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
855 diagonal = mesh->GetShapeDiagonalSize();
857 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
858 ::SMESH_Hypothesis::TDefaults dflts;
859 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
860 dflts._nbSegments = myGen.GetDefaultNbSegments();
861 dflts._shape = &shape;
862 // let the temporary hypothesis initialize it's values
863 if ( hyp->SetParametersByDefaults( dflts, mesh ))
864 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
867 return SMESH::SMESH_Hypothesis::_nil();
870 //=============================================================================
872 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
873 * \param [in] theHyp - the hypothesis of interest
874 * \param [out] theMesh - the sole mesh using \a theHyp
875 * \param [out] theShape - the sole geometry \a theHyp is assigned to
876 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
878 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
879 * considered as SAME sub-mesh => result is \c true.
880 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
881 * a shape to which an hyp being edited is assigned.
883 //=============================================================================
885 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
886 SMESH::SMESH_Mesh_out theMesh,
887 GEOM::GEOM_Object_out theShape)
889 if ( CORBA::is_nil( theHyp ))
892 // get Mesh component SO
893 CORBA::String_var compDataType = ComponentDataType();
894 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
895 if ( CORBA::is_nil( comp ))
898 // look for child SO of meshes
899 SMESH::SMESH_Mesh_var foundMesh;
900 TopoDS_Shape foundShape;
902 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
903 for ( ; meshIter->More() && isSole; meshIter->Next() )
905 SALOMEDS::SObject_wrap curSO = meshIter->Value();
906 CORBA::Object_var obj = SObjectToObject( curSO );
907 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
911 // look for a sole shape where theHyp is assigned
912 bool isHypFound = false;
913 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
914 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
915 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
917 const THypList& hyps = s2hypsIt.Value();
918 THypList::const_iterator h = hyps.begin();
919 for ( ; h != hyps.end(); ++h )
920 if ( (*h)->GetID() == theHyp->GetId() )
922 if ( h != hyps.end()) // theHyp found
925 if ( ! foundShape.IsNull() &&
926 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
928 foundShape.Nullify();
932 foundShape = s2hypsIt.Key();
934 } // loop on assigned hyps
936 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
938 if ( !foundMesh->_is_nil() ) // not a sole mesh
940 if ( !foundMesh->HasShapeToMesh() ||
941 !mesh_i ->HasShapeToMesh() )
943 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
947 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
948 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
949 isSole = s1->IsSame( s2 );
952 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
958 ! foundMesh->_is_nil() &&
959 ! foundShape.IsNull() )
961 theMesh = foundMesh._retn();
962 theShape = ShapeToGeomObject( foundShape );
963 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
968 //=============================================================================
970 * Sets number of segments per diagonal of boundary box of geometry by which
971 * default segment length of appropriate 1D hypotheses is defined
973 //=============================================================================
975 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
976 throw ( SALOME::SALOME_Exception )
978 if ( theNbSegments > 0 )
979 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
981 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
983 //=============================================================================
985 * \brief Sets default number of segments per edge
987 //=============================================================================
988 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
989 throw ( SALOME::SALOME_Exception )
991 if ( theNbSegments > 0 )
992 myGen.SetDefaultNbSegments( int(theNbSegments) );
994 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
997 //=============================================================================
1001 //=============================================================================
1003 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1005 if ( name && value && strlen( value ) > 0 )
1008 if ( strcmp(name, "historical_python_dump") == 0 )
1010 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1011 msgToGUI = "preferences/SMESH/historical_python_dump/";
1012 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1014 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1016 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1017 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1018 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1020 else if ( strcmp(name, "default_grp_color") == 0 )
1024 // color must be presented as a string of following form:
1025 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1026 str = str.substr(1);
1027 for ( size_t i = 0; i < str.length()/2; i++ )
1028 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1029 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1031 else if ( value ) { // rgb color ("255,170,0", for example)
1032 string tempValue( value );
1033 char* colorValue = strtok( &tempValue[0], "," );
1034 while ( colorValue != NULL ) {
1035 int c_value = atoi( colorValue );
1036 if ( c_value >= 0 && c_value <= 255 )
1037 color.push_back( c_value );
1038 colorValue = strtok( NULL, "," );
1041 if ( color.size() == 3 ) { // color must have three valid component
1042 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1043 myDefaultGroupColor = value;
1044 msgToGUI = "preferences/SMESH/default_grp_color/";
1049 // update preferences in case if SetOption() is invoked from python console
1050 if ( !msgToGUI.empty() )
1052 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1053 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1054 if ( !CORBA::is_nil( session ) )
1055 session->emitMessageOneWay(msgToGUI.c_str());
1060 //=============================================================================
1062 Return an option value
1064 //=============================================================================
1066 char* SMESH_Gen_i::GetOption(const char* name)
1070 if ( strcmp(name, "historical_python_dump") == 0 )
1072 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1074 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1076 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1078 if ( strcmp(name, "default_grp_color") == 0 )
1080 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1083 return CORBA::string_dup( "" );
1086 //=============================================================================
1088 * SMESH_Gen_i::CreateMesh
1090 * Create empty mesh on a shape and publish it in the study
1092 //=============================================================================
1094 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1095 throw ( SALOME::SALOME_Exception )
1097 Unexpect aCatch(SALOME_SalomeException);
1098 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1100 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1102 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1103 ASSERT( meshServant );
1104 meshServant->SetShape( theShapeObject );
1106 // publish mesh in the study
1107 if ( CanPublishInStudy( mesh ) ) {
1108 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1109 aStudyBuilder->NewCommand(); // There is a transaction
1110 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1111 aStudyBuilder->CommitCommand();
1112 if ( !aSO->_is_nil() ) {
1113 // Update Python script
1114 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1118 return mesh._retn();
1121 //=============================================================================
1123 * SMESH_Gen_i::CreateEmptyMesh
1127 //=============================================================================
1129 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1130 throw ( SALOME::SALOME_Exception )
1132 Unexpect aCatch(SALOME_SalomeException);
1133 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1135 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1137 // publish mesh in the study
1138 if ( CanPublishInStudy( mesh ) ) {
1139 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1140 aStudyBuilder->NewCommand(); // There is a transaction
1141 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1142 aStudyBuilder->CommitCommand();
1143 if ( !aSO->_is_nil() ) {
1144 // Update Python script
1145 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1149 return mesh._retn();
1154 //================================================================================
1156 * \brief Throws an exception in case if the file can't be read
1158 //================================================================================
1160 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1162 SMESH_File f ( theFileName );
1165 if ( !f.error().empty() )
1166 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1168 THROW_SALOME_CORBA_EXCEPTION
1169 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1170 SALOME::BAD_PARAM );
1175 //=============================================================================
1177 * SMESH_Gen_i::CreateMeshFromUNV
1179 * Create mesh and import data from UNV file
1181 //=============================================================================
1183 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1184 throw ( SALOME::SALOME_Exception )
1186 Unexpect aCatch(SALOME_SalomeException);
1188 checkFileReadable( theFileName );
1190 SMESH::SMESH_Mesh_var aMesh = createMesh();
1192 // publish mesh in the study
1193 if ( CanPublishInStudy( aMesh ) ) {
1194 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1195 aStudyBuilder->NewCommand(); // There is a transaction
1196 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1197 aStudyBuilder->CommitCommand();
1198 if ( !aSO->_is_nil() ) {
1199 // Update Python script
1200 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1204 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1206 aServant->ImportUNVFile( theFileName );
1208 // Dump creation of groups
1209 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1211 aServant->GetImpl().GetMeshDS()->Modified();
1212 return aMesh._retn();
1215 //=============================================================================
1217 * SMESH_Gen_i::CreateMeshFromMED
1219 * Create mesh and import data from MED file
1221 //=============================================================================
1223 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1224 SMESH::DriverMED_ReadStatus& theStatus,
1225 const char* theCommandNameForPython,
1226 const char* theFileNameForPython)
1229 char bname[ _MAX_FNAME ];
1230 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1231 string aFileName = bname;
1233 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1235 // Retrieve mesh names from the file
1236 DriverMED_R_SMESHDS_Mesh myReader;
1237 myReader.SetFile( theFileName );
1238 myReader.SetMeshId( -1 );
1239 Driver_Mesh::Status aStatus;
1240 list<string> aNames = myReader.GetMeshNames(aStatus);
1241 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1242 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1244 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1247 TPythonDump aPythonDump;
1248 aPythonDump << "([";
1250 if (theStatus == SMESH::DRS_OK) {
1251 SALOMEDS::StudyBuilder_var aStudyBuilder;
1252 aStudyBuilder = getStudyServant()->NewBuilder();
1253 aStudyBuilder->NewCommand(); // There is a transaction
1255 aResult->length( aNames.size() );
1258 // Iterate through all meshes and create mesh objects
1259 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1262 if (i > 0) aPythonDump << ", ";
1265 SMESH::SMESH_Mesh_var mesh = createMesh();
1267 // publish mesh in the study
1268 SALOMEDS::SObject_wrap aSO;
1269 if ( CanPublishInStudy( mesh ) )
1270 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1271 // - as names of meshes are stored in MED file, we use them for data publishing
1272 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1273 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1276 if ( !aSO->_is_nil() ) {
1279 aPythonDump << "mesh_" << i;
1282 // Read mesh data (groups are published automatically by ImportMEDFile())
1283 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1284 ASSERT( meshServant );
1285 SMESH::DriverMED_ReadStatus status1 =
1286 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1287 if (status1 > theStatus)
1288 theStatus = status1;
1290 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1291 meshServant->GetImpl().GetMeshDS()->Modified();
1293 if ( !aStudyBuilder->_is_nil() )
1294 aStudyBuilder->CommitCommand();
1297 // Update Python script
1298 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1300 // Dump creation of groups
1301 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1302 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1304 return aResult._retn();
1307 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1308 SMESH::DriverMED_ReadStatus& theStatus)
1309 throw ( SALOME::SALOME_Exception )
1311 Unexpect aCatch(SALOME_SalomeException);
1312 checkFileReadable( theFileName );
1314 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1318 //=============================================================================
1320 * SMESH_Gen_i::CreateMeshFromSAUV
1322 * Create mesh and import data from SAUV file
1324 //=============================================================================
1326 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1327 SMESH::DriverMED_ReadStatus& theStatus)
1328 throw ( SALOME::SALOME_Exception )
1330 Unexpect aCatch(SALOME_SalomeException);
1331 checkFileReadable( theFileName );
1333 std::string sauvfilename(theFileName);
1334 std::string medfilename(theFileName);
1335 medfilename += ".med";
1338 cmd = "%PYTHONBIN% ";
1343 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1345 system(cmd.c_str());
1346 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1348 cmd = "%PYTHONBIN% ";
1353 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1355 system(cmd.c_str());
1359 //=============================================================================
1361 * SMESH_Gen_i::CreateMeshFromSTL
1363 * Create mesh and import data from STL file
1365 //=============================================================================
1367 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1368 throw ( SALOME::SALOME_Exception )
1370 Unexpect aCatch(SALOME_SalomeException);
1371 checkFileReadable( theFileName );
1373 SMESH::SMESH_Mesh_var aMesh = createMesh();
1376 char bname[ _MAX_FNAME ];
1377 _splitpath( theFileName, NULL, NULL, bname, NULL );
1378 string aFileName = bname;
1380 string aFileName = basename( const_cast<char *>(theFileName) );
1382 // publish mesh in the study
1383 if ( CanPublishInStudy( aMesh ) ) {
1384 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1385 aStudyBuilder->NewCommand(); // There is a transaction
1386 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1387 aStudyBuilder->CommitCommand();
1388 if ( !aSO->_is_nil() ) {
1389 // Update Python script
1390 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1394 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1396 aServant->ImportSTLFile( theFileName );
1397 aServant->GetImpl().GetMeshDS()->Modified();
1398 return aMesh._retn();
1401 //================================================================================
1403 * \brief Create meshes and import data from the CGSN file
1405 //================================================================================
1407 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1408 SMESH::DriverMED_ReadStatus& theStatus)
1409 throw ( SALOME::SALOME_Exception )
1411 Unexpect aCatch(SALOME_SalomeException);
1412 checkFileReadable( theFileName );
1414 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1417 // Retrieve nb meshes from the file
1418 DriverCGNS_Read myReader;
1419 myReader.SetFile( theFileName );
1420 Driver_Mesh::Status aStatus;
1421 int nbMeshes = myReader.GetNbMeshes(aStatus);
1422 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1424 aResult->length( nbMeshes );
1426 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1429 TPythonDump aPythonDump;
1430 aPythonDump << "([";
1432 if (theStatus == SMESH::DRS_OK)
1434 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1435 aStudyBuilder->NewCommand(); // There is a transaction
1439 // Iterate through all meshes and create mesh objects
1440 for ( ; i < nbMeshes; ++i )
1443 if (i > 0) aPythonDump << ", ";
1446 SMESH::SMESH_Mesh_var mesh = createMesh();
1447 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1449 // Read mesh data (groups are published automatically by ImportMEDFile())
1450 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1451 ASSERT( meshServant );
1453 SMESH::DriverMED_ReadStatus status1 =
1454 meshServant->ImportCGNSFile( theFileName, i, meshName );
1455 if (status1 > theStatus)
1456 theStatus = status1;
1458 meshServant->GetImpl().GetMeshDS()->Modified();
1459 // publish mesh in the study
1460 SALOMEDS::SObject_wrap aSO;
1461 if ( CanPublishInStudy( mesh ) )
1462 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1465 if ( !aSO->_is_nil() ) {
1469 aPythonDump << "mesh_" << i;
1472 aStudyBuilder->CommitCommand();
1475 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1477 // Dump creation of groups
1478 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1479 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1481 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1484 return aResult._retn();
1487 //================================================================================
1489 * \brief Create a mesh and import data from a GMF file
1491 //================================================================================
1493 SMESH::SMESH_Mesh_ptr
1494 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1495 CORBA::Boolean theMakeRequiredGroups,
1496 SMESH::ComputeError_out theError)
1497 throw ( SALOME::SALOME_Exception )
1499 Unexpect aCatch(SALOME_SalomeException);
1500 checkFileReadable( theFileName );
1502 SMESH::SMESH_Mesh_var aMesh = createMesh();
1504 char bname[ _MAX_FNAME ];
1505 _splitpath( theFileName, NULL, NULL, bname, NULL );
1506 string aFileName = bname;
1508 string aFileName = basename( const_cast<char *>(theFileName) );
1510 // publish mesh in the study
1511 if ( CanPublishInStudy( aMesh ) ) {
1512 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1513 aStudyBuilder->NewCommand(); // There is a transaction
1514 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1515 aStudyBuilder->CommitCommand();
1516 if ( !aSO->_is_nil() ) {
1517 // Update Python script
1518 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1519 << theFileName << "', "
1520 << theMakeRequiredGroups << " )";
1523 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1525 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1526 aServant->GetImpl().GetMeshDS()->Modified();
1527 return aMesh._retn();
1531 //=============================================================================
1533 * SMESH_Gen_i::IsReadyToCompute
1535 * Returns true if mesh contains enough data to be computed
1537 //=============================================================================
1539 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1540 GEOM::GEOM_Object_ptr theShapeObject )
1541 throw ( SALOME::SALOME_Exception )
1543 Unexpect aCatch(SALOME_SalomeException);
1544 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1546 if ( CORBA::is_nil( theShapeObject ) )
1547 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1548 SALOME::BAD_PARAM );
1550 if ( CORBA::is_nil( theMesh ) )
1551 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1552 SALOME::BAD_PARAM );
1556 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1557 ASSERT( meshServant );
1558 if ( meshServant ) {
1559 // get local TopoDS_Shape
1560 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1561 // call implementation
1562 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1563 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1566 catch ( SALOME_Exception& S_ex ) {
1567 INFOS( "catch exception "<< S_ex.what() );
1572 //================================================================================
1574 * \brief Find SObject for an algo
1576 //================================================================================
1578 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1581 SALOMEDS::Study_var aStudy = getStudyServant();
1582 if ( !aStudy->_is_nil() ) {
1583 // find algo in the study
1584 CORBA::String_var compDataType = ComponentDataType();
1585 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1586 if ( !father->_is_nil() ) {
1587 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1588 for ( ; itBig->More(); itBig->Next() ) {
1589 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1590 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1591 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1592 for ( ; algoIt->More(); algoIt->Next() ) {
1593 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1594 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1595 if ( !CORBA::is_nil( algoIOR )) {
1596 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1597 if ( impl && impl->GetImpl() == algo )
1598 return algoSO._retn();
1600 } // loop on algo SO's
1603 } // SMESH component iterator
1607 return SALOMEDS::SObject::_nil();
1610 //================================================================================
1612 * \brief Return errors of mesh computation
1614 //================================================================================
1616 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1617 GEOM::GEOM_Object_ptr theSubObject )
1618 throw ( SALOME::SALOME_Exception )
1620 Unexpect aCatch(SALOME_SalomeException);
1621 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1623 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1624 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1626 if ( CORBA::is_nil( theMesh ) )
1627 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1629 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1631 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1634 if(theMesh->HasShapeToMesh())
1635 shape = GeomObjectToShape( theSubObject );
1637 shape = SMESH_Mesh::PseudoShape();
1639 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1641 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1644 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1645 const bool includeSelf = true, complexShapeFirst = true;
1646 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1648 while ( smIt->more() )
1651 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1653 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1654 if ( error && !error->IsOK() )
1656 if ( !( error->myAlgo ) &&
1657 !( error->myAlgo = sm->GetAlgo() ))
1659 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1660 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1661 errStruct.comment = error->myComment.c_str();
1662 errStruct.subShapeID = sm->GetId();
1663 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1664 if ( !algoSO->_is_nil() ) {
1665 CORBA::String_var algoName = algoSO->GetName();
1666 errStruct.algoName = algoName;
1669 errStruct.algoName = error->myAlgo->GetName();
1671 errStruct.hasBadMesh = error->HasBadElems();
1674 error_array->length( nbErr );
1677 catch ( SALOME_Exception& S_ex ) {
1678 INFOS( "catch exception "<< S_ex.what() );
1681 return error_array._retn();
1684 //================================================================================
1686 * \brief Return mesh elements preventing computation of a subshape
1688 //================================================================================
1690 SMESH::MeshPreviewStruct*
1691 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1692 CORBA::Short theSubShapeID )
1693 throw ( SALOME::SALOME_Exception )
1695 Unexpect aCatch(SALOME_SalomeException);
1696 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1698 if ( CORBA::is_nil( theMesh ) )
1699 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1701 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1704 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1706 // mesh implementation
1707 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1708 // submesh by subshape id
1709 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1712 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1713 if ( error && error->HasBadElems() )
1715 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1716 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1718 // get nodes of elements and count elements
1719 TNode2LocalIDMap mapNode2LocalID;
1720 list< TNodeLocalID > connectivity;
1721 int i, nbElements = 0, nbConnNodes = 0;
1723 const list<const SMDS_MeshElement*>& badElems =
1724 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1725 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1726 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1727 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1729 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1730 while ( nIt->more() )
1731 connectivity.push_back
1732 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1734 // fill node coords and assign local ids to the nodes
1735 int nbNodes = mapNode2LocalID.size();
1736 result->nodesXYZ.length( nbNodes );
1737 TNodeLocalID node2ID = mapNode2LocalID.begin();
1738 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1739 node2ID->second = i;
1740 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1741 result->nodesXYZ[i].x = node->X();
1742 result->nodesXYZ[i].y = node->Y();
1743 result->nodesXYZ[i].z = node->Z();
1745 // fill connectivity
1746 result->elementConnectivities.length( nbConnNodes );
1747 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1748 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1749 result->elementConnectivities[i] = (*connIt)->second;
1751 // fill element types
1752 result->elementTypes.length( nbElements );
1753 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1755 const SMDS_MeshElement* elem = *elemIt;
1756 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1757 result->elementTypes[i].isPoly = elem->IsPoly();
1758 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1764 catch ( SALOME_Exception& S_ex ) {
1765 INFOS( "catch exception "<< S_ex.what() );
1768 return result._retn();
1771 //================================================================================
1773 * \brief Create a group of elements preventing computation of a sub-shape
1775 //================================================================================
1777 SMESH::ListOfGroups*
1778 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1779 CORBA::Short theSubShapeID,
1780 const char* theGroupName )
1781 throw ( SALOME::SALOME_Exception )
1783 Unexpect aCatch(SALOME_SalomeException);
1785 SMESH::ListOfGroups_var groups;
1787 if ( CORBA::is_nil( theMesh ) )
1788 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1791 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1793 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1794 TPythonDump() << groups << " = " << this
1795 << ".MakeGroupsOfBadInputElements( "
1796 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1799 catch ( SALOME_Exception& S_ex ) {
1800 INFOS( "catch exception "<< S_ex.what() );
1802 return groups._retn();
1805 //================================================================================
1807 * \brief Returns errors of hypotheses definition
1808 * \param theMesh - the mesh
1809 * \param theSubObject - the main or sub- shape
1810 * \retval SMESH::algo_error_array* - sequence of errors
1812 //================================================================================
1814 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1815 GEOM::GEOM_Object_ptr theSubObject )
1816 throw ( SALOME::SALOME_Exception )
1818 Unexpect aCatch(SALOME_SalomeException);
1819 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1821 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1822 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1824 if ( CORBA::is_nil( theMesh ) )
1825 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1827 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1829 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1830 ASSERT( meshServant );
1831 if ( meshServant ) {
1832 TopoDS_Shape myLocShape;
1833 if(theMesh->HasShapeToMesh())
1834 myLocShape = GeomObjectToShape( theSubObject );
1836 myLocShape = SMESH_Mesh::PseudoShape();
1838 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1839 list< ::SMESH_Gen::TAlgoStateError > error_list;
1840 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1841 // call ::SMESH_Gen::GetAlgoState()
1842 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1843 error_array->length( error_list.size() );
1845 for ( error = error_list.begin(); error != error_list.end(); ++error )
1847 // fill AlgoStateError structure
1848 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1849 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1850 errStruct.algoDim = error->_algoDim;
1851 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1852 errStruct.algoName = "";
1853 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1854 if ( !algoSO->_is_nil() ) {
1855 CORBA::String_var algoName = algoSO->GetName();
1856 errStruct.algoName = algoName.in();
1861 catch ( SALOME_Exception& S_ex ) {
1862 INFOS( "catch exception "<< S_ex.what() );
1864 return error_array._retn();
1867 //=============================================================================
1869 * SMESH_Gen_i::GetSubShapesId
1871 * Get sub-shapes unique ID's list
1873 //=============================================================================
1876 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1877 const SMESH::object_array& theListOfSubShapeObject )
1878 throw ( SALOME::SALOME_Exception )
1880 Unexpect aCatch(SALOME_SalomeException);
1881 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1883 SMESH::long_array_var shapesId = new SMESH::long_array;
1886 if ( CORBA::is_nil( theMainShapeObject ) )
1887 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1891 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1892 TopTools_IndexedMapOfShape myIndexToShape;
1893 TopExp::MapShapes(myMainShape,myIndexToShape);
1895 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1897 GEOM::GEOM_Object_var aShapeObject
1898 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1899 if ( CORBA::is_nil( aShapeObject ) )
1900 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1901 SALOME::BAD_PARAM );
1903 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1904 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1906 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1907 setId.insert(myIndexToShape.FindIndex(F));
1908 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1910 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1912 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1913 setId.insert(myIndexToShape.FindIndex(E));
1914 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1916 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1918 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1919 setId.insert(myIndexToShape.FindIndex(V));
1920 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1923 shapesId->length(setId.size());
1924 set<int>::iterator iind;
1926 for (iind = setId.begin(); iind != setId.end(); iind++)
1928 if(MYDEBUG) SCRUTE((*iind));
1929 shapesId[i] = (*iind);
1930 if(MYDEBUG) SCRUTE(shapesId[i]);
1934 catch (SALOME_Exception& S_ex)
1936 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1939 return shapesId._retn();
1942 //=============================================================================
1944 * SMESH_Gen_i::Compute
1946 * Compute mesh on a shape
1948 //=============================================================================
1950 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1951 GEOM::GEOM_Object_ptr theShapeObject )
1952 throw ( SALOME::SALOME_Exception )
1955 Unexpect aCatch(SALOME_SalomeException);
1956 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1958 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1959 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1960 SALOME::BAD_PARAM );
1962 if ( CORBA::is_nil( theMesh ) )
1963 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1964 SALOME::BAD_PARAM );
1966 // Update Python script
1967 TPythonDump() << "isDone = " << this << ".Compute( "
1968 << theMesh << ", " << theShapeObject << ")";
1972 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1973 ASSERT( meshServant );
1974 if ( meshServant ) {
1975 meshServant->Load();
1976 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
1977 meshServant->CheckGeomModif();
1978 // get local TopoDS_Shape
1979 TopoDS_Shape myLocShape;
1980 if(theMesh->HasShapeToMesh())
1981 myLocShape = GeomObjectToShape( theShapeObject );
1983 myLocShape = SMESH_Mesh::PseudoShape();
1984 // call implementation compute
1985 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1986 myGen.PrepareCompute( myLocMesh, myLocShape );
1987 int how = ::SMESH_Gen::COMPACT_MESH;
1988 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1989 how |= ::SMESH_Gen::SHAPE_ONLY;
1990 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1991 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1992 myLocMesh.GetMeshDS()->Modified();
1993 UpdateIcons( theMesh );
1995 HighLightInvalid( theMesh, /*isInvalid=*/false );
1999 catch ( std::bad_alloc ) {
2000 INFOS( "Compute(): lack of memory" );
2002 catch ( SALOME_Exception& S_ex ) {
2003 INFOS( "Compute(): catch exception "<< S_ex.what() );
2006 INFOS( "Compute(): unknown exception " );
2011 //=============================================================================
2013 * SMESH_Gen_i::CancelCompute
2015 * Cancel Compute mesh on a shape
2017 //=============================================================================
2019 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2020 GEOM::GEOM_Object_ptr theShapeObject )
2022 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2024 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2025 TopoDS_Shape myLocShape;
2026 if(theMesh->HasShapeToMesh())
2027 myLocShape = GeomObjectToShape( theShapeObject );
2029 myLocShape = SMESH_Mesh::PseudoShape();
2030 myGen.CancelCompute( myLocMesh, myLocShape);
2034 //=============================================================================
2036 * SMESH_Gen_i::Precompute
2038 * Compute mesh as preview till indicated dimension on shape
2040 //=============================================================================
2042 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2043 GEOM::GEOM_Object_ptr theShapeObject,
2044 SMESH::Dimension theDimension,
2045 SMESH::long_array& theShapesId)
2046 throw ( SALOME::SALOME_Exception )
2048 Unexpect aCatch(SALOME_SalomeException);
2049 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2051 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2052 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2053 SALOME::BAD_PARAM );
2055 if ( CORBA::is_nil( theMesh ) )
2056 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2057 SALOME::BAD_PARAM );
2059 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2062 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2063 meshServant->Load();
2064 ASSERT( meshServant );
2065 if ( meshServant ) {
2066 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2067 meshServant->CheckGeomModif();
2068 // get local TopoDS_Shape
2069 TopoDS_Shape myLocShape;
2070 if(theMesh->HasShapeToMesh())
2071 myLocShape = GeomObjectToShape( theShapeObject );
2073 return result._retn();;
2075 // call implementation compute
2076 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2078 ::MeshDimension aDim = (MeshDimension)theDimension;
2079 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2081 int nbShapeId = shapeIds.size();
2082 theShapesId.length( nbShapeId );
2083 // iterates on shapes and collect mesh entities into mesh preview
2084 TSetOfInt::const_iterator idIt = shapeIds.begin();
2085 TSetOfInt::const_iterator idEnd = shapeIds.end();
2086 std::map< int, int > mapOfShIdNb;
2087 std::set< SMESH_TLink > setOfEdge;
2088 std::list< SMDSAbs_ElementType > listOfElemType;
2089 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2090 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2091 TNode2LocalIDMap mapNode2LocalID;
2092 list< TNodeLocalID > connectivity;
2093 int i, nbConnNodes = 0;
2094 std::set< const SMESH_subMesh* > setOfVSubMesh;
2095 // iterates on shapes
2096 for ( ; idIt != idEnd; idIt++ )
2098 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2100 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2101 if ( !sm || !sm->IsMeshComputed() )
2104 const TopoDS_Shape& aSh = sm->GetSubShape();
2105 const int shDim = myGen.GetShapeDim( aSh );
2106 if ( shDim < 1 || shDim > theDimension )
2109 mapOfShIdNb[ *idIt ] = 0;
2110 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2112 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2113 if ( !smDS ) continue;
2115 if ( theDimension == SMESH::DIM_2D )
2117 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2118 while ( faceIt->more() )
2120 const SMDS_MeshElement* face = faceIt->next();
2121 int aNbNode = face->NbNodes();
2123 aNbNode /= 2; // do not take into account additional middle nodes
2125 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2126 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2128 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2129 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2131 listOfElemType.push_back( SMDSAbs_Edge );
2132 connectivity.push_back
2133 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2134 connectivity.push_back
2135 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2141 else if ( theDimension == SMESH::DIM_1D )
2143 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2144 while ( nodeIt->more() )
2146 listOfElemType.push_back( SMDSAbs_Node );
2147 connectivity.push_back
2148 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2150 // add corner nodes by first vertex from edge
2151 SMESH_subMeshIteratorPtr edgeSmIt =
2152 sm->getDependsOnIterator(/*includeSelf*/false,
2153 /*complexShapeFirst*/false);
2154 while ( edgeSmIt->more() )
2156 SMESH_subMesh* vertexSM = edgeSmIt->next();
2157 // check that vertex is not already treated
2158 if ( !setOfVSubMesh.insert( vertexSM ).second )
2160 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2163 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2164 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2165 while ( nodeIt->more() )
2167 listOfElemType.push_back( SMDSAbs_Node );
2168 connectivity.push_back
2169 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2175 // fill node coords and assign local ids to the nodes
2176 int nbNodes = mapNode2LocalID.size();
2177 result->nodesXYZ.length( nbNodes );
2178 TNodeLocalID node2ID = mapNode2LocalID.begin();
2179 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2180 node2ID->second = i;
2181 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2182 result->nodesXYZ[i].x = node->X();
2183 result->nodesXYZ[i].y = node->Y();
2184 result->nodesXYZ[i].z = node->Z();
2186 // fill connectivity
2187 result->elementConnectivities.length( nbConnNodes );
2188 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2189 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2190 result->elementConnectivities[i] = (*connIt)->second;
2193 // fill element types
2194 result->elementTypes.length( listOfElemType.size() );
2195 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2196 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2197 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2199 SMDSAbs_ElementType elemType = *typeIt;
2200 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2201 result->elementTypes[i].isPoly = false;
2202 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2205 // correct number of shapes
2206 theShapesId.length( mapOfShIdNb.size() );
2210 catch ( std::bad_alloc ) {
2211 INFOS( "Precompute(): lack of memory" );
2213 catch ( SALOME_Exception& S_ex ) {
2214 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2217 INFOS( "Precompute(): unknown exception " );
2219 return result._retn();
2223 //=============================================================================
2225 * SMESH_Gen_i::Evaluate
2227 * Evaluate mesh on a shape
2229 //=============================================================================
2231 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2232 GEOM::GEOM_Object_ptr theShapeObject)
2233 // SMESH::long_array& theNbElems)
2234 throw ( SALOME::SALOME_Exception )
2236 Unexpect aCatch(SALOME_SalomeException);
2237 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2239 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2240 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2241 SALOME::BAD_PARAM );
2243 if ( CORBA::is_nil( theMesh ) )
2244 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2245 SALOME::BAD_PARAM );
2247 SMESH::long_array_var nbels = new SMESH::long_array;
2248 nbels->length(SMESH::Entity_Last);
2249 int i = SMESH::Entity_Node;
2250 for (; i < SMESH::Entity_Last; i++)
2253 // Update Python script
2254 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2255 << theMesh << ", " << theShapeObject << ")";
2259 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2260 ASSERT( meshServant );
2261 if ( meshServant ) {
2262 meshServant->Load();
2263 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2264 meshServant->CheckGeomModif();
2265 // get local TopoDS_Shape
2266 TopoDS_Shape myLocShape;
2267 if(theMesh->HasShapeToMesh())
2268 myLocShape = GeomObjectToShape( theShapeObject );
2270 myLocShape = SMESH_Mesh::PseudoShape();
2271 // call implementation compute
2272 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2273 MapShapeNbElems aResMap;
2274 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2275 MapShapeNbElemsItr anIt = aResMap.begin();
2276 for(; anIt!=aResMap.end(); anIt++) {
2277 const vector<int>& aVec = (*anIt).second;
2278 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2279 int nbElem = aVec[i];
2280 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2282 SMESH_subMesh* sm = anIt->first;
2283 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2284 const SMESH_Algo* algo = sm->GetAlgo();
2285 if ( (algo && !error.get()) || error->IsOK() )
2286 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2290 nbels[i] += aVec[i];
2294 return nbels._retn();
2297 catch ( std::bad_alloc ) {
2298 INFOS( "Evaluate(): lack of memory" );
2300 catch ( SALOME_Exception& S_ex ) {
2301 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2304 INFOS( "Evaluate(): unknown exception " );
2307 return nbels._retn();
2310 //================================================================================
2312 * \brief Return geometrical object the given element is built on
2313 * \param theMesh - the mesh the element is in
2314 * \param theElementID - the element ID
2315 * \param theGeomName - the name of the result geom object if it is not yet published
2316 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2318 //================================================================================
2320 GEOM::GEOM_Object_ptr
2321 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2322 CORBA::Long theElementID,
2323 const char* theGeomName)
2324 throw ( SALOME::SALOME_Exception )
2326 Unexpect aCatch(SALOME_SalomeException);
2328 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2329 if ( !geom->_is_nil() ) {
2330 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2331 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine( geom );
2333 // try to find the corresponding SObject
2334 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2335 if ( SObj->_is_nil() ) // submesh can be not found even if published
2337 // try to find published submesh
2338 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2339 if ( !geom->IsMainShape() && list->length() == 1 ) {
2340 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2341 SALOMEDS::ChildIterator_wrap it;
2342 if ( !mainSO->_is_nil() ) {
2343 it = getStudyServant()->NewChildIterator( mainSO );
2345 if ( !it->_is_nil() ) {
2346 for ( it->InitEx(true); it->More(); it->Next() ) {
2347 SALOMEDS::SObject_wrap so = it->Value();
2348 CORBA::Object_var obj = SObjectToObject( so );
2349 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2350 if ( !subGeom->_is_nil() ) {
2351 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2352 if ( subList->length() == 1 && list[0] == subList[0] ) {
2362 if ( SObj->_is_nil() ) // publish a new subshape
2363 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2365 // return only published geometry
2366 if ( !SObj->_is_nil() ) {
2367 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2368 CORBA::Object_var obj = SObjectToObject( SObj );
2369 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2373 return GEOM::GEOM_Object::_nil();
2376 //================================================================================
2378 * \brief Return geometrical object the given element is built on.
2379 * \param theMesh - the mesh the element is in
2380 * \param theElementID - the element ID
2381 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2383 //================================================================================
2385 GEOM::GEOM_Object_ptr
2386 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2387 CORBA::Long theElementID)
2388 throw ( SALOME::SALOME_Exception )
2390 Unexpect aCatch(SALOME_SalomeException);
2391 if ( CORBA::is_nil( theMesh ) )
2392 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2394 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2395 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine( mainShape );
2397 // get a core mesh DS
2398 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2399 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2401 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2402 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2403 // find the element in mesh
2404 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2405 // find a shape id by the element
2406 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2407 // get a geom object by the shape id
2408 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2409 if ( geom->_is_nil() ) {
2410 // try to find a published sub-shape
2411 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2412 SALOMEDS::ChildIterator_wrap it;
2413 if ( !mainSO->_is_nil() ) {
2414 it = getStudyServant()->NewChildIterator( mainSO );
2416 if ( !it->_is_nil() ) {
2417 for ( it->InitEx(true); it->More(); it->Next() ) {
2418 SALOMEDS::SObject_wrap so = it->Value();
2419 CORBA::Object_var obj = SObjectToObject( so );
2420 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2421 if ( !subGeom->_is_nil() ) {
2422 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2423 if ( subList->length() == 1 && shapeID == subList[0] ) {
2431 if ( geom->_is_nil() ) {
2433 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2434 if ( !op->_is_nil() )
2435 geom = op->GetSubShape( mainShape, shapeID );
2440 if ( !geom->_is_nil() ) {
2441 GeomObjectToShape( geom ); // let geom client remember the found shape
2442 return geom._retn();
2447 return GEOM::GEOM_Object::_nil();
2450 //================================================================================
2452 * SMESH_Gen_i::Concatenate
2454 * Concatenate the given meshes into one mesh
2456 //================================================================================
2458 SMESH::SMESH_Mesh_ptr
2459 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2460 CORBA::Boolean theUniteIdenticalGroups,
2461 CORBA::Boolean theMergeNodesAndElements,
2462 CORBA::Double theMergeTolerance,
2463 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2464 throw ( SALOME::SALOME_Exception )
2466 return ConcatenateCommon(theMeshesArray,
2467 theUniteIdenticalGroups,
2468 theMergeNodesAndElements,
2474 //================================================================================
2476 * SMESH_Gen_i::ConcatenateWithGroups
2478 * Concatenate the given meshes into one mesh
2479 * Create the groups of all elements from initial meshes
2481 //================================================================================
2483 SMESH::SMESH_Mesh_ptr
2484 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2485 CORBA::Boolean theUniteIdenticalGroups,
2486 CORBA::Boolean theMergeNodesAndElements,
2487 CORBA::Double theMergeTolerance,
2488 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2489 throw ( SALOME::SALOME_Exception )
2491 return ConcatenateCommon(theMeshesArray,
2492 theUniteIdenticalGroups,
2493 theMergeNodesAndElements,
2499 //================================================================================
2501 * SMESH_Gen_i::ConcatenateCommon
2503 * Concatenate the given meshes into one mesh
2505 //================================================================================
2507 SMESH::SMESH_Mesh_ptr
2508 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2509 CORBA::Boolean theUniteIdenticalGroups,
2510 CORBA::Boolean theMergeNodesAndElements,
2511 CORBA::Double theMergeTolerance,
2512 CORBA::Boolean theCommonGroups,
2513 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2514 throw ( SALOME::SALOME_Exception )
2516 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2517 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2519 // create mesh if theMeshToAppendTo not provided
2520 SMESH::SMESH_Mesh_var newMesh;
2521 if ( CORBA::is_nil( theMeshToAppendTo ))
2522 newMesh = CreateEmptyMesh();
2524 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2525 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2526 if ( !newImpl ) return newMesh._retn();
2529 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2530 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2532 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2533 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2534 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2535 TGroupsMap groupsMap;
2536 TListOfNewGroups listOfNewGroups;
2538 if ( !CORBA::is_nil( theMeshToAppendTo ))
2540 // fill groupsMap with existing groups
2541 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2542 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2544 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2545 if ( !group->_is_nil() )
2547 CORBA::String_var name = group->GetName();
2548 SMESH::ElementType type = group->GetType();
2549 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2554 ::SMESH_MeshEditor newEditor( &locMesh );
2555 ::SMESH_MeshEditor::ElemFeatures elemType;
2557 // loop on sub-meshes
2558 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2560 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2561 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2562 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2563 if ( !initImpl ) continue;
2564 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2568 // assure that IDs increment by one during iteration
2569 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2570 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2571 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2572 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2574 initMeshDS->Modified();
2575 initMeshDS->CompactMesh();
2578 // remember nb of elements before filling in
2579 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2583 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2584 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2585 while ( elemIt->more() )
2587 SMESH_NodeXYZ node = elemIt->next();
2588 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2593 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2594 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2596 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2597 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2598 while ( elemIt->more() )
2600 const SMDS_MeshElement* elem = elemIt->next();
2601 elemType.myNodes.resize( elem->NbNodes() );
2603 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2604 for ( int k = 0; itNodes->more(); k++)
2606 const SMDS_MeshNode* node = itNodes->next();
2607 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2610 // creates a corresponding element on existent nodes in new mesh
2611 newElems[ elem->GetID() ] =
2612 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2614 newEditor.ClearLastCreated(); // forget the history
2617 // create groups of just added elements
2618 SMESH::SMESH_Group_var newGroup;
2619 SMESH::ElementType groupType;
2620 if ( theCommonGroups )
2623 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2624 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2625 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2626 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2629 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2631 for( groupType = SMESH::NODE;
2632 groupType < SMESH::NB_ELEMENT_TYPES;
2633 groupType = (SMESH::ElementType)( groupType + 1 ))
2635 if ( curState[ groupType ] <= prevState[ groupType ])
2636 continue; // no elements of groupType added from the i-th mesh
2638 // make a group name
2639 std::string groupName = "Gr";
2640 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2642 CORBA::String_var name = meshSO->GetName();
2646 groupName += typeNames[ groupType ];
2648 // make and fill a group
2649 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2650 std::vector< const SMDS_MeshElement* > & elemVec =
2651 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2652 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2654 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2656 for ( size_t j = 0; j < elemVec.size(); ++j )
2658 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2659 grpDS->Add( elemVec[j] );
2663 listOfNewGroups.clear();
2664 listOfNewGroups.push_back( newGroup );
2665 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2670 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2674 SMESH::SMESH_GroupBase_ptr group;
2675 CORBA::String_var groupName;
2676 SMESH::long_array_var newIDs = new SMESH::long_array();
2678 // loop on groups of a source mesh
2679 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2680 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2682 group = listOfGroups[iG];
2683 groupType = group->GetType();
2684 groupName = group->GetName();
2685 std::string name = groupName.in();
2687 // convert a list of IDs
2688 newIDs->length( group->Size() );
2689 std::vector< const SMDS_MeshElement* > & elemVec =
2690 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2691 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2693 while ( itGrElems->more() )
2695 const SMDS_MeshElement* elem = itGrElems->next();
2696 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2698 newIDs[ nbElems++ ] = newElem->GetID();
2700 newIDs->length( nbElems );
2702 // check that a current group name and type don't have identical ones in final mesh
2703 listOfNewGroups.clear();
2704 TNameAndType nameAndType( name, groupType );
2705 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2706 if ( anIter == groupsMap.end() )
2708 // add a new group in the mesh
2709 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2710 newGroup->Add( newIDs );
2712 listOfNewGroups.push_back( newGroup );
2713 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2715 else if ( theUniteIdenticalGroups )
2717 // unite identical groups
2718 TListOfNewGroups& aNewGroups = anIter->second;
2719 aNewGroups.front()->Add( newIDs );
2723 // rename identical groups
2724 newGroup = newImpl->CreateGroup( groupType, groupName );
2725 newGroup->Add( newIDs );
2727 TListOfNewGroups& newGroups = anIter->second;
2728 std::string newGroupName;
2729 if ( newGroups.size() == 1 )
2731 newGroupName = name + "_1";
2732 newGroups.front()->SetName( newGroupName.c_str() );
2734 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2735 newGroup->SetName( newGroupName.c_str() );
2736 newGroups.push_back( newGroup );
2739 } // if an IDSource is a mesh
2742 if ( theMergeNodesAndElements ) // merge nodes
2744 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2745 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2746 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2747 /*SeparateCornersAndMedium=*/ false );
2748 newEditor.MergeNodes( groupsOfNodes );
2750 newEditor.MergeEqualElements();
2753 // Update Python script
2754 pythonDump << newMesh << " = " << this
2755 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2756 << theMeshesArray << ", "
2757 << theUniteIdenticalGroups << ", "
2758 << theMergeNodesAndElements << ", "
2759 << TVar( theMergeTolerance ) << ", "
2760 << theMeshToAppendTo << " )";
2762 pPythonDump.reset(); // enable python dump from GetGroups()
2764 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2765 if ( !newMesh->_is_nil() )
2767 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2770 // IPAL21468 Change icon of compound because it need not be computed.
2771 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2772 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2774 newMeshDS->Modified();
2776 return newMesh._retn();
2779 //================================================================================
2781 * \brief Create a mesh by copying a part of another mesh
2782 * \param meshPart - a part of mesh to copy
2783 * \param toCopyGroups - to create in the new mesh groups
2784 * the copied elements belongs to
2785 * \param toKeepIDs - to preserve IDs of the copied elements or not
2786 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2788 //================================================================================
2790 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2791 const char* meshName,
2792 CORBA::Boolean toCopyGroups,
2793 CORBA::Boolean toKeepIDs)
2794 throw ( SALOME::SALOME_Exception )
2796 Unexpect aCatch(SALOME_SalomeException);
2798 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2799 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2801 // 1. Get source mesh
2803 if ( CORBA::is_nil( meshPart ))
2804 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2806 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2807 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2809 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2811 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2813 // 2. Make a new mesh
2815 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2816 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2818 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2819 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2820 if ( !meshSO->_is_nil() )
2822 SetName( meshSO, meshName, "Mesh" );
2823 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2825 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2826 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2827 ::SMESH_MeshEditor::ElemFeatures elemType;
2829 // 3. Get elements to copy
2831 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2832 TIDSortedElemSet srcElems;
2833 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2834 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2837 srcElemIt = srcMeshDS->elementsIterator();
2838 srcNodeIt = srcMeshDS->nodesIterator();
2842 SMESH::long_array_var ids = meshPart->GetIDs();
2843 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2845 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2846 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2847 srcElems.insert( elem );
2851 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2852 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2853 srcElems.insert( elem );
2855 if ( srcElems.empty() )
2856 return newMesh._retn();
2858 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2859 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2864 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2865 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2866 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2868 const SMDS_MeshNode *nSrc, *nTgt;
2869 vector< const SMDS_MeshNode* > nodes;
2870 while ( srcElemIt->more() )
2872 const SMDS_MeshElement * elem = srcElemIt->next();
2874 nodes.resize( elem->NbNodes());
2875 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2877 for ( iN = 0; nIt->more(); ++iN )
2879 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2880 nTgt = newMeshDS->FindNode( nSrc->GetID());
2882 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2887 for ( iN = 0; nIt->more(); ++iN )
2889 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2890 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2892 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2893 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2897 if ( elem->GetType() != SMDSAbs_Node )
2899 elemType.Init( elem, /*basicOnly=*/false );
2900 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2902 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2903 if ( toCopyGroups && !toKeepIDs )
2904 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2906 } // while ( srcElemIt->more() )
2908 // 4(b). Copy free nodes
2910 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2912 while ( srcNodeIt->more() )
2914 nSrc = srcNodeIt->next();
2915 if ( nSrc->NbInverseElements() == 0 )
2918 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2920 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2927 int nbNewGroups = 0;
2930 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2931 while ( gIt->more() )
2933 SMESH_Group* group = gIt->next();
2934 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2936 // Check group type. We copy nodal groups containing nodes of copied element
2937 SMDSAbs_ElementType groupType = groupDS->GetType();
2938 if ( groupType != SMDSAbs_Node &&
2939 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2940 continue; // group type differs from types of meshPart
2942 // Find copied elements in the group
2943 vector< const SMDS_MeshElement* > groupElems;
2944 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2947 const SMDS_MeshElement* foundElem;
2948 if ( groupType == SMDSAbs_Node )
2950 while ( eIt->more() )
2951 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2952 groupElems.push_back( foundElem );
2956 while ( eIt->more() )
2957 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2958 groupElems.push_back( foundElem );
2963 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2964 if ( e2eMap.empty() ) continue;
2965 int minID = e2eMap.begin()->first->GetID();
2966 int maxID = e2eMap.rbegin()->first->GetID();
2967 TE2EMap::iterator e2e;
2968 while ( eIt->more() && groupElems.size() < e2eMap.size())
2970 const SMDS_MeshElement* e = eIt->next();
2971 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2972 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2973 groupElems.push_back( e2e->second );
2977 if ( !groupElems.empty() )
2979 SMESH::SMESH_Group_var newGroupObj =
2980 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2981 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2983 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2984 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2985 for ( unsigned i = 0; i < groupElems.size(); ++i )
2986 smdsGroup.Add( groupElems[i] );
2994 newMeshDS->Modified();
2996 *pyDump << newMesh << " = " << this
2997 << ".CopyMesh( " << meshPart << ", "
2998 << "'" << meshName << "', "
2999 << toCopyGroups << ", "
3000 << toKeepIDs << ")";
3002 pyDumpDeleter.reset(); // allow dump in GetGroups()
3004 if ( nbNewGroups > 0 ) // dump created groups
3005 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3007 return newMesh._retn();
3011 namespace // utils for CopyMeshWithGeom()
3013 typedef std::map< std::string, std::string > TStr2StrMap;
3014 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3015 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3016 typedef std::map< std::string, int > TName2IndexMap;
3018 //================================================================================
3020 * \brief Return a new sub-shape corresponding to an old one
3022 //================================================================================
3026 SMESH_Mesh_i* mySrcMesh_i;
3027 SMESH_Mesh_i* myNewMesh_i;
3028 SMESH_Gen_i* myGen_i;
3032 TStr2StrMap myOld2NewEntryMap; // map of study entries
3034 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3035 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3036 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3039 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3041 // not directly relating to shape search
3042 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3044 //================================================================================
3046 * \brief Constructor
3048 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3049 SMESH_Mesh_i* newMesh_i,
3050 SMESH_Gen_i* smeshGen_i )
3051 : mySrcMesh_i( srcMesh_i ),
3052 myNewMesh_i( newMesh_i ),
3053 myGen_i ( smeshGen_i ),
3054 myToPublish( smeshGen_i->IsEnablePublish() ),
3055 myGIPMapDone( false )
3057 // retrieve from the study shape mapping made thanks to
3058 // "Set presentation parameters and sub-shapes from arguments" option
3060 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3061 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3062 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3063 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3064 if ( newSO->_is_nil() )
3066 myToPublish = false;
3069 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3071 CORBA::String_var oldEntry = oldSO->GetID();
3072 CORBA::String_var newEntry = newSO->GetID();
3073 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3074 std::string( newEntry.in() )));
3075 std::string newMainEntry = newEntry.in();
3077 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3078 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3079 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3080 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3081 /*groupsOnly=*/false );
3082 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3084 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3085 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3086 bool refFound = false;
3087 for ( ; anIter->More(); anIter->Next() )
3089 SALOMEDS::SObject_wrap so = anIter->Value();
3090 if ( so->ReferencedObject( oldSO.inout() ))
3092 oldEntry = oldSO->GetID();
3093 newEntry = newSO->GetID();
3094 if (( refFound = ( newMainEntry != oldEntry.in() )))
3095 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3096 std::string( newEntry.in() )));
3101 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3102 if ( father->_is_equivalent( mainShapeNew ))
3104 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3105 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3106 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3107 CORBA::String_var name = newSO->GetName();
3109 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3115 //================================================================================
3117 * \brief Find a new sub-shape corresponding to an old one
3119 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3122 return GEOM::GEOM_Object::_duplicate( oldShape );
3124 GEOM::GEOM_Object_var newShape;
3126 if ( CORBA::is_nil( oldShape ))
3127 return newShape._retn();
3129 if ( !isChildOfOld( oldShape ))
3130 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3132 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3133 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3135 // try to find by entry or name
3138 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3139 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3140 if ( o2nID != myOld2NewEntryMap.end() )
3142 newShape = getShapeByEntry( o2nID->second );
3144 if ( newShape->_is_nil() )
3146 CORBA::String_var name = oldShape->GetName();
3147 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3148 if ( n2ind != myName2SubshapeIndex.end() )
3150 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3151 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3152 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3153 if ( oldIndices->length() == 0 ||
3154 newIndices->length() == 0 ||
3155 getShapeType( myNewMesh_i, newIndices[0] ) !=
3156 getShapeType( mySrcMesh_i, oldIndices[0] ))
3157 newShape = GEOM::GEOM_Object::_nil();
3162 if ( newShape->_is_nil() )
3164 // try to construct a new sub-shape using myGIPMap
3166 std::vector< int > newIndices;
3167 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3168 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3170 findNewIDs( oldIndices[i], newIndices );
3172 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3175 newShape = getInPlace( oldShape );
3177 if ( !newIndices.empty() && newShape->_is_nil() )
3179 // search for a sub-shape with same ids
3180 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3181 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3182 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3183 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3185 if ( newShape->_is_nil() )
3188 // create a new shape
3189 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3191 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3193 GEOM::GEOM_IGroupOperations_ptr grOp = geomGen->GetIGroupOperations();
3194 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3196 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3197 newIndicesList->length( newIndices.size() );
3198 for ( size_t i = 0; i < newIndices.size(); ++i )
3199 newIndicesList[ i ] = newIndices[ i ];
3200 grOp->UnionIDs( newShape, newIndicesList );
3204 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3205 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3214 if ( !newShape->_is_nil() && myToPublish )
3216 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3217 if ( !newEntry.in() || !newEntry.in()[0] )
3219 CORBA::String_var name = oldShape->GetName();
3220 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3221 newEntry = newShape->GetStudyEntry();
3222 oldEntry = oldShape->GetStudyEntry();
3223 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3224 std::string( newEntry.in() )));
3228 return newShape._retn();
3231 //================================================================================
3233 * \brief Return a study entry of a new shape by study entry of the old one
3235 std::string FindNew( const std::string & oldEntry )
3240 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3241 if ( o2nID != myOld2NewEntryMap.end() )
3242 return o2nID->second;
3244 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3245 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3248 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3249 if ( newShape->_is_nil() )
3250 return std::string();
3252 CORBA::String_var newEntry = newShape->GetStudyEntry();
3253 return newEntry.in();
3256 //================================================================================
3258 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3259 * Return zero if not found or there are more than one new ID
3261 int FindNew( int oldID )
3270 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3272 if ( myGIPMap[ oldID ].length() == 1 )
3274 newID = myGIPMap[ oldID ][ 0 ];
3276 else if ( myGIPMap[ oldID ].length() > 1 &&
3277 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3279 // select a meshed VERTEX
3280 SMESH_subMesh* newSM;
3281 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3282 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3283 ( !newSM->IsEmpty() ))
3284 newID = myGIPMap[ oldID ][ i ];
3290 //================================================================================
3292 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3293 * Return zero if the old shape is not kept as is in the new shape.
3295 int FindNewNotChanged( SMESH_subMesh* oldSM )
3298 return oldSM->GetId();
3300 int newID = FindNew( oldSM->GetId() );
3304 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3308 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3309 // one new sub-shape of the same type.
3311 if ( oldSM->DependsOn().size() !=
3312 newSM->DependsOn().size() )
3315 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3316 while ( srcSMIt->more() )
3318 oldSM = srcSMIt->next();
3319 int newSubID = FindNew( oldSM->GetId() );
3320 if ( getShapeType( myNewMesh_i, newSubID ) !=
3321 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3327 //================================================================================
3329 * \brief Return shape by study entry
3331 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3333 GEOM::GEOM_Object_var shape;
3334 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3335 if ( !so->_is_nil() )
3337 CORBA::Object_var obj = so->GetObject();
3338 shape = GEOM::GEOM_Object::_narrow( obj );
3340 return shape._retn();
3343 //================================================================================
3345 * \brief Fill myGIPMap by calling GetInPlaceMap()
3349 if ( !myGIPMapDone )
3351 myGIPMapDone = true;
3353 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3354 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3355 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3356 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3359 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3363 myGIPMap = new GEOM::ListOfListOfLong();
3368 //================================================================================
3370 * \brief Get new sub-shape by calling GetInPlace()
3372 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3374 GEOM::GEOM_Object_var newShape;
3376 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3377 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3378 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3381 newShape = op->GetInPlace( mainShapeNew, oldShape );
3386 return newShape._retn();
3389 //================================================================================
3391 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3392 * number of found IDs
3394 int findNewIDs( int oldID, std::vector< int >& newIDs )
3396 size_t prevNbIDs = newIDs.size();
3398 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3400 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3401 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3403 return newIDs.size() - prevNbIDs;
3406 //================================================================================
3408 * \brief Check if an object relates to the old shape
3410 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3412 if ( CORBA::is_nil( oldShape ))
3414 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3415 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3416 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3417 mainShapeOld1->_is_equivalent( oldShape ));
3420 //================================================================================
3422 * \brief Return shape type by shape ID
3424 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3426 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3427 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3428 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3431 //================================================================================
3433 * \brief Store a source sub-shape for which a counterpart not found and
3434 * a smesh object invalid due to that
3436 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3437 SALOMEDS::SObject_wrap smeshSO )
3439 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3440 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3442 CORBA::String_var smeshEntry = smeshSO->GetID();
3443 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3447 //================================================================================
3449 * \brief Store a source sub-shape for which a counterpart not found and
3450 * a smesh object invalid due to that
3452 void AddInvalid( std::string geomEntry,
3453 SALOMEDS::SObject_wrap smeshSO )
3455 if ( !geomEntry.empty() )
3457 CORBA::String_var smeshEntry = smeshSO->GetID();
3458 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3462 //================================================================================
3464 * \brief Store a source sub-shape for which a counterpart not found and
3465 * a smesh object invalid due to that
3467 void AddInvalid( int oldGeomID,
3468 SALOMEDS::SObject_wrap smeshSO )
3470 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3471 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3474 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3475 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3477 SMESH_Comment geomName( typeName[ shapeType ]);
3478 geomName << " #" << oldGeomID;
3480 CORBA::String_var smeshEntry = smeshSO->GetID();
3481 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3484 //================================================================================
3486 * \brief Return entries of a source sub-shape for which a counterpart not found and
3487 * of smesh objects invalid due to that
3489 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3490 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3493 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3494 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3496 nbSO += 1 + entry2entrySet->second.size();
3498 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3499 theInvalidEntries->length ( nbSO );
3500 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3502 entry2entrySet = myInvalidMap.begin();
3503 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3505 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3507 std::set< std::string > & entrySet = entry2entrySet->second;
3508 std::set< std::string >::iterator entry = entrySet.begin();
3509 for ( ; entry != entrySet.end(); ++entry )
3511 theInvalidEntries[ iEntry++ ] = entry->c_str();
3513 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3514 if ( !so->_is_nil() )
3515 theInvalidMeshSObjects[ iSO++ ] = so;
3520 }; // struct ShapeMapper
3522 //================================================================================
3524 * \brief Append an item to a CORBA sequence
3526 template < class CORBA_seq, class ITEM >
3527 void append( CORBA_seq& seq, ITEM item )
3529 if ( !CORBA::is_nil( item ))
3531 seq->length( 1 + seq->length() );
3532 seq[ seq->length() - 1 ] = item;
3535 } // namespace // utils for CopyMeshWithGeom()
3537 //================================================================================
3539 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3540 * \param [in] sourceMesh - a mesh to copy
3541 * \param [in] newGeometry - a new geometry
3542 * \param [in] toCopyGroups - to create groups in the new mesh
3543 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3544 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3545 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3546 * \param [out] newMesh - return a new mesh
3547 * \param [out] newGroups - return new groups
3548 * \param [out] newSubmeshes - return new sub-meshes
3549 * \param [out] newHypotheses - return new algorithms and hypotheses
3550 * \param [out] invalidEntries - return study entries of objects whose
3551 * counterparts are not found in the newGeometry, followed by entries
3552 * of mesh sub-objects that are invalid because they depend on a not found
3553 * preceding sub-shape
3554 * \return CORBA::Boolean - is a success
3556 //================================================================================
3558 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3559 GEOM::GEOM_Object_ptr theNewGeometry,
3560 const char* theMeshName,
3561 CORBA::Boolean theToCopyGroups,
3562 CORBA::Boolean theToReuseHypotheses,
3563 CORBA::Boolean theToCopyElements,
3564 SMESH::SMESH_Mesh_out theNewMesh,
3565 SMESH::ListOfGroups_out theNewGroups,
3566 SMESH::submesh_array_out theNewSubmeshes,
3567 SMESH::ListOfHypothesis_out theNewHypotheses,
3568 SMESH::string_array_out theInvalidEntries)
3569 throw ( SALOME::SALOME_Exception )
3571 if ( CORBA::is_nil( theSourceMesh ) ||
3572 CORBA::is_nil( theNewGeometry ))
3573 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3575 if ( !theSourceMesh->HasShapeToMesh() )
3576 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3581 TPythonDump pyDump; // prevent dump from CreateMesh()
3583 theNewMesh = CreateMesh( theNewGeometry );
3584 theNewGroups = new SMESH::ListOfGroups();
3585 theNewSubmeshes = new SMESH::submesh_array();
3586 theNewHypotheses = new SMESH::ListOfHypothesis();
3587 theInvalidEntries = new SMESH::string_array();
3589 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3591 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3592 GEOM::GEOM_Object_var geom, newGeom;
3593 SALOMEDS::SObject_wrap so;
3595 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3596 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3599 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3601 // treat hypotheses of mesh and sub-meshes
3602 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3603 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3605 bool isSubMesh = ( iSM < smList->length() );
3608 // create a new sub-mesh
3609 SMESH::SMESH_subMesh_var newSM;
3610 geom = smList[iSM]->GetSubShape();
3611 so = ObjectToSObject( smList[iSM] );
3612 CORBA::String_var name;
3613 if ( !so->_is_nil() )
3614 name = so->GetName();
3615 newGeom = shapeMapper.FindNew( geom );
3616 if ( newGeom->_is_nil() )
3618 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3619 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3624 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3626 append( theNewSubmeshes, newSM );
3628 if ( newGeom->_is_nil() )
3629 continue; // don't assign hypotheses
3633 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3635 so = ObjectToSObject( theNewMesh );
3636 SetName( so, theMeshName, "Mesh" );
3639 // assign hypotheses
3640 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3641 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3643 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3644 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3646 // get geometry hyp depends on
3647 std::vector< std::string > entryArray;
3648 std::vector< int > subIDArray;
3649 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3651 if ( !theToReuseHypotheses || dependsOnGeom )
3653 // create a new hypothesis
3654 CORBA::String_var type = hyp->GetName();
3655 CORBA::String_var lib = hyp->GetLibName();
3656 CORBA::String_var data = hyp_i->SaveTo();
3659 hyp = CreateHypothesis( type, lib );
3660 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3661 hyp_i->LoadFrom( data.in() );
3662 append( theNewHypotheses, hyp );
3666 // update geometry hyp depends on
3667 if ( dependsOnGeom )
3669 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3671 if ( !entryArray[ iGeo ].empty() )
3673 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3674 if ( newEntry.empty() )
3677 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3678 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3680 entryArray[ iGeo ] = newEntry;
3683 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3685 if ( subIDArray[ iGeo ] > 0 )
3687 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3691 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3692 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3694 subIDArray[ iGeo ] = newID;
3697 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3701 CORBA::String_var errorText;
3702 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3703 if ( errorText.in()[0] )
3706 } // loop on hypotheses
3707 } // loop on sub-meshes and mesh
3710 // copy mesh elements, keeping IDs
3711 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3712 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3714 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3715 ::SMESH_MeshEditor::ElemFeatures elemData;
3717 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3718 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3719 /*vertexLast=*/false);
3720 while ( srcSMIt->more() )
3722 SMESH_subMesh* srcSM = srcSMIt->next();
3723 if ( srcSM->IsEmpty() )
3724 continue; // not yet computed
3725 int newID = shapeMapper.FindNewNotChanged( srcSM );
3729 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3730 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3731 while ( nIt->more() )
3733 SMESH_NodeXYZ node( nIt->next() );
3734 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3736 const SMDS_PositionPtr pos = node->GetPosition();
3737 const double* uv = pos->GetParameters();
3738 switch ( pos->GetTypeOfPosition() )
3740 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3741 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3742 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3743 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3747 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3748 while( eIt->more() )
3750 const SMDS_MeshElement* e = eIt->next();
3751 elemData.Init( e, /*basicOnly=*/false );
3752 elemData.SetID( e->GetID() );
3753 elemData.myNodes.resize( e->NbNodes() );
3754 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3756 for ( iN = 0; nnIt->more(); ++iN )
3758 const SMDS_MeshNode* srcNode = nnIt->next();
3759 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3760 if ( !elemData.myNodes[ iN ])
3763 if ( iN == elemData.myNodes.size() )
3764 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3765 newMeshDS->SetMeshElementOnShape( newElem, newID );
3767 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3768 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3771 newMeshDS->Modified();
3777 TStr2StrMap old2newGroupMap;
3779 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3781 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3782 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3783 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3785 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3786 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3787 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3789 CORBA::String_var name = groups[ i ]->GetName();
3790 SMESH::ElementType elemType = groups[ i ]->GetType();
3792 SMESH::SMESH_GroupBase_var newGroup;
3794 if ( !stdlGroup->_is_nil() )
3796 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3798 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3799 const bool isElem = ( elemType != SMESH::NODE );
3800 CORBA::ULong iE = 0;
3801 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3802 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3804 if ( iE < elemIDs->length() )
3806 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3807 stdlGroup->Add( elemIDs );
3808 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3812 else if ( !geomGroup->_is_nil() )
3814 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3815 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3816 if ( newGeom->_is_nil() )
3818 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3819 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3824 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3827 else if ( !fltrGroup->_is_nil() )
3829 // replace geometry in a filter
3830 SMESH::Filter_var filter = fltrGroup->GetFilter();
3831 SMESH::Filter::Criteria_var criteria;
3832 filter->GetCriteria( criteria.out() );
3834 bool isMissingGroup = false;
3835 std::vector< std::string > badEntries;
3837 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3839 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3840 switch ( criteria[ iCr ].Type )
3842 case SMESH::FT_BelongToMeshGroup:
3844 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3845 btgg->SetGroupID( thresholdID );
3846 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3847 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3848 if ( refGroupSO->_is_nil() )
3850 CORBA::String_var refID = refGroupSO->GetID();
3851 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3852 if ( o2nID == old2newGroupMap.end() )
3854 isMissingGroup = true; // corresponding new group not yet created
3857 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3859 if ( o2nID->second.empty() ) // new referred group is invalid
3860 badEntries.push_back( refID.in() );
3863 case SMESH::FT_BelongToGeom:
3864 case SMESH::FT_BelongToPlane:
3865 case SMESH::FT_BelongToCylinder:
3866 case SMESH::FT_BelongToGenSurface:
3867 case SMESH::FT_LyingOnGeom:
3869 std::string newID = shapeMapper.FindNew( thresholdID );
3870 criteria[ iCr ].ThresholdID = newID.c_str();
3871 if ( newID.empty() )
3872 badEntries.push_back( thresholdID );
3875 case SMESH::FT_ConnectedElements:
3877 if ( thresholdID && thresholdID[0] )
3879 std::string newID = shapeMapper.FindNew( thresholdID );
3880 criteria[ iCr ].ThresholdID = newID.c_str();
3881 if ( newID.empty() )
3882 badEntries.push_back( thresholdID );
3888 } // loop on criteria
3890 if ( isMissingGroup && i < nbGroups )
3892 // to treat the group again
3893 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3897 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3898 newFilter->SetCriteria( criteria );
3900 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3901 newFilter->UnRegister();
3903 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3904 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3905 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3907 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3909 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3912 if ( !badEntries.empty() )
3915 } // treat a group on filter
3917 append( theNewGroups, newGroup );
3919 // fill old2newGroupMap
3920 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3921 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3922 if ( !srcSO->_is_nil() )
3924 CORBA::String_var srcID, newID("");
3925 srcID = srcSO->GetID();
3926 if ( !newSO->_is_nil() )
3927 newID = newSO->GetID();
3928 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3929 std::string( newID.in() )));
3932 if ( newGroup->_is_nil() )
3937 newMeshDS->CompactMesh();
3940 if ( !theMeshName || !theMeshName[0] )
3942 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3943 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3944 CORBA::String_var oldName = soOld->GetName();
3945 SetName( soNew, oldName.in(), "Mesh" );
3947 // mark invalid objects
3948 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3950 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3951 highLightInvalid( invalidSObjects[i].in(), true );
3954 << theNewMesh << ", "
3955 << theNewGroups << ", "
3956 << *theNewSubmeshes.ptr() << ", "
3957 << *theNewHypotheses.ptr() << ", "
3958 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3959 << theSourceMesh << ", "
3960 << theNewGeometry << ", "
3961 << "'" << theMeshName << "', "
3962 << theToCopyGroups << ", "
3963 << theToReuseHypotheses << ", "
3964 << theToCopyElements << " )";
3966 SMESH_CATCH( SMESH::throwCorbaException );
3971 //================================================================================
3973 * \brief Get version of MED format being used.
3975 //================================================================================
3977 char* SMESH_Gen_i::GetMEDFileVersion()
3979 MED::TInt majeur, mineur, release;
3980 majeur = mineur = release = 0;
3981 MED::GetVersionRelease(majeur, mineur, release);
3982 std::ostringstream version;
3983 version << majeur << "." << mineur << "." << release;
3984 return CORBA::string_dup( version.str().c_str() );
3987 //================================================================================
3989 * SMESH_Gen_i::GetMEDVersion
3991 * Get MED version of the file by its name
3993 //================================================================================
3994 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
3996 std::string version = MED::GetMEDVersion( theFileName );
3997 return CORBA::string_dup( version.c_str() );
4000 //================================================================================
4002 * SMESH_Gen_i::CheckCompatibility
4004 * Check compatibility of file with MED format being used, read only.
4006 //================================================================================
4007 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4009 return MED::CheckCompatibility( theFileName );
4012 //================================================================================
4014 * SMESH_Gen_i::CheckWriteCompatibility
4016 * Check compatibility of file with MED format being used, for append on write.
4018 //================================================================================
4019 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4021 return MED::CheckCompatibility( theFileName, true );
4024 //================================================================================
4026 * SMESH_Gen_i::GetMeshNames
4028 * Get names of meshes defined in file with the specified name
4030 //================================================================================
4031 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4033 //MESSAGE("GetMeshNames " << theFileName);
4034 SMESH::string_array_var aResult = new SMESH::string_array();
4035 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4037 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4038 //MESSAGE("---" << aNbMeshes);
4040 aResult->length( aNbMeshes );
4041 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4042 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4043 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4046 return aResult._retn();
4049 //=============================================================================
4053 * Save SMESH module's data
4055 //=============================================================================
4056 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4061 Kernel_Utils::Localizer loc;
4063 if (!myStudyContext)
4066 // Store study contents as a set of python commands
4069 SALOMEDS::Study_var aStudy = getStudyServant();
4071 // Declare a byte stream
4072 SALOMEDS::TMPFile_var aStreamFile;
4074 // Obtain a temporary dir
4075 TCollection_AsciiString tmpDir =
4076 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4078 // Create a sequence of files processed
4079 SALOMEDS_Tool::ListOfFiles aFileSeq;
4080 aFileSeq.reserve( NUM_TMP_FILES );
4082 TCollection_AsciiString aStudyName( "" );
4084 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4086 // Set names of temporary files
4087 TCollection_AsciiString filename =
4088 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4089 TCollection_AsciiString meshfile =
4090 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4091 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4092 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4093 filename = tmpDir + filename;
4094 meshfile = tmpDir + meshfile;
4097 HDFdataset* aDataset;
4098 HDFgroup* aTopGroup;
4100 HDFgroup* aSubGroup;
4101 HDFgroup* aSubSubGroup;
4102 hdf_size aSize[ 1 ];
4105 //Remove the files if they exist: BugID: 11225
4106 #ifndef WIN32 /* unix functionality */
4107 TCollection_AsciiString cmd("rm -f \"");
4109 TCollection_AsciiString cmd("del /F \"");
4119 system(cmd.ToCString());
4121 // MED writer to be used by storage process
4122 DriverMED_W_SMESHDS_Mesh myWriter;
4123 myWriter.SetFile( meshfile.ToCString() );
4126 // SetStoreName() to groups before storing hypotheses to let them refer to
4127 // groups using "store name", which is "Group <group_persistent_id>"
4129 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4130 for ( ; itBig->More(); itBig->Next() ) {
4131 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4132 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4133 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4134 if ( !CORBA::is_nil( anObject ) ) {
4135 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4136 if ( !myMesh->_is_nil() ) {
4137 myMesh->Load(); // load from study file if not yet done
4138 TPythonDump pd; // not to dump GetGroups()
4139 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4140 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4142 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4145 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4146 int anId = myStudyContext->findId( string( objStr.in() ) );
4148 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4149 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4150 aGrpBaseDS->SetStoreName( grpName );
4160 // ---> create HDF file
4161 aFile = new HDFfile( (char*) filename.ToCString() );
4162 aFile->CreateOnDisk();
4164 // --> iterator for top-level objects
4165 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4166 for ( ; itBig->More(); itBig->Next() ) {
4167 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4169 // --> hypotheses root branch (only one for the study)
4170 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4171 // create hypotheses root HDF group
4172 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4173 aTopGroup->CreateOnDisk();
4175 // iterator for all hypotheses
4176 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4177 for ( ; it->More(); it->Next() ) {
4178 SALOMEDS::SObject_wrap mySObject = it->Value();
4179 CORBA::Object_var anObject = SObjectToObject( mySObject );
4180 if ( !CORBA::is_nil( anObject ) ) {
4181 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4182 if ( !myHyp->_is_nil() ) {
4183 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4185 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4186 std::string hypname = hn.in();
4187 std::string libname = ln.in();
4189 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4190 // WIN32 and ".so" for X-system) must be deleted
4191 int libname_len = libname.length();
4193 if( libname_len > 4 )
4194 libname.resize( libname_len - 4 );
4196 // PAL17753 (Regression: missing hypothesis in restored study)
4197 // "lib" also should be removed from the beginning
4198 //if( libname_len > 3 )
4199 //libname.resize( libname_len - 3 );
4200 if( libname_len > 6 )
4201 libname = libname.substr( 3, libname_len - 3 - 3 );
4203 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4204 CORBA::String_var hypdata = myImpl->SaveTo();
4205 int id = myStudyContext->findId( string( objStr.in() ));
4207 // for each hypothesis create HDF group basing on its id
4208 char hypGrpName[30];
4209 sprintf( hypGrpName, "Hypothesis %d", id );
4210 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4211 aGroup->CreateOnDisk();
4212 // --> type name of hypothesis
4213 aSize[ 0 ] = hypname.length() + 1;
4214 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4215 aDataset->CreateOnDisk();
4216 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4217 aDataset->CloseOnDisk();
4218 // --> server plugin library name of hypothesis
4219 aSize[ 0 ] = libname.length() + 1;
4220 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4221 aDataset->CreateOnDisk();
4222 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4223 aDataset->CloseOnDisk();
4224 // --> persistent data of hypothesis
4225 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4226 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4227 aDataset->CreateOnDisk();
4228 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4229 aDataset->CloseOnDisk();
4230 // close hypothesis HDF group
4231 aGroup->CloseOnDisk();
4236 // close hypotheses root HDF group
4237 aTopGroup->CloseOnDisk();
4239 // --> algorithms root branch (only one for the study)
4240 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4241 // create algorithms root HDF group
4242 aTopGroup = new HDFgroup( "Algorithms", aFile );
4243 aTopGroup->CreateOnDisk();
4245 // iterator for all algorithms
4246 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4247 for ( ; it->More(); it->Next() ) {
4248 SALOMEDS::SObject_wrap mySObject = it->Value();
4249 CORBA::Object_var anObject = SObjectToObject( mySObject );
4250 if ( !CORBA::is_nil( anObject ) ) {
4251 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4252 if ( !myHyp->_is_nil() ) {
4253 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4255 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4256 std::string hypname = hn.in();
4257 std::string libname = ln.in();
4259 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4260 // WIN32 and ".so" for X-system) must be deleted
4261 int libname_len = libname.length();
4263 if( libname_len > 4 )
4264 libname.resize( libname_len - 4 );
4266 // PAL17753 (Regression: missing hypothesis in restored study)
4267 // "lib" also should be removed from the beginning
4268 //if( libname_len > 3 )
4269 //libname.resize( libname_len - 3 );
4270 if( libname_len > 6 )
4271 libname = libname.substr( 3, libname_len - 3 - 3 );
4273 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4274 CORBA::String_var hypdata = myImpl->SaveTo();
4275 int id = myStudyContext->findId( string( objStr.in() ) );
4277 // for each algorithm create HDF group basing on its id
4278 char hypGrpName[30];
4279 sprintf( hypGrpName, "Algorithm %d", id );
4280 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4281 aGroup->CreateOnDisk();
4282 // --> type name of algorithm
4283 aSize[0] = hypname.length() + 1;
4284 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4285 aDataset->CreateOnDisk();
4286 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4287 aDataset->CloseOnDisk();
4288 // --> server plugin library name of hypothesis
4289 aSize[0] = libname.length() + 1;
4290 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4291 aDataset->CreateOnDisk();
4292 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4293 aDataset->CloseOnDisk();
4294 // --> persistent data of algorithm
4295 aSize[0] = strlen( hypdata.in() ) + 1;
4296 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4297 aDataset->CreateOnDisk();
4298 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4299 aDataset->CloseOnDisk();
4300 // close algorithm HDF group
4301 aGroup->CloseOnDisk();
4306 // close algorithms root HDF group
4307 aTopGroup->CloseOnDisk();
4309 // --> mesh objects roots branches
4310 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4311 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4312 if ( !CORBA::is_nil( anObject ) ) {
4313 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4314 if ( !myMesh->_is_nil() ) {
4315 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4317 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4318 int id = myStudyContext->findId( string( objStr.in() ) );
4319 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4320 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4321 bool hasShape = myLocMesh.HasShapeToMesh();
4323 // for each mesh open the HDF group basing on its id
4324 char meshGrpName[ 30 ];
4325 sprintf( meshGrpName, "Mesh %d", id );
4326 aTopGroup = new HDFgroup( meshGrpName, aFile );
4327 aTopGroup->CreateOnDisk();
4329 // --> put dataset to hdf file which is a flag that mesh has data
4330 string strHasData = "0";
4331 // check if the mesh is not empty
4332 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4333 // write mesh data to med file
4334 myWriter.SetMesh( mySMESHDSMesh );
4335 myWriter.SetMeshId( id );
4338 aSize[ 0 ] = strHasData.length() + 1;
4339 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4340 aDataset->CreateOnDisk();
4341 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4342 aDataset->CloseOnDisk();
4345 // for each mesh open the HDF group basing on its auto color parameter
4346 char meshAutoColorName[ 30 ];
4347 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4349 anAutoColor[0] = myImpl->GetAutoColor();
4351 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4352 aDataset->CreateOnDisk();
4353 aDataset->WriteOnDisk( anAutoColor );
4354 aDataset->CloseOnDisk();
4356 // issue 0020693. Store _isModified flag
4357 int isModified = myLocMesh.GetIsModified();
4359 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4360 aDataset->CreateOnDisk();
4361 aDataset->WriteOnDisk( &isModified );
4362 aDataset->CloseOnDisk();
4364 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4365 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4367 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4368 aDataset->CreateOnDisk();
4369 aDataset->WriteOnDisk( &meshPersistentId );
4370 aDataset->CloseOnDisk();
4372 // write reference on a shape if exists
4373 SALOMEDS::SObject_wrap myRef;
4374 bool shapeRefFound = false;
4375 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4377 SALOMEDS::SObject_wrap myShape;
4378 bool ok = myRef->ReferencedObject( myShape.inout() );
4380 CORBA::Object_var shapeObj = myShape->GetObject();
4381 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4382 CORBA::String_var myRefOnObject = myShape->GetID();
4383 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4384 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4385 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4386 aDataset->CreateOnDisk();
4387 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4388 aDataset->CloseOnDisk();
4394 std::string info = myImpl->FileInfoToString();
4395 if ( !info.empty() )
4397 aSize[ 0 ] = info.size();
4398 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4399 aDataset->CreateOnDisk();
4400 aDataset->WriteOnDisk( (char*) info.data() );
4401 aDataset->CloseOnDisk();
4404 // write applied hypotheses if exist
4405 SALOMEDS::SObject_wrap myHypBranch;
4406 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4407 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4408 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4410 if ( found && (shapeRefFound || !hasShape) ) {
4411 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4412 aGroup->CreateOnDisk();
4414 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4416 for ( ; it->More(); it->Next() ) {
4417 SALOMEDS::SObject_wrap mySObject = it->Value();
4418 SALOMEDS::SObject_wrap myRefOnHyp;
4419 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4421 // san - it is impossible to recover applied hypotheses
4422 // using their entries within Load() method,
4423 // for there are no AttributeIORs in the study when Load() is working.
4424 // Hence, it is better to store persistent IDs of hypotheses as references to them
4426 //string myRefOnObject = myRefOnHyp->GetID();
4427 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4428 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4429 int id = myStudyContext->findId( string( objStr.in() ) );
4430 //if ( myRefOnObject.length() > 0 ) {
4431 //aSize[ 0 ] = myRefOnObject.length() + 1;
4432 char hypName[ 30 ], hypId[ 30 ];
4433 sprintf( hypName, "Hyp %d", ++hypNb );
4434 sprintf( hypId, "%d", id );
4435 aSize[ 0 ] = strlen( hypId ) + 1;
4436 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4437 aDataset->CreateOnDisk();
4438 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4439 aDataset->WriteOnDisk( hypId );
4440 aDataset->CloseOnDisk();
4444 aGroup->CloseOnDisk();
4447 // write applied algorithms if exist
4448 SALOMEDS::SObject_wrap myAlgoBranch;
4449 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4450 myAlgoBranch.inout() );
4451 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4452 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4454 if ( found && (shapeRefFound || !hasShape)) {
4455 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4456 aGroup->CreateOnDisk();
4458 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4460 for ( ; it->More(); it->Next() ) {
4461 SALOMEDS::SObject_wrap mySObject = it->Value();
4462 SALOMEDS::SObject_wrap myRefOnAlgo;
4463 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4465 // san - it is impossible to recover applied algorithms
4466 // using their entries within Load() method,
4467 // for there are no AttributeIORs in the study when Load() is working.
4468 // Hence, it is better to store persistent IDs of algorithms as references to them
4470 //string myRefOnObject = myRefOnAlgo->GetID();
4471 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4472 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4473 int id = myStudyContext->findId( string( objStr.in() ) );
4474 //if ( myRefOnObject.length() > 0 ) {
4475 //aSize[ 0 ] = myRefOnObject.length() + 1;
4476 char algoName[ 30 ], algoId[ 30 ];
4477 sprintf( algoName, "Algo %d", ++algoNb );
4478 sprintf( algoId, "%d", id );
4479 aSize[ 0 ] = strlen( algoId ) + 1;
4480 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4481 aDataset->CreateOnDisk();
4482 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4483 aDataset->WriteOnDisk( algoId );
4484 aDataset->CloseOnDisk();
4488 aGroup->CloseOnDisk();
4491 // --> submesh objects sub-branches
4493 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4494 SALOMEDS::SObject_wrap mySubmeshBranch;
4495 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4497 if ( found ) // check if there is shape reference in submeshes
4499 bool hasShapeRef = false;
4500 SALOMEDS::ChildIterator_wrap itSM =
4501 aStudy->NewChildIterator( mySubmeshBranch );
4502 for ( ; itSM->More(); itSM->Next() ) {
4503 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4504 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4505 mySubRef->ReferencedObject( myShape.inout() );
4506 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4509 { // remove one submesh
4510 if ( shapeRefFound )
4511 { // unassign hypothesis
4512 SMESH::SMESH_subMesh_var mySubMesh =
4513 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4514 if ( !mySubMesh->_is_nil() ) {
4515 int shapeID = mySubMesh->GetId();
4516 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4517 const list<const SMESHDS_Hypothesis*>& hypList =
4518 mySMESHDSMesh->GetHypothesis( S );
4519 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4520 while ( hyp != hypList.end() ) {
4521 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4522 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4526 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4528 } // loop on submeshes of a type
4529 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4530 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4533 } // end check if there is shape reference in submeshes
4535 char name_meshgroup[ 30 ];
4536 if ( i == GetSubMeshOnVertexTag() )
4537 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4538 else if ( i == GetSubMeshOnEdgeTag() )
4539 strcpy( name_meshgroup, "SubMeshes On Edge" );
4540 else if ( i == GetSubMeshOnWireTag() )
4541 strcpy( name_meshgroup, "SubMeshes On Wire" );
4542 else if ( i == GetSubMeshOnFaceTag() )
4543 strcpy( name_meshgroup, "SubMeshes On Face" );
4544 else if ( i == GetSubMeshOnShellTag() )
4545 strcpy( name_meshgroup, "SubMeshes On Shell" );
4546 else if ( i == GetSubMeshOnSolidTag() )
4547 strcpy( name_meshgroup, "SubMeshes On Solid" );
4548 else if ( i == GetSubMeshOnCompoundTag() )
4549 strcpy( name_meshgroup, "SubMeshes On Compound" );
4551 // for each type of submeshes create container HDF group
4552 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4553 aGroup->CreateOnDisk();
4555 // iterator for all submeshes of given type
4556 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4557 for ( ; itSM->More(); itSM->Next() ) {
4558 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4559 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4560 if ( !CORBA::is_nil( anSubObject ))
4562 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4563 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4564 int subid = myStudyContext->findId( string( objStr.in() ) );
4566 // for each mesh open the HDF group basing on its id
4567 char submeshGrpName[ 30 ];
4568 sprintf( submeshGrpName, "SubMesh %d", subid );
4569 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4570 aSubGroup->CreateOnDisk();
4572 // write reference on a shape, already checked if it exists
4573 SALOMEDS::SObject_wrap mySubRef, myShape;
4574 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4575 mySubRef->ReferencedObject( myShape.inout() );
4576 string myRefOnObject = myShape->GetID();
4577 if ( myRefOnObject.length() > 0 ) {
4578 aSize[ 0 ] = myRefOnObject.length() + 1;
4579 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4580 aDataset->CreateOnDisk();
4581 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4582 aDataset->CloseOnDisk();
4585 // write applied hypotheses if exist
4586 SALOMEDS::SObject_wrap mySubHypBranch;
4587 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4588 mySubHypBranch.inout() );
4590 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4591 aSubSubGroup->CreateOnDisk();
4593 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4595 for ( ; it->More(); it->Next() ) {
4596 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4597 SALOMEDS::SObject_wrap myRefOnHyp;
4598 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4600 //string myRefOnObject = myRefOnHyp->GetID();
4601 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4602 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4603 int id = myStudyContext->findId( string( objStr.in() ) );
4604 //if ( myRefOnObject.length() > 0 ) {
4605 //aSize[ 0 ] = myRefOnObject.length() + 1;
4606 char hypName[ 30 ], hypId[ 30 ];
4607 sprintf( hypName, "Hyp %d", ++hypNb );
4608 sprintf( hypId, "%d", id );
4609 aSize[ 0 ] = strlen( hypId ) + 1;
4610 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4611 aDataset->CreateOnDisk();
4612 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4613 aDataset->WriteOnDisk( hypId );
4614 aDataset->CloseOnDisk();
4618 aSubSubGroup->CloseOnDisk();
4621 // write applied algorithms if exist
4622 SALOMEDS::SObject_wrap mySubAlgoBranch;
4623 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4624 mySubAlgoBranch.inout() );
4626 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4627 aSubSubGroup->CreateOnDisk();
4629 SALOMEDS::ChildIterator_wrap it =
4630 aStudy->NewChildIterator( mySubAlgoBranch );
4632 for ( ; it->More(); it->Next() ) {
4633 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4634 SALOMEDS::SObject_wrap myRefOnAlgo;
4635 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4637 //string myRefOnObject = myRefOnAlgo->GetID();
4638 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4639 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4640 int id = myStudyContext->findId( string( objStr.in() ) );
4641 //if ( myRefOnObject.length() > 0 ) {
4642 //aSize[ 0 ] = myRefOnObject.length() + 1;
4643 char algoName[ 30 ], algoId[ 30 ];
4644 sprintf( algoName, "Algo %d", ++algoNb );
4645 sprintf( algoId, "%d", id );
4646 aSize[ 0 ] = strlen( algoId ) + 1;
4647 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4648 aDataset->CreateOnDisk();
4649 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4650 aDataset->WriteOnDisk( algoId );
4651 aDataset->CloseOnDisk();
4655 aSubSubGroup->CloseOnDisk();
4657 // close submesh HDF group
4658 aSubGroup->CloseOnDisk();
4661 // close container of submeshes by type HDF group
4662 aGroup->CloseOnDisk();
4665 // All sub-meshes will be stored in MED file
4666 // .. will NOT (PAL 12992)
4667 //if ( shapeRefFound )
4668 //myWriter.AddAllSubMeshes();
4670 // store submesh order if any
4671 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4672 if ( theOrderIds.size() ) {
4673 char order_list[ 30 ];
4674 strcpy( order_list, "Mesh Order" );
4675 // count number of submesh ids
4677 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4678 for ( ; idIt != theOrderIds.end(); idIt++ )
4679 nbIDs += (*idIt).size();
4680 // number of values = number of IDs +
4681 // number of lists (for separators) - 1
4682 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4683 idIt = theOrderIds.begin();
4684 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4685 const TListOfInt& idList = *idIt;
4686 if (idIt != theOrderIds.begin()) // not first list
4687 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4688 // dump submesh ids from current list
4689 TListOfInt::const_iterator id_smId = idList.begin();
4690 for( ; id_smId != idList.end(); id_smId++ )
4691 smIDs[ i++ ] = *id_smId;
4694 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4696 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4697 aDataset->CreateOnDisk();
4698 aDataset->WriteOnDisk( smIDs );
4699 aDataset->CloseOnDisk();
4704 // groups root sub-branch
4705 SALOMEDS::SObject_wrap myGroupsBranch;
4706 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4707 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4709 char name_group[ 30 ];
4710 if ( i == GetNodeGroupsTag() )
4711 strcpy( name_group, "Groups of Nodes" );
4712 else if ( i == GetEdgeGroupsTag() )
4713 strcpy( name_group, "Groups of Edges" );
4714 else if ( i == GetFaceGroupsTag() )
4715 strcpy( name_group, "Groups of Faces" );
4716 else if ( i == GetVolumeGroupsTag() )
4717 strcpy( name_group, "Groups of Volumes" );
4718 else if ( i == Get0DElementsGroupsTag() )
4719 strcpy( name_group, "Groups of 0D Elements" );
4720 else if ( i == GetBallElementsGroupsTag() )
4721 strcpy( name_group, "Groups of Balls" );
4723 aGroup = new HDFgroup( name_group, aTopGroup );
4724 aGroup->CreateOnDisk();
4726 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4727 for ( ; it->More(); it->Next() ) {
4728 SALOMEDS::SObject_wrap mySObject = it->Value();
4729 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4730 if ( !CORBA::is_nil( aSubObject ) ) {
4731 SMESH_GroupBase_i* myGroupImpl =
4732 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4735 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4739 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4740 int anId = myStudyContext->findId( string( objStr.in() ) );
4742 // For each group, create a dataset named "Group <group_persistent_id>"
4743 // and store the group's user name into it
4744 const char* grpName = aGrpBaseDS->GetStoreName();
4745 CORBA::String_var aUserName = myGroupImpl->GetName();
4746 aSize[ 0 ] = strlen( aUserName ) + 1;
4748 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4749 aDataset->CreateOnDisk();
4750 aDataset->WriteOnDisk( aUserName );
4751 aDataset->CloseOnDisk();
4754 // For each group, create a dataset named "Group <group_persistent_id> Color"
4755 // and store the group's color into it
4756 char grpColorName[ 30 ];
4757 sprintf( grpColorName, "ColorGroup %d", anId );
4758 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4760 anRGB[ 0 ] = aColor.R;
4761 anRGB[ 1 ] = aColor.G;
4762 anRGB[ 2 ] = aColor.B;
4764 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4765 aDataset->CreateOnDisk();
4766 aDataset->WriteOnDisk( anRGB );
4767 aDataset->CloseOnDisk();
4769 // Pass SMESHDS_Group to MED writer
4770 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4772 myWriter.AddGroup( aGrpDS );
4774 // write reference on a shape if exists
4775 SMESHDS_GroupOnGeom* aGeomGrp =
4776 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4778 SALOMEDS::SObject_wrap mySubRef, myShape;
4779 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4780 mySubRef->ReferencedObject( myShape.inout() ) &&
4781 !CORBA::is_nil( myShape->GetObject() ))
4783 CORBA::String_var myRefOnObject = myShape->GetID();
4784 if ( myRefOnObject.in()[0] ) {
4785 char aRefName[ 30 ];
4786 sprintf( aRefName, "Ref on shape %d", anId);
4787 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4788 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4789 aDataset->CreateOnDisk();
4790 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4791 aDataset->CloseOnDisk();
4794 else // shape ref is invalid:
4796 // save a group on geometry as ordinary group
4797 myWriter.AddGroup( aGeomGrp );
4800 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4801 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4803 std::string str = aFilterGrp_i->FilterToString();
4804 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4805 aSize[ 0 ] = str.length() + 1;
4806 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4807 aDataset->CreateOnDisk();
4808 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4809 aDataset->CloseOnDisk();
4813 aGroup->CloseOnDisk();
4817 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4819 // Flush current mesh information into MED file
4822 // save info on nb of elements
4823 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4825 // maybe a shape was deleted in the study
4826 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4827 TopoDS_Shape nullShape;
4828 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4831 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4836 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4837 aGroup->CreateOnDisk();
4839 // each element belongs to one or none submesh,
4840 // so for each node/element, we store a submesh ID
4842 // Store submesh IDs
4843 for ( int isNode = 0; isNode < 2; ++isNode )
4845 SMDS_ElemIteratorPtr eIt =
4846 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4847 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4850 std::vector<int> smIDs; smIDs.reserve( nbElems );
4851 while ( eIt->more() )
4852 if ( const SMDS_MeshElement* e = eIt->next())
4853 smIDs.push_back( e->getshapeId() );
4855 aSize[ 0 ] = nbElems;
4856 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4857 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4858 aDataset->CreateOnDisk();
4859 aDataset->WriteOnDisk( & smIDs[0] );
4860 aDataset->CloseOnDisk();
4863 aGroup->CloseOnDisk();
4865 // Store node positions on sub-shapes (SMDS_Position):
4866 // ----------------------------------------------------
4868 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4869 aGroup->CreateOnDisk();
4871 // in aGroup, create 5 datasets to contain:
4872 // "Nodes on Edges" - ID of node on edge
4873 // "Edge positions" - U parameter on node on edge
4874 // "Nodes on Faces" - ID of node on face
4875 // "Face U positions" - U parameter of node on face
4876 // "Face V positions" - V parameter of node on face
4878 // Find out nb of nodes on edges and faces
4879 // Collect corresponding sub-meshes
4880 int nbEdgeNodes = 0, nbFaceNodes = 0;
4881 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4882 // loop on SMESHDS_SubMesh'es
4883 while ( smIt->more() )
4885 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4886 if ( aSubMesh->IsComplexSubmesh() )
4887 continue; // submesh containing other submeshs
4888 int nbNodes = aSubMesh->NbNodes();
4889 if ( nbNodes == 0 ) continue;
4891 int aShapeID = aSubMesh->GetID();
4892 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4894 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4895 // write only SMDS_FacePosition and SMDS_EdgePosition
4896 switch ( aShapeType ) {
4898 nbFaceNodes += nbNodes;
4899 aFaceSM.push_back( aSubMesh );
4902 nbEdgeNodes += nbNodes;
4903 aEdgeSM.push_back( aSubMesh );
4909 // Treat positions on edges or faces
4910 for ( int onFace = 0; onFace < 2; onFace++ )
4912 // Create arrays to store in datasets
4913 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4914 if (!nbNodes) continue;
4915 int* aNodeIDs = new int [ nbNodes ];
4916 double* aUPos = new double [ nbNodes ];
4917 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4920 // loop on sub-meshes
4921 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4922 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4923 for ( ; itSM != pListSM->end(); itSM++ )
4925 SMESHDS_SubMesh* aSubMesh = (*itSM);
4927 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4928 // loop on nodes in aSubMesh
4929 while ( itNode->more() )
4932 const SMDS_MeshNode* node = itNode->next();
4933 aNodeIDs [ iNode ] = node->GetID();
4936 const SMDS_PositionPtr pos = node->GetPosition();
4937 if ( onFace ) { // on FACE
4938 SMDS_FacePositionPtr fPos = pos;
4940 aUPos[ iNode ] = fPos->GetUParameter();
4941 aVPos[ iNode ] = fPos->GetVParameter();
4948 SMDS_EdgePositionPtr ePos = pos;
4950 aUPos[ iNode ] = ePos->GetUParameter();
4956 } // loop on nodes in aSubMesh
4957 } // loop on sub-meshes
4962 aSize[ 0 ] = nbNodes;
4964 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4965 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4966 aDataset->CreateOnDisk();
4967 aDataset->WriteOnDisk( aNodeIDs );
4968 aDataset->CloseOnDisk();
4971 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4972 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4973 aDataset->CreateOnDisk();
4974 aDataset->WriteOnDisk( aUPos );
4975 aDataset->CloseOnDisk();
4978 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4979 aDataset->CreateOnDisk();
4980 aDataset->WriteOnDisk( aVPos );
4981 aDataset->CloseOnDisk();
4986 if ( aVPos ) delete [] aVPos;
4988 } // treat positions on edges or faces
4990 // close "Node Positions" group
4991 aGroup->CloseOnDisk();
4993 } // if ( there are submeshes in SMESHDS_Mesh )
4996 // close mesh HDF group
4997 aTopGroup->CloseOnDisk();
5005 aFile->CloseOnDisk();
5008 // Convert temporary files to stream
5009 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5011 // Remove temporary files and directory
5013 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5015 return aStreamFile._retn();
5018 //=============================================================================
5020 * SMESH_Gen_i::SaveASCII
5022 * Save SMESH module's data in ASCII format
5024 //=============================================================================
5026 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5028 bool isMultiFile ) {
5029 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5030 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5031 return aStreamFile._retn();
5033 //after usual saving needs to encipher binary to text string
5034 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5035 int size = aStreamFile.in().length();
5036 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5037 for ( int i = 0; i < size; i++ )
5038 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5040 buffer[size * 3] = '\0';
5042 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5044 return anAsciiStreamFile._retn();
5047 //=============================================================================
5051 * Load SMESH module's data
5053 //=============================================================================
5055 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5056 const SALOMEDS::TMPFile& theStream,
5060 UpdateStudy(); // load geom data
5061 Kernel_Utils::Localizer loc;
5063 SALOMEDS::Study_var aStudy = getStudyServant();
5065 // Get temporary files location
5066 TCollection_AsciiString tmpDir =
5067 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5069 // Convert the stream into sequence of files to process
5070 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5073 TCollection_AsciiString aStudyName( "" );
5074 if ( isMultiFile ) {
5075 CORBA::WString_var url = aStudy->URL();
5076 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5078 // Set names of temporary files
5079 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5080 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5084 HDFdataset* aDataset;
5085 HDFgroup* aTopGroup;
5087 HDFgroup* aSubGroup;
5088 HDFgroup* aSubSubGroup;
5091 // ---> open HDF file
5092 aFile = new HDFfile( (char*) filename.ToCString() );
5094 aFile->OpenOnDisk( HDF_RDONLY );
5096 catch ( HDFexception ) {
5097 INFOS( "Load(): " << filename << " not found!" );
5101 TPythonDump pd; // prevent dump during loading
5103 // DriverMED_R_SMESHDS_Mesh myReader;
5104 // myReader.SetFile( meshfile.ToCString() );
5106 // For PAL13473 ("Repetitive mesh") implementation.
5107 // New dependencies between SMESH objects are established:
5108 // now hypotheses can refer to meshes, shapes and other hypotheses.
5109 // To keep data consistent, the following order of data restoration
5111 // 1. Create hypotheses
5112 // 2. Create all meshes
5113 // 3. Load hypotheses' data
5116 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5117 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5118 list< SMESH::Filter_var > filters;
5120 // get total number of top-level groups
5121 int aNbGroups = aFile->nInternalObjects();
5122 if ( aNbGroups > 0 ) {
5123 // --> in first turn we should read&create hypotheses
5124 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5125 // open hypotheses root HDF group
5126 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5127 aTopGroup->OpenOnDisk();
5129 // get number of hypotheses
5130 int aNbObjects = aTopGroup->nInternalObjects();
5131 for ( int j = 0; j < aNbObjects; j++ ) {
5132 // try to identify hypothesis
5133 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5134 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5136 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5137 // open hypothesis group
5138 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5139 aGroup->OpenOnDisk();
5141 // --> get hypothesis id
5142 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5147 // get number of datasets
5148 int aNbSubObjects = aGroup->nInternalObjects();
5149 for ( int k = 0; k < aNbSubObjects; k++ ) {
5151 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5152 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5153 // --> get hypothesis name
5154 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5155 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5156 aDataset->OpenOnDisk();
5157 size = aDataset->GetSize();
5158 char* hypname_str = new char[ size ];
5159 aDataset->ReadFromDisk( hypname_str );
5160 hypname = string( hypname_str );
5161 delete [] hypname_str;
5162 aDataset->CloseOnDisk();
5164 // --> get hypothesis plugin library name
5165 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5166 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5167 aDataset->OpenOnDisk();
5168 size = aDataset->GetSize();
5169 char* libname_str = new char[ size ];
5170 aDataset->ReadFromDisk( libname_str );
5171 if(MYDEBUG) SCRUTE( libname_str );
5172 libname = string( libname_str );
5173 delete [] libname_str;
5174 aDataset->CloseOnDisk();
5176 // --> get hypothesis data
5177 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5178 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5179 aDataset->OpenOnDisk();
5180 size = aDataset->GetSize();
5181 char* hypdata_str = new char[ size ];
5182 aDataset->ReadFromDisk( hypdata_str );
5183 hypdata = string( hypdata_str );
5184 delete [] hypdata_str;
5185 aDataset->CloseOnDisk();
5188 // close hypothesis HDF group
5189 aGroup->CloseOnDisk();
5191 // --> restore hypothesis from data
5192 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5193 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5194 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5195 SMESH::SMESH_Hypothesis_var myHyp;
5197 try { // protect persistence mechanism against exceptions
5198 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5201 INFOS( "Exception during hypothesis creation" );
5204 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5206 // myImpl->LoadFrom( hypdata.c_str() );
5207 hypDataList.push_back( make_pair( myImpl, hypdata ));
5208 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5209 int newId = myStudyContext->findId( iorString.in() );
5210 myStudyContext->mapOldToNew( id, newId );
5213 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5217 // close hypotheses root HDF group
5218 aTopGroup->CloseOnDisk();
5222 // --> then we should read&create algorithms
5223 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5224 // open algorithms root HDF group
5225 aTopGroup = new HDFgroup( "Algorithms", aFile );
5226 aTopGroup->OpenOnDisk();
5228 // get number of algorithms
5229 int aNbObjects = aTopGroup->nInternalObjects();
5230 for ( int j = 0; j < aNbObjects; j++ ) {
5231 // try to identify algorithm
5232 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5233 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5235 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5236 // open algorithm group
5237 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5238 aGroup->OpenOnDisk();
5240 // --> get algorithm id
5241 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5246 // get number of datasets
5247 int aNbSubObjects = aGroup->nInternalObjects();
5248 for ( int k = 0; k < aNbSubObjects; k++ ) {
5250 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5251 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5252 // --> get algorithm name
5253 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5254 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5255 aDataset->OpenOnDisk();
5256 size = aDataset->GetSize();
5257 char* hypname_str = new char[ size ];
5258 aDataset->ReadFromDisk( hypname_str );
5259 hypname = string( hypname_str );
5260 delete [] hypname_str;
5261 aDataset->CloseOnDisk();
5263 // --> get algorithm plugin library name
5264 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5265 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5266 aDataset->OpenOnDisk();
5267 size = aDataset->GetSize();
5268 char* libname_str = new char[ size ];
5269 aDataset->ReadFromDisk( libname_str );
5270 if(MYDEBUG) SCRUTE( libname_str );
5271 libname = string( libname_str );
5272 delete [] libname_str;
5273 aDataset->CloseOnDisk();
5275 // --> get algorithm data
5276 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5277 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5278 aDataset->OpenOnDisk();
5279 size = aDataset->GetSize();
5280 char* hypdata_str = new char[ size ];
5281 aDataset->ReadFromDisk( hypdata_str );
5282 if(MYDEBUG) SCRUTE( hypdata_str );
5283 hypdata = string( hypdata_str );
5284 delete [] hypdata_str;
5285 aDataset->CloseOnDisk();
5288 // close algorithm HDF group
5289 aGroup->CloseOnDisk();
5291 // --> restore algorithm from data
5292 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5293 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5294 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5295 SMESH::SMESH_Hypothesis_var myHyp;
5297 try { // protect persistence mechanism against exceptions
5298 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5300 catch( SALOME::SALOME_Exception& ex )
5302 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5305 INFOS( "Exception during hypothesis creation" );
5308 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5310 //myImpl->LoadFrom( hypdata.c_str() );
5311 hypDataList.push_back( make_pair( myImpl, hypdata ));
5312 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5313 int newId = myStudyContext->findId( iorString.in() );
5314 myStudyContext->mapOldToNew( id, newId );
5317 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5321 // close algorithms root HDF group
5322 aTopGroup->CloseOnDisk();
5326 // --> the rest groups should be meshes
5327 for ( int i = 0; i < aNbGroups; i++ ) {
5328 // identify next group
5329 char meshName[ HDF_NAME_MAX_LEN+1 ];
5330 aFile->InternalObjectIndentify( i, meshName );
5332 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5334 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5338 // open mesh HDF group
5339 aTopGroup = new HDFgroup( meshName, aFile );
5340 aTopGroup->OpenOnDisk();
5342 // get number of child HDF objects
5343 int aNbObjects = aTopGroup->nInternalObjects();
5344 if ( aNbObjects > 0 ) {
5346 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5347 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5348 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5349 if ( !myNewMeshImpl )
5351 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5353 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5354 int newId = myStudyContext->findId( iorString.in() );
5355 myStudyContext->mapOldToNew( id, newId );
5358 // try to read and set auto color flag
5359 char aMeshAutoColorName[ 30 ];
5360 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5361 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5363 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5364 aDataset->OpenOnDisk();
5365 size = aDataset->GetSize();
5366 int* anAutoColor = new int[ size ];
5367 aDataset->ReadFromDisk( anAutoColor );
5368 aDataset->CloseOnDisk();
5369 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5370 delete [] anAutoColor;
5373 // try to read and set reference to shape
5374 GEOM::GEOM_Object_var aShapeObject;
5375 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5376 // load mesh "Ref on shape" - it's an entry to SObject
5377 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5378 aDataset->OpenOnDisk();
5379 size = aDataset->GetSize();
5380 char* refFromFile = new char[ size ];
5381 aDataset->ReadFromDisk( refFromFile );
5382 aDataset->CloseOnDisk();
5383 if ( strlen( refFromFile ) > 0 ) {
5384 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5385 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5386 if ( !CORBA::is_nil( shapeObject ) ) {
5387 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5388 if ( !aShapeObject->_is_nil() )
5389 myNewMeshImpl->SetShape( aShapeObject );
5392 delete [] refFromFile;
5395 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5396 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5398 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5399 aDataset->OpenOnDisk();
5400 size = aDataset->GetSize();
5401 int* meshPersistentId = new int[ size ];
5402 aDataset->ReadFromDisk( meshPersistentId );
5403 aDataset->CloseOnDisk();
5404 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5405 delete [] meshPersistentId;
5408 // Restore file info
5409 if ( aTopGroup->ExistInternalObject( "file info" ))
5411 aDataset = new HDFdataset( "file info", aTopGroup );
5412 aDataset->OpenOnDisk();
5413 size = aDataset->GetSize();
5414 std::string info( size, ' ');
5415 aDataset->ReadFromDisk( (char*) info.data() );
5416 aDataset->CloseOnDisk();
5417 myNewMeshImpl->FileInfoFromString( info );
5423 // As all object that can be referred by hypothesis are created,
5424 // we can restore hypothesis data
5426 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5427 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5429 SMESH_Hypothesis_i* hyp = hyp_data->first;
5430 string & data = hyp_data->second;
5431 hyp->LoadFrom( data.c_str() );
5434 // Restore the rest mesh data
5436 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5437 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5439 aTopGroup = meshi_group->second;
5440 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5441 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5442 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5444 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5445 bool hasData = false;
5448 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5449 int newId = myStudyContext->findId( iorString.in() );
5450 int meshOldId = myStudyContext->getOldId( newId );
5452 // try to find mesh data dataset
5453 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5454 // load mesh "has data" flag
5455 aDataset = new HDFdataset( "Has data", aTopGroup );
5456 aDataset->OpenOnDisk();
5457 size = aDataset->GetSize();
5458 char* strHasData = new char[ size ];
5459 aDataset->ReadFromDisk( strHasData );
5460 aDataset->CloseOnDisk();
5461 if ( strcmp( strHasData, "1") == 0 ) {
5464 delete [] strHasData;
5467 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5468 // nodes and elements are not yet put into sub-meshes)
5469 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5470 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5471 aGroup->OpenOnDisk();
5472 // get number of applied algorithms
5473 int aNbSubObjects = aGroup->nInternalObjects();
5474 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5475 for ( int j = 0; j < aNbSubObjects; j++ ) {
5476 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5477 aGroup->InternalObjectIndentify( j, name_dataset );
5478 // check if it is an algorithm
5479 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5480 aDataset = new HDFdataset( name_dataset, aGroup );
5481 aDataset->OpenOnDisk();
5482 size = aDataset->GetSize();
5483 char* refFromFile = new char[ size ];
5484 aDataset->ReadFromDisk( refFromFile );
5485 aDataset->CloseOnDisk();
5486 // san - it is impossible to recover applied algorithms using their entries within Load() method
5487 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5488 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5489 int id = atoi( refFromFile );
5490 delete [] refFromFile;
5491 string anIOR = myStudyContext->getIORbyOldId( id );
5492 if ( !anIOR.empty() ) {
5493 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5494 if ( !CORBA::is_nil( hypObject ) ) {
5495 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5496 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5497 || !myNewMeshImpl->HasShapeToMesh()) )
5498 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5503 aGroup->CloseOnDisk();
5506 // try to get applied hypotheses
5507 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5508 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5509 aGroup->OpenOnDisk();
5510 // get number of applied hypotheses
5511 int aNbSubObjects = aGroup->nInternalObjects();
5512 for ( int j = 0; j < aNbSubObjects; j++ ) {
5513 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5514 aGroup->InternalObjectIndentify( j, name_dataset );
5515 // check if it is a hypothesis
5516 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5517 aDataset = new HDFdataset( name_dataset, aGroup );
5518 aDataset->OpenOnDisk();
5519 size = aDataset->GetSize();
5520 char* refFromFile = new char[ size ];
5521 aDataset->ReadFromDisk( refFromFile );
5522 aDataset->CloseOnDisk();
5523 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5524 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5525 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5526 int id = atoi( refFromFile );
5527 delete [] refFromFile;
5528 string anIOR = myStudyContext->getIORbyOldId( id );
5529 if ( !anIOR.empty() ) {
5530 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5531 if ( !CORBA::is_nil( hypObject ) ) {
5532 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5533 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5534 || !myNewMeshImpl->HasShapeToMesh()) )
5535 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5540 aGroup->CloseOnDisk();
5543 // --> try to find SUB-MESHES containers for each type of submesh
5544 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5545 const char* name_meshgroup = 0;
5546 if ( j == GetSubMeshOnVertexTag() )
5547 name_meshgroup = "SubMeshes On Vertex";
5548 else if ( j == GetSubMeshOnEdgeTag() )
5549 name_meshgroup = "SubMeshes On Edge";
5550 else if ( j == GetSubMeshOnWireTag() )
5551 name_meshgroup = "SubMeshes On Wire";
5552 else if ( j == GetSubMeshOnFaceTag() )
5553 name_meshgroup = "SubMeshes On Face";
5554 else if ( j == GetSubMeshOnShellTag() )
5555 name_meshgroup = "SubMeshes On Shell";
5556 else if ( j == GetSubMeshOnSolidTag() )
5557 name_meshgroup = "SubMeshes On Solid";
5558 else if ( j == GetSubMeshOnCompoundTag() )
5559 name_meshgroup = "SubMeshes On Compound";
5561 // try to get submeshes container HDF group
5562 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5563 // open submeshes containers HDF group
5564 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5565 aGroup->OpenOnDisk();
5567 // get number of submeshes
5568 int aNbSubMeshes = aGroup->nInternalObjects();
5569 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5571 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5572 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5573 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5574 // --> get submesh id
5575 int subid = atoi( name_submeshgroup + 7 );
5578 // open submesh HDF group
5579 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5580 aSubGroup->OpenOnDisk();
5582 // try to read and set reference to subshape
5583 GEOM::GEOM_Object_var aSubShapeObject;
5584 SMESH::SMESH_subMesh_var aSubMesh;
5586 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5587 // load submesh "Ref on shape" - it's an entry to SObject
5588 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5589 aDataset->OpenOnDisk();
5590 size = aDataset->GetSize();
5591 char* refFromFile = new char[ size ];
5592 aDataset->ReadFromDisk( refFromFile );
5593 aDataset->CloseOnDisk();
5594 if ( strlen( refFromFile ) > 0 ) {
5595 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5596 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5597 if ( !CORBA::is_nil( subShapeObject ) ) {
5598 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5599 if ( !aSubShapeObject->_is_nil() )
5600 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5601 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5602 if ( aSubMesh->_is_nil() )
5604 string iorSubString = GetORB()->object_to_string( aSubMesh );
5605 int newSubId = myStudyContext->findId( iorSubString );
5606 myStudyContext->mapOldToNew( subid, newSubId );
5609 delete [] refFromFile;
5612 if ( aSubMesh->_is_nil() )
5615 // try to get applied algorithms
5616 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5617 // open "applied algorithms" HDF group
5618 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5619 aSubSubGroup->OpenOnDisk();
5620 // get number of applied algorithms
5621 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5622 for ( int l = 0; l < aNbSubObjects; l++ ) {
5623 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5624 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5625 // check if it is an algorithm
5626 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5627 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5628 aDataset->OpenOnDisk();
5629 size = aDataset->GetSize();
5630 char* refFromFile = new char[ size ];
5631 aDataset->ReadFromDisk( refFromFile );
5632 aDataset->CloseOnDisk();
5634 int id = atoi( refFromFile );
5635 string anIOR = myStudyContext->getIORbyOldId( id );
5636 if ( !anIOR.empty() ) {
5637 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5638 if ( !CORBA::is_nil( hypObject ) ) {
5639 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5640 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5641 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5644 delete [] refFromFile;
5647 // close "applied algorithms" HDF group
5648 aSubSubGroup->CloseOnDisk();
5651 // try to get applied hypotheses
5652 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5653 // open "applied hypotheses" HDF group
5654 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5655 aSubSubGroup->OpenOnDisk();
5656 // get number of applied hypotheses
5657 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5658 for ( int l = 0; l < aNbSubObjects; l++ ) {
5659 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5660 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5661 // check if it is a hypothesis
5662 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5663 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5664 aDataset->OpenOnDisk();
5665 size = aDataset->GetSize();
5666 char* refFromFile = new char[ size ];
5667 aDataset->ReadFromDisk( refFromFile );
5668 aDataset->CloseOnDisk();
5670 int id = atoi( refFromFile );
5671 string anIOR = myStudyContext->getIORbyOldId( id );
5672 if ( !anIOR.empty() ) {
5673 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5674 if ( !CORBA::is_nil( hypObject ) ) {
5675 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5676 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5677 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5680 delete [] refFromFile;
5683 // close "APPLIED HYPOTHESES" hdf group
5684 aSubSubGroup->CloseOnDisk();
5687 // close SUB-MESH hdf group
5688 aSubGroup->CloseOnDisk();
5691 // close SUB-MESHES containers hdf group
5692 aGroup->CloseOnDisk();
5696 // try to get GROUPS
5697 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5698 char name_group[ 30 ];
5699 if ( ii == GetNodeGroupsTag() )
5700 strcpy( name_group, "Groups of Nodes" );
5701 else if ( ii == GetEdgeGroupsTag() )
5702 strcpy( name_group, "Groups of Edges" );
5703 else if ( ii == GetFaceGroupsTag() )
5704 strcpy( name_group, "Groups of Faces" );
5705 else if ( ii == GetVolumeGroupsTag() )
5706 strcpy( name_group, "Groups of Volumes" );
5707 else if ( ii == Get0DElementsGroupsTag() )
5708 strcpy( name_group, "Groups of 0D Elements" );
5709 else if ( ii == GetBallElementsGroupsTag() )
5710 strcpy( name_group, "Groups of Balls" );
5712 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5713 aGroup = new HDFgroup( name_group, aTopGroup );
5714 aGroup->OpenOnDisk();
5715 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5716 // within aGroup->ExistInternalObject( name )
5717 std::vector< std::string > subNames;
5718 TColStd_MapOfAsciiString mapOfNames;
5719 aGroup->GetAllObjects( subNames );
5720 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5721 mapOfNames.Add( subNames[ iN ].c_str() );
5723 for ( size_t j = 0; j < subNames.size(); j++ ) {
5724 const std::string& name_dataset = subNames[ j ];
5725 // check if it is a group
5726 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5729 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5732 int groupID = -1; // group local ID (also persistent)
5734 groupID = atoi( endptr + 1 );
5735 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5736 aDataset->OpenOnDisk();
5738 // Retrieve actual group name
5739 size = aDataset->GetSize();
5740 char* nameFromFile = new char[ size ];
5741 aDataset->ReadFromDisk( nameFromFile );
5742 aDataset->CloseOnDisk();
5744 // Try to find a shape reference
5745 TopoDS_Shape aShape;
5746 char aRefName[ 30 ];
5747 sprintf( aRefName, "Ref on shape %d", subid);
5748 if ( mapOfNames.Contains( aRefName ))
5750 // load mesh "Ref on shape" - it's an entry to SObject
5751 aDataset = new HDFdataset( aRefName, aGroup );
5752 aDataset->OpenOnDisk();
5753 size = aDataset->GetSize();
5754 char* refFromFile = new char[ size ];
5755 aDataset->ReadFromDisk( refFromFile );
5756 aDataset->CloseOnDisk();
5757 if ( strlen( refFromFile ) > 0 ) {
5758 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5759 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5760 if ( !CORBA::is_nil( shapeObject ) ) {
5761 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5762 if ( !aShapeObject->_is_nil() )
5763 aShape = GeomObjectToShape( aShapeObject );
5766 delete [] refFromFile;
5768 // Try to read a filter of SMESH_GroupOnFilter
5769 SMESH::Filter_var filter;
5770 SMESH_PredicatePtr predicate;
5771 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5772 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5774 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5775 aDataset->OpenOnDisk();
5776 size = aDataset->GetSize();
5777 char* persistStr = new char[ size ];
5778 aDataset->ReadFromDisk( persistStr );
5779 aDataset->CloseOnDisk();
5780 if ( strlen( persistStr ) > 0 ) {
5781 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5782 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5783 filters.push_back( filter );
5785 delete [] persistStr;
5788 // Create group servant
5789 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5790 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5791 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5792 delete [] nameFromFile;
5793 // Obtain a SMESHDS_Group object
5794 if ( aNewGroup->_is_nil() )
5797 string iorSubString = GetORB()->object_to_string( aNewGroup );
5798 int newSubId = myStudyContext->findId( iorSubString );
5799 myStudyContext->mapOldToNew( subid, newSubId );
5801 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5805 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5806 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5808 aFilterGroup->SetFilter( filter );
5809 filter->UnRegister();
5811 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5812 if ( !aGroupBaseDS )
5815 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5818 // Read color of the group
5819 char aGroupColorName[ 30 ];
5820 sprintf( aGroupColorName, "ColorGroup %d", subid);
5821 if ( mapOfNames.Contains( aGroupColorName ))
5823 aDataset = new HDFdataset( aGroupColorName, aGroup );
5824 aDataset->OpenOnDisk();
5825 size = aDataset->GetSize();
5826 double* anRGB = new double[ size ];
5827 aDataset->ReadFromDisk( anRGB );
5828 aDataset->CloseOnDisk();
5829 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5830 aGroupBaseDS->SetColor( aColor );
5835 aGroup->CloseOnDisk();
5839 // instead of reading mesh data, we read only brief information of all
5840 // objects: mesh, groups, sub-meshes (issue 0021208)
5843 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5844 meshfile.ToCString(), filename.ToCString(),
5848 // read Sub-Mesh ORDER if any
5849 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5850 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5851 aDataset->OpenOnDisk();
5852 size = aDataset->GetSize();
5853 int* smIDs = new int[ size ];
5854 aDataset->ReadFromDisk( smIDs );
5855 aDataset->CloseOnDisk();
5856 TListOfListOfInt anOrderIds;
5857 anOrderIds.push_back( TListOfInt() );
5858 for ( int i = 0; i < size; i++ )
5859 if ( smIDs[ i ] < 0 ) // is separator
5860 anOrderIds.push_back( TListOfInt() );
5862 anOrderIds.back().push_back(smIDs[ i ]);
5864 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5869 // update hyps needing full mesh data restored (issue 20918)
5870 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5872 SMESH_Hypothesis_i* hyp = hyp_data->first;
5873 hyp->UpdateAsMeshesRestored();
5876 // notify algos on completed restoration to set sub-mesh event listeners
5877 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5879 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5880 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5882 TopoDS_Shape myLocShape;
5883 if(myLocMesh.HasShapeToMesh())
5884 myLocShape = myLocMesh.GetShapeToMesh();
5886 myLocShape = SMESH_Mesh::PseudoShape();
5888 myLocMesh.GetSubMesh(myLocShape)->
5889 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5892 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5893 list< SMESH::Filter_var >::iterator f = filters.begin();
5894 for ( ; f != filters.end(); ++f )
5895 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5896 fi->FindBaseObjects();
5901 aTopGroup->CloseOnDisk();
5904 aFile->CloseOnDisk();
5907 // Remove temporary files created from the stream
5910 SMESH_File meshFile( meshfile.ToCString() );
5911 if ( !meshFile ) // no meshfile exists
5913 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5917 Engines::Container_var container = GetContainerRef();
5918 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5920 container_i->registerTemporaryFile( filename.ToCString() );
5921 container_i->registerTemporaryFile( meshfile.ToCString() );
5922 container_i->registerTemporaryFile( tmpDir.ToCString() );
5926 pd << ""; // prevent optimizing pd out
5928 // creation of tree nodes for all data objects in the study
5929 // to support tree representation customization and drag-n-drop:
5930 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5931 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5932 useCaseBuilder->SetRootCurrent();
5933 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5934 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5935 for (it->InitEx(true); it->More(); it->Next()) {
5936 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5943 //=============================================================================
5945 * SMESH_Gen_i::LoadASCII
5947 * Load SMESH module's data in ASCII format
5949 //=============================================================================
5951 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5952 const SALOMEDS::TMPFile& theStream,
5954 bool isMultiFile ) {
5955 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5956 return Load( theComponent, theStream, theURL, isMultiFile );
5958 //before call main ::Load method it's need for decipher text format to
5959 //binary ( "|xx" => x' )
5960 int size = theStream.length();
5961 if ( int((size / 3 )*3) != size ) //error size of buffer
5964 int real_size = int(size / 3);
5966 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5969 unsigned int c = -1;
5970 for ( int i = 0; i < real_size; i++ )
5972 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5973 sscanf( tmp, "%x", &c );
5974 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5977 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5979 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5982 //=============================================================================
5984 * SMESH_Gen_i::Close
5986 * Clears study-connected data when it is closed
5988 //=============================================================================
5990 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
5992 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
5994 // Clear study contexts data
5995 myStudyContext->Clear();
5997 // remove the tmp files meshes are loaded from
5998 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6000 // Clean trace of API methods calls
6006 //=============================================================================
6008 * SMESH_Gen_i::ComponentDataType
6010 * Get component data type
6012 //=============================================================================
6014 char* SMESH_Gen_i::ComponentDataType()
6016 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6017 return CORBA::string_dup( "SMESH" );
6021 //=============================================================================
6023 * SMESH_Gen_i::IORToLocalPersistentID
6025 * Transform data from transient form to persistent
6027 //=============================================================================
6029 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6030 const char* IORString,
6031 CORBA::Boolean /*isMultiFile*/,
6032 CORBA::Boolean /*isASCII*/ )
6034 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6036 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6037 int anId = myStudyContext->findId( IORString );
6039 if(MYDEBUG) MESSAGE( "VSR " << anId )
6041 sprintf( strId, "%d", anId );
6042 return CORBA::string_dup( strId );
6045 return CORBA::string_dup( "" );
6048 //=============================================================================
6050 * SMESH_Gen_i::LocalPersistentIDToIOR
6052 * Transform data from persistent form to transient
6054 //=============================================================================
6056 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6057 const char* aLocalPersistentID,
6058 CORBA::Boolean /*isMultiFile*/,
6059 CORBA::Boolean /*isASCII*/ )
6061 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6063 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6064 int anId = atoi( aLocalPersistentID );
6065 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6067 return CORBA::string_dup( "" );
6070 //=======================================================================
6071 //function : RegisterObject
6073 //=======================================================================
6075 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6077 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6078 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6079 return myStudyContext->addObject( string( iorString.in() ) );
6084 //================================================================================
6086 * \brief Return id of registered object
6087 * \param theObject - the Object
6088 * \retval int - Object id
6090 //================================================================================
6092 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6094 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6095 string iorString = GetORB()->object_to_string( theObject );
6096 return myStudyContext->findId( iorString );
6101 //=============================================================================
6103 * SMESH_Gen_i::SetName
6105 * Set a new object name
6107 //=============================================================================
6108 void SMESH_Gen_i::SetName(const char* theIOR,
6109 const char* theName)
6111 if ( theIOR && strcmp( theIOR, "" ) ) {
6112 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6113 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6114 if ( !aSO->_is_nil() ) {
6115 SetName( aSO, theName );
6120 // Version information
6121 char* SMESH_Gen_i::getVersion()
6123 #if SMESH_DEVELOPMENT
6124 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6126 return CORBA::string_dup(SMESH_VERSION_STR);
6130 //=================================================================================
6131 // function : Move()
6132 // purpose : Moves objects to the specified position.
6133 // Is used in the drag-n-drop functionality.
6134 //=================================================================================
6135 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6136 SALOMEDS::SObject_ptr where,
6139 if ( CORBA::is_nil( where ) ) return;
6141 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6142 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6143 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6144 std::string dataType = father->ComponentDataType();
6145 if ( dataType != "SMESH" ) return; // not a SMESH component
6147 SALOMEDS::SObject_var objAfter;
6148 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6149 // insert at given row -> find insertion position
6150 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6152 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6153 if ( i == row && useCaseIt->More() ) {
6154 objAfter = useCaseIt->Value();
6158 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6159 SALOMEDS::SObject_var sobj = what[i];
6160 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6161 // insert the object to the use case tree
6162 if ( !CORBA::is_nil( objAfter ) )
6163 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6165 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6168 //================================================================================
6170 * \brief Returns true if algorithm can be used to mesh a given geometry
6171 * \param [in] theAlgoType - the algorithm type
6172 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6173 * \param [in] theGeomObject - the geometry to mesh
6174 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6175 * else, returns \c True if at least one shape is meshable
6176 * \return CORBA::Boolean - can or can't
6178 //================================================================================
6180 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6181 const char* theLibName,
6182 GEOM::GEOM_Object_ptr theGeomObject,
6183 CORBA::Boolean toCheckAll)
6187 std::string aPlatformLibName;
6188 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6189 GenericHypothesisCreator_i* aCreator =
6190 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6193 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6194 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6195 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6202 SMESH_CATCH( SMESH::doNothing );
6205 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6210 //=================================================================================
6211 // function : GetInsideSphere
6212 // purpose : Collect indices of elements, which are located inside the sphere
6213 //=================================================================================
6214 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6215 SMESH::ElementType theElemType,
6221 SMESH::long_array_var aResult = new SMESH::long_array();
6222 if ( meshPart->_is_nil() )
6223 return aResult._retn();
6225 // 1. Create geometrical object
6226 gp_Pnt aP( theX, theY, theZ );
6227 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6229 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6231 if ( lst.size() > 0 ) {
6232 aResult->length( lst.size() );
6233 for ( size_t i = 0; i < lst.size(); i++ ) {
6234 aResult[i] = lst[i];
6237 return aResult._retn();
6240 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6241 SMESH::ElementType theElemType,
6242 CORBA::Double theX1,
6243 CORBA::Double theY1,
6244 CORBA::Double theZ1,
6245 CORBA::Double theX2,
6246 CORBA::Double theY2,
6247 CORBA::Double theZ2) {
6248 SMESH::long_array_var aResult = new SMESH::long_array();
6249 if( meshPart->_is_nil() )
6250 return aResult._retn();
6252 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6254 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6256 if( lst.size() > 0 ) {
6257 aResult->length( lst.size() );
6258 for ( size_t i = 0; i < lst.size(); i++ ) {
6259 aResult[i] = lst[i];
6262 return aResult._retn();
6265 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6266 SMESH::ElementType theElemType,
6270 CORBA::Double theDX,
6271 CORBA::Double theDY,
6272 CORBA::Double theDZ,
6274 CORBA::Double theR ){
6275 SMESH::long_array_var aResult = new SMESH::long_array();
6276 if( meshPart->_is_nil() )
6277 return aResult._retn();
6279 gp_Pnt aP( theX, theY, theZ );
6280 gp_Vec aV( theDX, theDY, theDZ );
6281 gp_Ax2 anAxes (aP, aV);
6283 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6285 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6287 if( lst.size() > 0 ) {
6288 aResult->length( lst.size() );
6289 for ( size_t i = 0; i < lst.size(); i++ ) {
6290 aResult[i] = lst[i];
6293 return aResult._retn();
6296 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6297 SMESH::ElementType theElemType,
6298 GEOM::GEOM_Object_ptr theGeom,
6299 CORBA::Double theTolerance ) {
6300 SMESH::long_array_var aResult = new SMESH::long_array();
6301 if( meshPart->_is_nil() || theGeom->_is_nil() )
6302 return aResult._retn();
6304 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6306 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6308 if( lst.size() > 0 ) {
6309 aResult->length( lst.size() );
6310 for ( size_t i = 0; i < lst.size(); i++ ) {
6311 aResult[i] = lst[i];
6314 return aResult._retn();
6319 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6320 SMESH::ElementType theElemType,
6321 TopoDS_Shape& aShape,
6322 double* theTolerance) {
6324 std::vector<long> res;
6325 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6327 if ( mesh->_is_nil() )
6330 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6334 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6339 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6340 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6341 anElementsOnShape->SetAllNodes( true );
6342 anElementsOnShape->SetMesh( meshDS );
6343 anElementsOnShape->SetShape( aShape, aType );
6346 anElementsOnShape->SetTolerance(*theTolerance);
6348 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6349 if ( !msource->_is_nil() ) { // Mesh case
6350 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6352 while ( elemIt->more() ) {
6353 const SMDS_MeshElement* anElem = elemIt->next();
6354 long anId = anElem->GetID();
6355 if ( anElementsOnShape->IsSatisfy( anId ) )
6356 res.push_back( anId );
6360 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6361 if ( !gsource->_is_nil() ) {
6362 if(theElemType == SMESH::NODE) {
6363 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6364 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6365 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6366 long anId = node->GetID();
6367 if ( anElementsOnShape->IsSatisfy( anId ) )
6368 res.push_back( anId );
6371 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6372 SMESH::long_array_var elems = gsource->GetListOfID();
6373 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6374 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6375 long anId = elem->GetID();
6376 if ( anElementsOnShape->IsSatisfy( anId ) )
6377 res.push_back( anId );
6382 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6383 if ( !smsource->_is_nil() ) {
6384 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6385 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6386 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6388 long anId = elem->GetID();
6389 if ( anElementsOnShape->IsSatisfy( anId ) )
6390 res.push_back( anId );
6398 //=============================================================================
6400 * SMESHEngine_factory
6402 * C factory, accessible with dlsym, after dlopen
6404 //=============================================================================
6408 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6409 PortableServer::POA_ptr poa,
6410 PortableServer::ObjectId* contId,
6411 const char* instanceName,
6412 const char* interfaceName )
6414 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6415 if(MYDEBUG) SCRUTE(interfaceName);
6416 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6417 return aSMESHGen->getId() ;