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_var 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() && !geomGen->_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_var 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 // Store SMESH_Mesh_i::_mainShapeTick
4373 int shapeTick = myImpl->MainShapeTick();
4375 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4376 aDataset->CreateOnDisk();
4377 aDataset->WriteOnDisk( &shapeTick );
4378 aDataset->CloseOnDisk();
4380 // write reference on a shape if exists
4381 SALOMEDS::SObject_wrap myRef;
4382 bool shapeRefFound = false;
4383 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4385 SALOMEDS::SObject_wrap myShape;
4386 bool ok = myRef->ReferencedObject( myShape.inout() );
4388 CORBA::Object_var shapeObj = myShape->GetObject();
4389 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4390 CORBA::String_var myRefOnObject = myShape->GetID();
4391 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4392 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4393 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4394 aDataset->CreateOnDisk();
4395 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4396 aDataset->CloseOnDisk();
4402 std::string info = myImpl->FileInfoToString();
4403 if ( !info.empty() )
4405 aSize[ 0 ] = info.size();
4406 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4407 aDataset->CreateOnDisk();
4408 aDataset->WriteOnDisk( (char*) info.data() );
4409 aDataset->CloseOnDisk();
4412 // write applied hypotheses if exist
4413 SALOMEDS::SObject_wrap myHypBranch;
4414 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4415 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4416 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4418 if ( found && (shapeRefFound || !hasShape) ) {
4419 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4420 aGroup->CreateOnDisk();
4422 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4424 for ( ; it->More(); it->Next() ) {
4425 SALOMEDS::SObject_wrap mySObject = it->Value();
4426 SALOMEDS::SObject_wrap myRefOnHyp;
4427 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4429 // san - it is impossible to recover applied hypotheses
4430 // using their entries within Load() method,
4431 // for there are no AttributeIORs in the study when Load() is working.
4432 // Hence, it is better to store persistent IDs of hypotheses as references to them
4434 //string myRefOnObject = myRefOnHyp->GetID();
4435 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4436 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4437 int id = myStudyContext->findId( string( objStr.in() ) );
4438 //if ( myRefOnObject.length() > 0 ) {
4439 //aSize[ 0 ] = myRefOnObject.length() + 1;
4440 char hypName[ 30 ], hypId[ 30 ];
4441 sprintf( hypName, "Hyp %d", ++hypNb );
4442 sprintf( hypId, "%d", id );
4443 aSize[ 0 ] = strlen( hypId ) + 1;
4444 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4445 aDataset->CreateOnDisk();
4446 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4447 aDataset->WriteOnDisk( hypId );
4448 aDataset->CloseOnDisk();
4452 aGroup->CloseOnDisk();
4455 // write applied algorithms if exist
4456 SALOMEDS::SObject_wrap myAlgoBranch;
4457 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4458 myAlgoBranch.inout() );
4459 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4460 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4462 if ( found && (shapeRefFound || !hasShape)) {
4463 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4464 aGroup->CreateOnDisk();
4466 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4468 for ( ; it->More(); it->Next() ) {
4469 SALOMEDS::SObject_wrap mySObject = it->Value();
4470 SALOMEDS::SObject_wrap myRefOnAlgo;
4471 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4473 // san - it is impossible to recover applied algorithms
4474 // using their entries within Load() method,
4475 // for there are no AttributeIORs in the study when Load() is working.
4476 // Hence, it is better to store persistent IDs of algorithms as references to them
4478 //string myRefOnObject = myRefOnAlgo->GetID();
4479 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4480 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4481 int id = myStudyContext->findId( string( objStr.in() ) );
4482 //if ( myRefOnObject.length() > 0 ) {
4483 //aSize[ 0 ] = myRefOnObject.length() + 1;
4484 char algoName[ 30 ], algoId[ 30 ];
4485 sprintf( algoName, "Algo %d", ++algoNb );
4486 sprintf( algoId, "%d", id );
4487 aSize[ 0 ] = strlen( algoId ) + 1;
4488 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4489 aDataset->CreateOnDisk();
4490 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4491 aDataset->WriteOnDisk( algoId );
4492 aDataset->CloseOnDisk();
4496 aGroup->CloseOnDisk();
4499 // --> submesh objects sub-branches
4501 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4502 SALOMEDS::SObject_wrap mySubmeshBranch;
4503 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4505 if ( found ) // check if there is shape reference in submeshes
4507 bool hasShapeRef = false;
4508 SALOMEDS::ChildIterator_wrap itSM =
4509 aStudy->NewChildIterator( mySubmeshBranch );
4510 for ( ; itSM->More(); itSM->Next() ) {
4511 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4512 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4513 mySubRef->ReferencedObject( myShape.inout() );
4514 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4517 { // remove one submesh
4518 if ( shapeRefFound )
4519 { // unassign hypothesis
4520 SMESH::SMESH_subMesh_var mySubMesh =
4521 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4522 if ( !mySubMesh->_is_nil() ) {
4523 int shapeID = mySubMesh->GetId();
4524 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4525 const list<const SMESHDS_Hypothesis*>& hypList =
4526 mySMESHDSMesh->GetHypothesis( S );
4527 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4528 while ( hyp != hypList.end() ) {
4529 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4530 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4534 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4536 } // loop on submeshes of a type
4537 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4538 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4541 } // end check if there is shape reference in submeshes
4543 char name_meshgroup[ 30 ];
4544 if ( i == GetSubMeshOnVertexTag() )
4545 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4546 else if ( i == GetSubMeshOnEdgeTag() )
4547 strcpy( name_meshgroup, "SubMeshes On Edge" );
4548 else if ( i == GetSubMeshOnWireTag() )
4549 strcpy( name_meshgroup, "SubMeshes On Wire" );
4550 else if ( i == GetSubMeshOnFaceTag() )
4551 strcpy( name_meshgroup, "SubMeshes On Face" );
4552 else if ( i == GetSubMeshOnShellTag() )
4553 strcpy( name_meshgroup, "SubMeshes On Shell" );
4554 else if ( i == GetSubMeshOnSolidTag() )
4555 strcpy( name_meshgroup, "SubMeshes On Solid" );
4556 else if ( i == GetSubMeshOnCompoundTag() )
4557 strcpy( name_meshgroup, "SubMeshes On Compound" );
4559 // for each type of submeshes create container HDF group
4560 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4561 aGroup->CreateOnDisk();
4563 // iterator for all submeshes of given type
4564 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4565 for ( ; itSM->More(); itSM->Next() ) {
4566 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4567 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4568 if ( !CORBA::is_nil( anSubObject ))
4570 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4571 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4572 int subid = myStudyContext->findId( string( objStr.in() ) );
4574 // for each mesh open the HDF group basing on its id
4575 char submeshGrpName[ 30 ];
4576 sprintf( submeshGrpName, "SubMesh %d", subid );
4577 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4578 aSubGroup->CreateOnDisk();
4580 // write reference on a shape, already checked if it exists
4581 SALOMEDS::SObject_wrap mySubRef, myShape;
4582 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4583 mySubRef->ReferencedObject( myShape.inout() );
4584 string myRefOnObject = myShape->GetID();
4585 if ( myRefOnObject.length() > 0 ) {
4586 aSize[ 0 ] = myRefOnObject.length() + 1;
4587 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4588 aDataset->CreateOnDisk();
4589 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4590 aDataset->CloseOnDisk();
4593 // write applied hypotheses if exist
4594 SALOMEDS::SObject_wrap mySubHypBranch;
4595 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4596 mySubHypBranch.inout() );
4598 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4599 aSubSubGroup->CreateOnDisk();
4601 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4603 for ( ; it->More(); it->Next() ) {
4604 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4605 SALOMEDS::SObject_wrap myRefOnHyp;
4606 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4608 //string myRefOnObject = myRefOnHyp->GetID();
4609 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4610 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4611 int id = myStudyContext->findId( string( objStr.in() ) );
4612 //if ( myRefOnObject.length() > 0 ) {
4613 //aSize[ 0 ] = myRefOnObject.length() + 1;
4614 char hypName[ 30 ], hypId[ 30 ];
4615 sprintf( hypName, "Hyp %d", ++hypNb );
4616 sprintf( hypId, "%d", id );
4617 aSize[ 0 ] = strlen( hypId ) + 1;
4618 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4619 aDataset->CreateOnDisk();
4620 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4621 aDataset->WriteOnDisk( hypId );
4622 aDataset->CloseOnDisk();
4626 aSubSubGroup->CloseOnDisk();
4629 // write applied algorithms if exist
4630 SALOMEDS::SObject_wrap mySubAlgoBranch;
4631 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4632 mySubAlgoBranch.inout() );
4634 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4635 aSubSubGroup->CreateOnDisk();
4637 SALOMEDS::ChildIterator_wrap it =
4638 aStudy->NewChildIterator( mySubAlgoBranch );
4640 for ( ; it->More(); it->Next() ) {
4641 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4642 SALOMEDS::SObject_wrap myRefOnAlgo;
4643 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4645 //string myRefOnObject = myRefOnAlgo->GetID();
4646 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4647 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4648 int id = myStudyContext->findId( string( objStr.in() ) );
4649 //if ( myRefOnObject.length() > 0 ) {
4650 //aSize[ 0 ] = myRefOnObject.length() + 1;
4651 char algoName[ 30 ], algoId[ 30 ];
4652 sprintf( algoName, "Algo %d", ++algoNb );
4653 sprintf( algoId, "%d", id );
4654 aSize[ 0 ] = strlen( algoId ) + 1;
4655 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4656 aDataset->CreateOnDisk();
4657 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4658 aDataset->WriteOnDisk( algoId );
4659 aDataset->CloseOnDisk();
4663 aSubSubGroup->CloseOnDisk();
4665 // close submesh HDF group
4666 aSubGroup->CloseOnDisk();
4669 // close container of submeshes by type HDF group
4670 aGroup->CloseOnDisk();
4673 // All sub-meshes will be stored in MED file
4674 // .. will NOT (PAL 12992)
4675 //if ( shapeRefFound )
4676 //myWriter.AddAllSubMeshes();
4678 // store submesh order if any
4679 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4680 if ( theOrderIds.size() ) {
4681 char order_list[ 30 ];
4682 strcpy( order_list, "Mesh Order" );
4683 // count number of submesh ids
4685 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4686 for ( ; idIt != theOrderIds.end(); idIt++ )
4687 nbIDs += (*idIt).size();
4688 // number of values = number of IDs +
4689 // number of lists (for separators) - 1
4690 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4691 idIt = theOrderIds.begin();
4692 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4693 const TListOfInt& idList = *idIt;
4694 if (idIt != theOrderIds.begin()) // not first list
4695 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4696 // dump submesh ids from current list
4697 TListOfInt::const_iterator id_smId = idList.begin();
4698 for( ; id_smId != idList.end(); id_smId++ )
4699 smIDs[ i++ ] = *id_smId;
4702 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4704 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4705 aDataset->CreateOnDisk();
4706 aDataset->WriteOnDisk( smIDs );
4707 aDataset->CloseOnDisk();
4712 // groups root sub-branch
4713 SALOMEDS::SObject_wrap myGroupsBranch;
4714 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4715 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4717 char name_group[ 30 ];
4718 if ( i == GetNodeGroupsTag() )
4719 strcpy( name_group, "Groups of Nodes" );
4720 else if ( i == GetEdgeGroupsTag() )
4721 strcpy( name_group, "Groups of Edges" );
4722 else if ( i == GetFaceGroupsTag() )
4723 strcpy( name_group, "Groups of Faces" );
4724 else if ( i == GetVolumeGroupsTag() )
4725 strcpy( name_group, "Groups of Volumes" );
4726 else if ( i == Get0DElementsGroupsTag() )
4727 strcpy( name_group, "Groups of 0D Elements" );
4728 else if ( i == GetBallElementsGroupsTag() )
4729 strcpy( name_group, "Groups of Balls" );
4731 aGroup = new HDFgroup( name_group, aTopGroup );
4732 aGroup->CreateOnDisk();
4734 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4735 for ( ; it->More(); it->Next() ) {
4736 SALOMEDS::SObject_wrap mySObject = it->Value();
4737 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4738 if ( !CORBA::is_nil( aSubObject ) ) {
4739 SMESH_GroupBase_i* myGroupImpl =
4740 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4743 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4747 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4748 int anId = myStudyContext->findId( string( objStr.in() ) );
4750 // For each group, create a dataset named "Group <group_persistent_id>"
4751 // and store the group's user name into it
4752 const char* grpName = aGrpBaseDS->GetStoreName();
4753 CORBA::String_var aUserName = myGroupImpl->GetName();
4754 aSize[ 0 ] = strlen( aUserName ) + 1;
4756 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4757 aDataset->CreateOnDisk();
4758 aDataset->WriteOnDisk( aUserName );
4759 aDataset->CloseOnDisk();
4762 // For each group, create a dataset named "Group <group_persistent_id> Color"
4763 // and store the group's color into it
4764 char grpColorName[ 30 ];
4765 sprintf( grpColorName, "ColorGroup %d", anId );
4766 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4768 anRGB[ 0 ] = aColor.R;
4769 anRGB[ 1 ] = aColor.G;
4770 anRGB[ 2 ] = aColor.B;
4772 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4773 aDataset->CreateOnDisk();
4774 aDataset->WriteOnDisk( anRGB );
4775 aDataset->CloseOnDisk();
4777 // Pass SMESHDS_Group to MED writer
4778 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4780 myWriter.AddGroup( aGrpDS );
4782 // write reference on a shape if exists
4783 SMESHDS_GroupOnGeom* aGeomGrp =
4784 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4786 SALOMEDS::SObject_wrap mySubRef, myShape;
4787 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4788 mySubRef->ReferencedObject( myShape.inout() ) &&
4789 !CORBA::is_nil( myShape->GetObject() ))
4791 CORBA::String_var myRefOnObject = myShape->GetID();
4792 if ( myRefOnObject.in()[0] ) {
4793 char aRefName[ 30 ];
4794 sprintf( aRefName, "Ref on shape %d", anId);
4795 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4796 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4797 aDataset->CreateOnDisk();
4798 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4799 aDataset->CloseOnDisk();
4802 else // shape ref is invalid:
4804 // save a group on geometry as ordinary group
4805 myWriter.AddGroup( aGeomGrp );
4808 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4809 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4811 std::string str = aFilterGrp_i->FilterToString();
4812 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4813 aSize[ 0 ] = str.length() + 1;
4814 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4815 aDataset->CreateOnDisk();
4816 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4817 aDataset->CloseOnDisk();
4821 aGroup->CloseOnDisk();
4825 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4827 // Flush current mesh information into MED file
4830 // save info on nb of elements
4831 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4833 // maybe a shape was deleted in the study
4834 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4835 TopoDS_Shape nullShape;
4836 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4839 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4844 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4845 aGroup->CreateOnDisk();
4847 // each element belongs to one or none submesh,
4848 // so for each node/element, we store a submesh ID
4850 // Store submesh IDs
4851 for ( int isNode = 0; isNode < 2; ++isNode )
4853 SMDS_ElemIteratorPtr eIt =
4854 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4855 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4858 std::vector<int> smIDs; smIDs.reserve( nbElems );
4859 while ( eIt->more() )
4860 if ( const SMDS_MeshElement* e = eIt->next())
4861 smIDs.push_back( e->getshapeId() );
4863 aSize[ 0 ] = nbElems;
4864 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4865 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4866 aDataset->CreateOnDisk();
4867 aDataset->WriteOnDisk( & smIDs[0] );
4868 aDataset->CloseOnDisk();
4871 aGroup->CloseOnDisk();
4873 // Store node positions on sub-shapes (SMDS_Position):
4874 // ----------------------------------------------------
4876 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4877 aGroup->CreateOnDisk();
4879 // in aGroup, create 5 datasets to contain:
4880 // "Nodes on Edges" - ID of node on edge
4881 // "Edge positions" - U parameter on node on edge
4882 // "Nodes on Faces" - ID of node on face
4883 // "Face U positions" - U parameter of node on face
4884 // "Face V positions" - V parameter of node on face
4886 // Find out nb of nodes on edges and faces
4887 // Collect corresponding sub-meshes
4888 int nbEdgeNodes = 0, nbFaceNodes = 0;
4889 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4890 // loop on SMESHDS_SubMesh'es
4891 while ( smIt->more() )
4893 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4894 if ( aSubMesh->IsComplexSubmesh() )
4895 continue; // submesh containing other submeshs
4896 int nbNodes = aSubMesh->NbNodes();
4897 if ( nbNodes == 0 ) continue;
4899 int aShapeID = aSubMesh->GetID();
4900 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4902 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4903 // write only SMDS_FacePosition and SMDS_EdgePosition
4904 switch ( aShapeType ) {
4906 nbFaceNodes += nbNodes;
4907 aFaceSM.push_back( aSubMesh );
4910 nbEdgeNodes += nbNodes;
4911 aEdgeSM.push_back( aSubMesh );
4917 // Treat positions on edges or faces
4918 for ( int onFace = 0; onFace < 2; onFace++ )
4920 // Create arrays to store in datasets
4921 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4922 if (!nbNodes) continue;
4923 int* aNodeIDs = new int [ nbNodes ];
4924 double* aUPos = new double [ nbNodes ];
4925 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4928 // loop on sub-meshes
4929 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4930 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4931 for ( ; itSM != pListSM->end(); itSM++ )
4933 SMESHDS_SubMesh* aSubMesh = (*itSM);
4935 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4936 // loop on nodes in aSubMesh
4937 while ( itNode->more() )
4940 const SMDS_MeshNode* node = itNode->next();
4941 aNodeIDs [ iNode ] = node->GetID();
4944 const SMDS_PositionPtr pos = node->GetPosition();
4945 if ( onFace ) { // on FACE
4946 SMDS_FacePositionPtr fPos = pos;
4948 aUPos[ iNode ] = fPos->GetUParameter();
4949 aVPos[ iNode ] = fPos->GetVParameter();
4956 SMDS_EdgePositionPtr ePos = pos;
4958 aUPos[ iNode ] = ePos->GetUParameter();
4964 } // loop on nodes in aSubMesh
4965 } // loop on sub-meshes
4970 aSize[ 0 ] = nbNodes;
4972 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4973 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4974 aDataset->CreateOnDisk();
4975 aDataset->WriteOnDisk( aNodeIDs );
4976 aDataset->CloseOnDisk();
4979 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4980 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4981 aDataset->CreateOnDisk();
4982 aDataset->WriteOnDisk( aUPos );
4983 aDataset->CloseOnDisk();
4986 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4987 aDataset->CreateOnDisk();
4988 aDataset->WriteOnDisk( aVPos );
4989 aDataset->CloseOnDisk();
4994 if ( aVPos ) delete [] aVPos;
4996 } // treat positions on edges or faces
4998 // close "Node Positions" group
4999 aGroup->CloseOnDisk();
5001 } // if ( there are submeshes in SMESHDS_Mesh )
5004 // close mesh HDF group
5005 aTopGroup->CloseOnDisk();
5013 aFile->CloseOnDisk();
5016 // Convert temporary files to stream
5017 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5019 // Remove temporary files and directory
5021 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5023 return aStreamFile._retn();
5026 //=============================================================================
5028 * SMESH_Gen_i::SaveASCII
5030 * Save SMESH module's data in ASCII format
5032 //=============================================================================
5034 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5036 bool isMultiFile ) {
5037 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5038 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5039 return aStreamFile._retn();
5041 //after usual saving needs to encipher binary to text string
5042 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5043 int size = aStreamFile.in().length();
5044 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5045 for ( int i = 0; i < size; i++ )
5046 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5048 buffer[size * 3] = '\0';
5050 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5052 return anAsciiStreamFile._retn();
5055 //=============================================================================
5059 * Load SMESH module's data
5061 //=============================================================================
5063 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5064 const SALOMEDS::TMPFile& theStream,
5068 UpdateStudy(); // load geom data
5069 Kernel_Utils::Localizer loc;
5071 SALOMEDS::Study_var aStudy = getStudyServant();
5073 // Get temporary files location
5074 TCollection_AsciiString tmpDir =
5075 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5077 // Convert the stream into sequence of files to process
5078 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5081 TCollection_AsciiString aStudyName( "" );
5082 if ( isMultiFile ) {
5083 CORBA::WString_var url = aStudy->URL();
5084 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5086 // Set names of temporary files
5087 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5088 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5092 HDFdataset* aDataset;
5093 HDFgroup* aTopGroup;
5095 HDFgroup* aSubGroup;
5096 HDFgroup* aSubSubGroup;
5099 // ---> open HDF file
5100 aFile = new HDFfile( (char*) filename.ToCString() );
5102 aFile->OpenOnDisk( HDF_RDONLY );
5104 catch ( HDFexception ) {
5105 INFOS( "Load(): " << filename << " not found!" );
5109 TPythonDump pd; // prevent dump during loading
5111 // DriverMED_R_SMESHDS_Mesh myReader;
5112 // myReader.SetFile( meshfile.ToCString() );
5114 // For PAL13473 ("Repetitive mesh") implementation.
5115 // New dependencies between SMESH objects are established:
5116 // now hypotheses can refer to meshes, shapes and other hypotheses.
5117 // To keep data consistent, the following order of data restoration
5119 // 1. Create hypotheses
5120 // 2. Create all meshes
5121 // 3. Load hypotheses' data
5124 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5125 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5126 list< SMESH::Filter_var > filters;
5128 // get total number of top-level groups
5129 int aNbGroups = aFile->nInternalObjects();
5130 if ( aNbGroups > 0 ) {
5131 // --> in first turn we should read&create hypotheses
5132 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5133 // open hypotheses root HDF group
5134 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5135 aTopGroup->OpenOnDisk();
5137 // get number of hypotheses
5138 int aNbObjects = aTopGroup->nInternalObjects();
5139 for ( int j = 0; j < aNbObjects; j++ ) {
5140 // try to identify hypothesis
5141 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5142 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5144 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5145 // open hypothesis group
5146 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5147 aGroup->OpenOnDisk();
5149 // --> get hypothesis id
5150 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5155 // get number of datasets
5156 int aNbSubObjects = aGroup->nInternalObjects();
5157 for ( int k = 0; k < aNbSubObjects; k++ ) {
5159 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5160 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5161 // --> get hypothesis name
5162 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5163 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5164 aDataset->OpenOnDisk();
5165 size = aDataset->GetSize();
5166 char* hypname_str = new char[ size ];
5167 aDataset->ReadFromDisk( hypname_str );
5168 hypname = string( hypname_str );
5169 delete [] hypname_str;
5170 aDataset->CloseOnDisk();
5172 // --> get hypothesis plugin library name
5173 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5174 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5175 aDataset->OpenOnDisk();
5176 size = aDataset->GetSize();
5177 char* libname_str = new char[ size ];
5178 aDataset->ReadFromDisk( libname_str );
5179 if(MYDEBUG) SCRUTE( libname_str );
5180 libname = string( libname_str );
5181 delete [] libname_str;
5182 aDataset->CloseOnDisk();
5184 // --> get hypothesis data
5185 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5186 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5187 aDataset->OpenOnDisk();
5188 size = aDataset->GetSize();
5189 char* hypdata_str = new char[ size ];
5190 aDataset->ReadFromDisk( hypdata_str );
5191 hypdata = string( hypdata_str );
5192 delete [] hypdata_str;
5193 aDataset->CloseOnDisk();
5196 // close hypothesis HDF group
5197 aGroup->CloseOnDisk();
5199 // --> restore hypothesis from data
5200 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5201 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5202 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5203 SMESH::SMESH_Hypothesis_var myHyp;
5205 try { // protect persistence mechanism against exceptions
5206 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5209 INFOS( "Exception during hypothesis creation" );
5212 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5214 // myImpl->LoadFrom( hypdata.c_str() );
5215 hypDataList.push_back( make_pair( myImpl, hypdata ));
5216 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5217 int newId = myStudyContext->findId( iorString.in() );
5218 myStudyContext->mapOldToNew( id, newId );
5221 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5225 // close hypotheses root HDF group
5226 aTopGroup->CloseOnDisk();
5230 // --> then we should read&create algorithms
5231 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5232 // open algorithms root HDF group
5233 aTopGroup = new HDFgroup( "Algorithms", aFile );
5234 aTopGroup->OpenOnDisk();
5236 // get number of algorithms
5237 int aNbObjects = aTopGroup->nInternalObjects();
5238 for ( int j = 0; j < aNbObjects; j++ ) {
5239 // try to identify algorithm
5240 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5241 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5243 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5244 // open algorithm group
5245 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5246 aGroup->OpenOnDisk();
5248 // --> get algorithm id
5249 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5254 // get number of datasets
5255 int aNbSubObjects = aGroup->nInternalObjects();
5256 for ( int k = 0; k < aNbSubObjects; k++ ) {
5258 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5259 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5260 // --> get algorithm name
5261 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5262 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5263 aDataset->OpenOnDisk();
5264 size = aDataset->GetSize();
5265 char* hypname_str = new char[ size ];
5266 aDataset->ReadFromDisk( hypname_str );
5267 hypname = string( hypname_str );
5268 delete [] hypname_str;
5269 aDataset->CloseOnDisk();
5271 // --> get algorithm plugin library name
5272 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5273 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5274 aDataset->OpenOnDisk();
5275 size = aDataset->GetSize();
5276 char* libname_str = new char[ size ];
5277 aDataset->ReadFromDisk( libname_str );
5278 if(MYDEBUG) SCRUTE( libname_str );
5279 libname = string( libname_str );
5280 delete [] libname_str;
5281 aDataset->CloseOnDisk();
5283 // --> get algorithm data
5284 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5285 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5286 aDataset->OpenOnDisk();
5287 size = aDataset->GetSize();
5288 char* hypdata_str = new char[ size ];
5289 aDataset->ReadFromDisk( hypdata_str );
5290 if(MYDEBUG) SCRUTE( hypdata_str );
5291 hypdata = string( hypdata_str );
5292 delete [] hypdata_str;
5293 aDataset->CloseOnDisk();
5296 // close algorithm HDF group
5297 aGroup->CloseOnDisk();
5299 // --> restore algorithm from data
5300 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5301 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5302 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5303 SMESH::SMESH_Hypothesis_var myHyp;
5305 try { // protect persistence mechanism against exceptions
5306 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5308 catch( SALOME::SALOME_Exception& ex )
5310 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5313 INFOS( "Exception during hypothesis creation" );
5316 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5318 //myImpl->LoadFrom( hypdata.c_str() );
5319 hypDataList.push_back( make_pair( myImpl, hypdata ));
5320 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5321 int newId = myStudyContext->findId( iorString.in() );
5322 myStudyContext->mapOldToNew( id, newId );
5325 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5329 // close algorithms root HDF group
5330 aTopGroup->CloseOnDisk();
5334 // --> the rest groups should be meshes
5335 for ( int i = 0; i < aNbGroups; i++ ) {
5336 // identify next group
5337 char meshName[ HDF_NAME_MAX_LEN+1 ];
5338 aFile->InternalObjectIndentify( i, meshName );
5340 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5342 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5346 // open mesh HDF group
5347 aTopGroup = new HDFgroup( meshName, aFile );
5348 aTopGroup->OpenOnDisk();
5350 // get number of child HDF objects
5351 int aNbObjects = aTopGroup->nInternalObjects();
5352 if ( aNbObjects > 0 ) {
5354 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5355 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5356 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5357 if ( !myNewMeshImpl )
5359 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5361 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5362 int newId = myStudyContext->findId( iorString.in() );
5363 myStudyContext->mapOldToNew( id, newId );
5366 // try to read and set auto color flag
5367 char aMeshAutoColorName[ 30 ];
5368 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5369 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5371 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5372 aDataset->OpenOnDisk();
5373 size = aDataset->GetSize();
5374 int* anAutoColor = new int[ size ];
5375 aDataset->ReadFromDisk( anAutoColor );
5376 aDataset->CloseOnDisk();
5377 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5378 delete [] anAutoColor;
5381 // try to read and set reference to shape
5382 GEOM::GEOM_Object_var aShapeObject;
5383 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5384 // load mesh "Ref on shape" - it's an entry to SObject
5385 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5386 aDataset->OpenOnDisk();
5387 size = aDataset->GetSize();
5388 char* refFromFile = new char[ size ];
5389 aDataset->ReadFromDisk( refFromFile );
5390 aDataset->CloseOnDisk();
5391 if ( strlen( refFromFile ) > 0 ) {
5392 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5393 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5394 if ( !CORBA::is_nil( shapeObject ) ) {
5395 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5396 if ( !aShapeObject->_is_nil() )
5397 myNewMeshImpl->SetShape( aShapeObject );
5400 delete [] refFromFile;
5403 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5404 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5406 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5407 aDataset->OpenOnDisk();
5408 size = aDataset->GetSize();
5409 int* meshPersistentId = new int[ size ];
5410 aDataset->ReadFromDisk( meshPersistentId );
5411 aDataset->CloseOnDisk();
5412 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5413 delete [] meshPersistentId;
5416 // Restore SMESH_Mesh_i::_mainShapeTick
5417 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5419 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5420 aDataset->OpenOnDisk();
5421 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5422 aDataset->ReadFromDisk( shapeTick );
5423 aDataset->CloseOnDisk();
5426 // Restore file info
5427 if ( aTopGroup->ExistInternalObject( "file info" ))
5429 aDataset = new HDFdataset( "file info", aTopGroup );
5430 aDataset->OpenOnDisk();
5431 size = aDataset->GetSize();
5432 std::string info( size, ' ');
5433 aDataset->ReadFromDisk( (char*) info.data() );
5434 aDataset->CloseOnDisk();
5435 myNewMeshImpl->FileInfoFromString( info );
5441 // As all object that can be referred by hypothesis are created,
5442 // we can restore hypothesis data
5444 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5445 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5447 SMESH_Hypothesis_i* hyp = hyp_data->first;
5448 string & data = hyp_data->second;
5449 hyp->LoadFrom( data.c_str() );
5452 // Restore the rest mesh data
5454 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5455 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5457 aTopGroup = meshi_group->second;
5458 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5459 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5460 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5462 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5463 bool hasData = false;
5466 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5467 int newId = myStudyContext->findId( iorString.in() );
5468 int meshOldId = myStudyContext->getOldId( newId );
5470 // try to find mesh data dataset
5471 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5472 // load mesh "has data" flag
5473 aDataset = new HDFdataset( "Has data", aTopGroup );
5474 aDataset->OpenOnDisk();
5475 size = aDataset->GetSize();
5476 char* strHasData = new char[ size ];
5477 aDataset->ReadFromDisk( strHasData );
5478 aDataset->CloseOnDisk();
5479 if ( strcmp( strHasData, "1") == 0 ) {
5482 delete [] strHasData;
5485 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5486 // nodes and elements are not yet put into sub-meshes)
5487 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5488 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5489 aGroup->OpenOnDisk();
5490 // get number of applied algorithms
5491 int aNbSubObjects = aGroup->nInternalObjects();
5492 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5493 for ( int j = 0; j < aNbSubObjects; j++ ) {
5494 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5495 aGroup->InternalObjectIndentify( j, name_dataset );
5496 // check if it is an algorithm
5497 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5498 aDataset = new HDFdataset( name_dataset, aGroup );
5499 aDataset->OpenOnDisk();
5500 size = aDataset->GetSize();
5501 char* refFromFile = new char[ size ];
5502 aDataset->ReadFromDisk( refFromFile );
5503 aDataset->CloseOnDisk();
5504 // san - it is impossible to recover applied algorithms using their entries within Load() method
5505 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5506 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5507 int id = atoi( refFromFile );
5508 delete [] refFromFile;
5509 string anIOR = myStudyContext->getIORbyOldId( id );
5510 if ( !anIOR.empty() ) {
5511 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5512 if ( !CORBA::is_nil( hypObject ) ) {
5513 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5514 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5515 || !myNewMeshImpl->HasShapeToMesh()) )
5516 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5521 aGroup->CloseOnDisk();
5524 // try to get applied hypotheses
5525 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5526 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5527 aGroup->OpenOnDisk();
5528 // get number of applied hypotheses
5529 int aNbSubObjects = aGroup->nInternalObjects();
5530 for ( int j = 0; j < aNbSubObjects; j++ ) {
5531 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5532 aGroup->InternalObjectIndentify( j, name_dataset );
5533 // check if it is a hypothesis
5534 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5535 aDataset = new HDFdataset( name_dataset, aGroup );
5536 aDataset->OpenOnDisk();
5537 size = aDataset->GetSize();
5538 char* refFromFile = new char[ size ];
5539 aDataset->ReadFromDisk( refFromFile );
5540 aDataset->CloseOnDisk();
5541 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5542 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5543 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5544 int id = atoi( refFromFile );
5545 delete [] refFromFile;
5546 string anIOR = myStudyContext->getIORbyOldId( id );
5547 if ( !anIOR.empty() ) {
5548 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5549 if ( !CORBA::is_nil( hypObject ) ) {
5550 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5551 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5552 || !myNewMeshImpl->HasShapeToMesh()) )
5553 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5558 aGroup->CloseOnDisk();
5561 // --> try to find SUB-MESHES containers for each type of submesh
5562 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5563 const char* name_meshgroup = 0;
5564 if ( j == GetSubMeshOnVertexTag() )
5565 name_meshgroup = "SubMeshes On Vertex";
5566 else if ( j == GetSubMeshOnEdgeTag() )
5567 name_meshgroup = "SubMeshes On Edge";
5568 else if ( j == GetSubMeshOnWireTag() )
5569 name_meshgroup = "SubMeshes On Wire";
5570 else if ( j == GetSubMeshOnFaceTag() )
5571 name_meshgroup = "SubMeshes On Face";
5572 else if ( j == GetSubMeshOnShellTag() )
5573 name_meshgroup = "SubMeshes On Shell";
5574 else if ( j == GetSubMeshOnSolidTag() )
5575 name_meshgroup = "SubMeshes On Solid";
5576 else if ( j == GetSubMeshOnCompoundTag() )
5577 name_meshgroup = "SubMeshes On Compound";
5579 // try to get submeshes container HDF group
5580 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5581 // open submeshes containers HDF group
5582 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5583 aGroup->OpenOnDisk();
5585 // get number of submeshes
5586 int aNbSubMeshes = aGroup->nInternalObjects();
5587 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5589 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5590 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5591 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5592 // --> get submesh id
5593 int subid = atoi( name_submeshgroup + 7 );
5596 // open submesh HDF group
5597 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5598 aSubGroup->OpenOnDisk();
5600 // try to read and set reference to subshape
5601 GEOM::GEOM_Object_var aSubShapeObject;
5602 SMESH::SMESH_subMesh_var aSubMesh;
5604 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5605 // load submesh "Ref on shape" - it's an entry to SObject
5606 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5607 aDataset->OpenOnDisk();
5608 size = aDataset->GetSize();
5609 char* refFromFile = new char[ size ];
5610 aDataset->ReadFromDisk( refFromFile );
5611 aDataset->CloseOnDisk();
5612 if ( strlen( refFromFile ) > 0 ) {
5613 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5614 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5615 if ( !CORBA::is_nil( subShapeObject ) ) {
5616 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5617 if ( !aSubShapeObject->_is_nil() )
5618 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5619 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5620 if ( aSubMesh->_is_nil() )
5622 string iorSubString = GetORB()->object_to_string( aSubMesh );
5623 int newSubId = myStudyContext->findId( iorSubString );
5624 myStudyContext->mapOldToNew( subid, newSubId );
5627 delete [] refFromFile;
5630 if ( aSubMesh->_is_nil() )
5633 // try to get applied algorithms
5634 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5635 // open "applied algorithms" HDF group
5636 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5637 aSubSubGroup->OpenOnDisk();
5638 // get number of applied algorithms
5639 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5640 for ( int l = 0; l < aNbSubObjects; l++ ) {
5641 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5642 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5643 // check if it is an algorithm
5644 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5645 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5646 aDataset->OpenOnDisk();
5647 size = aDataset->GetSize();
5648 char* refFromFile = new char[ size ];
5649 aDataset->ReadFromDisk( refFromFile );
5650 aDataset->CloseOnDisk();
5652 int id = atoi( refFromFile );
5653 string anIOR = myStudyContext->getIORbyOldId( id );
5654 if ( !anIOR.empty() ) {
5655 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5656 if ( !CORBA::is_nil( hypObject ) ) {
5657 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5658 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5659 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5662 delete [] refFromFile;
5665 // close "applied algorithms" HDF group
5666 aSubSubGroup->CloseOnDisk();
5669 // try to get applied hypotheses
5670 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5671 // open "applied hypotheses" HDF group
5672 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5673 aSubSubGroup->OpenOnDisk();
5674 // get number of applied hypotheses
5675 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5676 for ( int l = 0; l < aNbSubObjects; l++ ) {
5677 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5678 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5679 // check if it is a hypothesis
5680 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5681 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5682 aDataset->OpenOnDisk();
5683 size = aDataset->GetSize();
5684 char* refFromFile = new char[ size ];
5685 aDataset->ReadFromDisk( refFromFile );
5686 aDataset->CloseOnDisk();
5688 int id = atoi( refFromFile );
5689 string anIOR = myStudyContext->getIORbyOldId( id );
5690 if ( !anIOR.empty() ) {
5691 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5692 if ( !CORBA::is_nil( hypObject ) ) {
5693 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5694 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5695 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5698 delete [] refFromFile;
5701 // close "APPLIED HYPOTHESES" hdf group
5702 aSubSubGroup->CloseOnDisk();
5705 // close SUB-MESH hdf group
5706 aSubGroup->CloseOnDisk();
5709 // close SUB-MESHES containers hdf group
5710 aGroup->CloseOnDisk();
5714 // try to get GROUPS
5715 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5716 char name_group[ 30 ];
5717 if ( ii == GetNodeGroupsTag() )
5718 strcpy( name_group, "Groups of Nodes" );
5719 else if ( ii == GetEdgeGroupsTag() )
5720 strcpy( name_group, "Groups of Edges" );
5721 else if ( ii == GetFaceGroupsTag() )
5722 strcpy( name_group, "Groups of Faces" );
5723 else if ( ii == GetVolumeGroupsTag() )
5724 strcpy( name_group, "Groups of Volumes" );
5725 else if ( ii == Get0DElementsGroupsTag() )
5726 strcpy( name_group, "Groups of 0D Elements" );
5727 else if ( ii == GetBallElementsGroupsTag() )
5728 strcpy( name_group, "Groups of Balls" );
5730 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5731 aGroup = new HDFgroup( name_group, aTopGroup );
5732 aGroup->OpenOnDisk();
5733 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5734 // within aGroup->ExistInternalObject( name )
5735 std::vector< std::string > subNames;
5736 TColStd_MapOfAsciiString mapOfNames;
5737 aGroup->GetAllObjects( subNames );
5738 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5739 mapOfNames.Add( subNames[ iN ].c_str() );
5741 for ( size_t j = 0; j < subNames.size(); j++ ) {
5742 const std::string& name_dataset = subNames[ j ];
5743 // check if it is a group
5744 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5747 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5750 int groupID = -1; // group local ID (also persistent)
5752 groupID = atoi( endptr + 1 );
5753 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5754 aDataset->OpenOnDisk();
5756 // Retrieve actual group name
5757 size = aDataset->GetSize();
5758 char* nameFromFile = new char[ size ];
5759 aDataset->ReadFromDisk( nameFromFile );
5760 aDataset->CloseOnDisk();
5762 // Try to find a shape reference
5763 TopoDS_Shape aShape;
5764 char aRefName[ 30 ];
5765 sprintf( aRefName, "Ref on shape %d", subid);
5766 if ( mapOfNames.Contains( aRefName ))
5768 // load mesh "Ref on shape" - it's an entry to SObject
5769 aDataset = new HDFdataset( aRefName, aGroup );
5770 aDataset->OpenOnDisk();
5771 size = aDataset->GetSize();
5772 char* refFromFile = new char[ size ];
5773 aDataset->ReadFromDisk( refFromFile );
5774 aDataset->CloseOnDisk();
5775 if ( strlen( refFromFile ) > 0 ) {
5776 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5777 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5778 if ( !CORBA::is_nil( shapeObject ) ) {
5779 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5780 if ( !aShapeObject->_is_nil() )
5781 aShape = GeomObjectToShape( aShapeObject );
5784 delete [] refFromFile;
5786 // Try to read a filter of SMESH_GroupOnFilter
5787 SMESH::Filter_var filter;
5788 SMESH_PredicatePtr predicate;
5789 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5790 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5792 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5793 aDataset->OpenOnDisk();
5794 size = aDataset->GetSize();
5795 char* persistStr = new char[ size ];
5796 aDataset->ReadFromDisk( persistStr );
5797 aDataset->CloseOnDisk();
5798 if ( strlen( persistStr ) > 0 ) {
5799 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5800 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5801 filters.push_back( filter );
5803 delete [] persistStr;
5806 // Create group servant
5807 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5808 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5809 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5810 delete [] nameFromFile;
5811 // Obtain a SMESHDS_Group object
5812 if ( aNewGroup->_is_nil() )
5815 string iorSubString = GetORB()->object_to_string( aNewGroup );
5816 int newSubId = myStudyContext->findId( iorSubString );
5817 myStudyContext->mapOldToNew( subid, newSubId );
5819 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5823 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5824 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5826 aFilterGroup->SetFilter( filter );
5827 filter->UnRegister();
5829 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5830 if ( !aGroupBaseDS )
5833 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5836 // Read color of the group
5837 char aGroupColorName[ 30 ];
5838 sprintf( aGroupColorName, "ColorGroup %d", subid);
5839 if ( mapOfNames.Contains( aGroupColorName ))
5841 aDataset = new HDFdataset( aGroupColorName, aGroup );
5842 aDataset->OpenOnDisk();
5843 size = aDataset->GetSize();
5844 double* anRGB = new double[ size ];
5845 aDataset->ReadFromDisk( anRGB );
5846 aDataset->CloseOnDisk();
5847 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5848 aGroupBaseDS->SetColor( aColor );
5853 aGroup->CloseOnDisk();
5857 // instead of reading mesh data, we read only brief information of all
5858 // objects: mesh, groups, sub-meshes (issue 0021208)
5861 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5862 meshfile.ToCString(), filename.ToCString(),
5866 // read Sub-Mesh ORDER if any
5867 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5868 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5869 aDataset->OpenOnDisk();
5870 size = aDataset->GetSize();
5871 int* smIDs = new int[ size ];
5872 aDataset->ReadFromDisk( smIDs );
5873 aDataset->CloseOnDisk();
5874 TListOfListOfInt anOrderIds;
5875 anOrderIds.push_back( TListOfInt() );
5876 for ( int i = 0; i < size; i++ )
5877 if ( smIDs[ i ] < 0 ) // is separator
5878 anOrderIds.push_back( TListOfInt() );
5880 anOrderIds.back().push_back(smIDs[ i ]);
5882 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5887 // update hyps needing full mesh data restored (issue 20918)
5888 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5890 SMESH_Hypothesis_i* hyp = hyp_data->first;
5891 hyp->UpdateAsMeshesRestored();
5894 // notify algos on completed restoration to set sub-mesh event listeners
5895 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5897 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5898 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5900 TopoDS_Shape myLocShape;
5901 if(myLocMesh.HasShapeToMesh())
5902 myLocShape = myLocMesh.GetShapeToMesh();
5904 myLocShape = SMESH_Mesh::PseudoShape();
5906 myLocMesh.GetSubMesh(myLocShape)->
5907 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5910 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5911 list< SMESH::Filter_var >::iterator f = filters.begin();
5912 for ( ; f != filters.end(); ++f )
5913 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5914 fi->FindBaseObjects();
5919 aTopGroup->CloseOnDisk();
5922 aFile->CloseOnDisk();
5925 // Remove temporary files created from the stream
5928 SMESH_File meshFile( meshfile.ToCString() );
5929 if ( !meshFile ) // no meshfile exists
5931 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5935 Engines::Container_var container = GetContainerRef();
5936 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5938 container_i->registerTemporaryFile( filename.ToCString() );
5939 container_i->registerTemporaryFile( meshfile.ToCString() );
5940 container_i->registerTemporaryFile( tmpDir.ToCString() );
5944 pd << ""; // prevent optimizing pd out
5946 // creation of tree nodes for all data objects in the study
5947 // to support tree representation customization and drag-n-drop:
5948 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5949 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5950 useCaseBuilder->SetRootCurrent();
5951 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5952 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5953 for (it->InitEx(true); it->More(); it->Next()) {
5954 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5961 //=============================================================================
5963 * SMESH_Gen_i::LoadASCII
5965 * Load SMESH module's data in ASCII format
5967 //=============================================================================
5969 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5970 const SALOMEDS::TMPFile& theStream,
5972 bool isMultiFile ) {
5973 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5974 return Load( theComponent, theStream, theURL, isMultiFile );
5976 //before call main ::Load method it's need for decipher text format to
5977 //binary ( "|xx" => x' )
5978 int size = theStream.length();
5979 if ( int((size / 3 )*3) != size ) //error size of buffer
5982 int real_size = int(size / 3);
5984 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5987 unsigned int c = -1;
5988 for ( int i = 0; i < real_size; i++ )
5990 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5991 sscanf( tmp, "%x", &c );
5992 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5995 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5997 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6000 //=============================================================================
6002 * SMESH_Gen_i::Close
6004 * Clears study-connected data when it is closed
6006 //=============================================================================
6008 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6010 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6012 // Clear study contexts data
6013 myStudyContext->Clear();
6015 // remove the tmp files meshes are loaded from
6016 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6018 // Clean trace of API methods calls
6024 //=============================================================================
6026 * SMESH_Gen_i::ComponentDataType
6028 * Get component data type
6030 //=============================================================================
6032 char* SMESH_Gen_i::ComponentDataType()
6034 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6035 return CORBA::string_dup( "SMESH" );
6039 //=============================================================================
6041 * SMESH_Gen_i::IORToLocalPersistentID
6043 * Transform data from transient form to persistent
6045 //=============================================================================
6047 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6048 const char* IORString,
6049 CORBA::Boolean /*isMultiFile*/,
6050 CORBA::Boolean /*isASCII*/ )
6052 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6054 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6055 int anId = myStudyContext->findId( IORString );
6057 if(MYDEBUG) MESSAGE( "VSR " << anId )
6059 sprintf( strId, "%d", anId );
6060 return CORBA::string_dup( strId );
6063 return CORBA::string_dup( "" );
6066 //=============================================================================
6068 * SMESH_Gen_i::LocalPersistentIDToIOR
6070 * Transform data from persistent form to transient
6072 //=============================================================================
6074 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6075 const char* aLocalPersistentID,
6076 CORBA::Boolean /*isMultiFile*/,
6077 CORBA::Boolean /*isASCII*/ )
6079 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6081 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6082 int anId = atoi( aLocalPersistentID );
6083 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6085 return CORBA::string_dup( "" );
6088 //=======================================================================
6089 //function : RegisterObject
6091 //=======================================================================
6093 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6095 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6096 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6097 return myStudyContext->addObject( string( iorString.in() ) );
6102 //================================================================================
6104 * \brief Return id of registered object
6105 * \param theObject - the Object
6106 * \retval int - Object id
6108 //================================================================================
6110 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6112 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6113 string iorString = GetORB()->object_to_string( theObject );
6114 return myStudyContext->findId( iorString );
6119 //=============================================================================
6121 * SMESH_Gen_i::SetName
6123 * Set a new object name
6125 //=============================================================================
6126 void SMESH_Gen_i::SetName(const char* theIOR,
6127 const char* theName)
6129 if ( theIOR && strcmp( theIOR, "" ) ) {
6130 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6131 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6132 if ( !aSO->_is_nil() ) {
6133 SetName( aSO, theName );
6138 // Version information
6139 char* SMESH_Gen_i::getVersion()
6141 #if SMESH_DEVELOPMENT
6142 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6144 return CORBA::string_dup(SMESH_VERSION_STR);
6148 //=================================================================================
6149 // function : Move()
6150 // purpose : Moves objects to the specified position.
6151 // Is used in the drag-n-drop functionality.
6152 //=================================================================================
6153 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6154 SALOMEDS::SObject_ptr where,
6157 if ( CORBA::is_nil( where ) ) return;
6159 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6160 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6161 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6162 std::string dataType = father->ComponentDataType();
6163 if ( dataType != "SMESH" ) return; // not a SMESH component
6165 SALOMEDS::SObject_var objAfter;
6166 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6167 // insert at given row -> find insertion position
6168 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6170 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6171 if ( i == row && useCaseIt->More() ) {
6172 objAfter = useCaseIt->Value();
6176 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6177 SALOMEDS::SObject_var sobj = what[i];
6178 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6179 // insert the object to the use case tree
6180 if ( !CORBA::is_nil( objAfter ) )
6181 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6183 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6186 //================================================================================
6188 * \brief Returns true if algorithm can be used to mesh a given geometry
6189 * \param [in] theAlgoType - the algorithm type
6190 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6191 * \param [in] theGeomObject - the geometry to mesh
6192 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6193 * else, returns \c True if at least one shape is meshable
6194 * \return CORBA::Boolean - can or can't
6196 //================================================================================
6198 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6199 const char* theLibName,
6200 GEOM::GEOM_Object_ptr theGeomObject,
6201 CORBA::Boolean toCheckAll)
6205 std::string aPlatformLibName;
6206 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6207 GenericHypothesisCreator_i* aCreator =
6208 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6211 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6212 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6213 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6220 SMESH_CATCH( SMESH::doNothing );
6223 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6228 //=================================================================================
6229 // function : GetInsideSphere
6230 // purpose : Collect indices of elements, which are located inside the sphere
6231 //=================================================================================
6232 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6233 SMESH::ElementType theElemType,
6239 SMESH::long_array_var aResult = new SMESH::long_array();
6240 if ( meshPart->_is_nil() )
6241 return aResult._retn();
6243 // 1. Create geometrical object
6244 gp_Pnt aP( theX, theY, theZ );
6245 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6247 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6249 if ( lst.size() > 0 ) {
6250 aResult->length( lst.size() );
6251 for ( size_t i = 0; i < lst.size(); i++ ) {
6252 aResult[i] = lst[i];
6255 return aResult._retn();
6258 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6259 SMESH::ElementType theElemType,
6260 CORBA::Double theX1,
6261 CORBA::Double theY1,
6262 CORBA::Double theZ1,
6263 CORBA::Double theX2,
6264 CORBA::Double theY2,
6265 CORBA::Double theZ2) {
6266 SMESH::long_array_var aResult = new SMESH::long_array();
6267 if( meshPart->_is_nil() )
6268 return aResult._retn();
6270 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6272 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6274 if( lst.size() > 0 ) {
6275 aResult->length( lst.size() );
6276 for ( size_t i = 0; i < lst.size(); i++ ) {
6277 aResult[i] = lst[i];
6280 return aResult._retn();
6283 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6284 SMESH::ElementType theElemType,
6288 CORBA::Double theDX,
6289 CORBA::Double theDY,
6290 CORBA::Double theDZ,
6292 CORBA::Double theR ){
6293 SMESH::long_array_var aResult = new SMESH::long_array();
6294 if( meshPart->_is_nil() )
6295 return aResult._retn();
6297 gp_Pnt aP( theX, theY, theZ );
6298 gp_Vec aV( theDX, theDY, theDZ );
6299 gp_Ax2 anAxes (aP, aV);
6301 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6303 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6305 if( lst.size() > 0 ) {
6306 aResult->length( lst.size() );
6307 for ( size_t i = 0; i < lst.size(); i++ ) {
6308 aResult[i] = lst[i];
6311 return aResult._retn();
6314 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6315 SMESH::ElementType theElemType,
6316 GEOM::GEOM_Object_ptr theGeom,
6317 CORBA::Double theTolerance ) {
6318 SMESH::long_array_var aResult = new SMESH::long_array();
6319 if( meshPart->_is_nil() || theGeom->_is_nil() )
6320 return aResult._retn();
6322 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6324 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6326 if( lst.size() > 0 ) {
6327 aResult->length( lst.size() );
6328 for ( size_t i = 0; i < lst.size(); i++ ) {
6329 aResult[i] = lst[i];
6332 return aResult._retn();
6337 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6338 SMESH::ElementType theElemType,
6339 TopoDS_Shape& aShape,
6340 double* theTolerance) {
6342 std::vector<long> res;
6343 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6345 if ( mesh->_is_nil() )
6348 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6352 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6357 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6358 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6359 anElementsOnShape->SetAllNodes( true );
6360 anElementsOnShape->SetMesh( meshDS );
6361 anElementsOnShape->SetShape( aShape, aType );
6364 anElementsOnShape->SetTolerance(*theTolerance);
6366 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6367 if ( !msource->_is_nil() ) { // Mesh case
6368 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6370 while ( elemIt->more() ) {
6371 const SMDS_MeshElement* anElem = elemIt->next();
6372 long anId = anElem->GetID();
6373 if ( anElementsOnShape->IsSatisfy( anId ) )
6374 res.push_back( anId );
6378 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6379 if ( !gsource->_is_nil() ) {
6380 if(theElemType == SMESH::NODE) {
6381 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6382 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6383 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6384 long anId = node->GetID();
6385 if ( anElementsOnShape->IsSatisfy( anId ) )
6386 res.push_back( anId );
6389 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6390 SMESH::long_array_var elems = gsource->GetListOfID();
6391 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6392 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6393 long anId = elem->GetID();
6394 if ( anElementsOnShape->IsSatisfy( anId ) )
6395 res.push_back( anId );
6400 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6401 if ( !smsource->_is_nil() ) {
6402 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6403 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6404 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6406 long anId = elem->GetID();
6407 if ( anElementsOnShape->IsSatisfy( anId ) )
6408 res.push_back( anId );
6416 //=============================================================================
6418 * SMESHEngine_factory
6420 * C factory, accessible with dlsym, after dlopen
6422 //=============================================================================
6426 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6427 PortableServer::POA_ptr poa,
6428 PortableServer::ObjectId* contId,
6429 const char* instanceName,
6430 const char* interfaceName )
6432 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6433 if(MYDEBUG) SCRUTE(interfaceName);
6434 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6435 return aSMESHGen->getId() ;