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 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
738 //================================================================================
740 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
742 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
743 SALOMEDS::GenericAttribute_wrap attr;
744 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
746 SALOMEDS::AttributePixMap_wrap pm = attr;
747 CORBA::String_var ico = pm->GetPixMap();
748 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
753 //=================================================================================
754 // function : hasObjectInfo()
755 // purpose : shows if module provides information for its objects
756 //=================================================================================
758 bool SMESH_Gen_i::hasObjectInfo()
763 //=================================================================================
764 // function : getObjectInfo()
765 // purpose : returns an information for a given object by its entry
766 //=================================================================================
768 char* SMESH_Gen_i::getObjectInfo( const char* entry )
770 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
771 // for the rest, "module 'SMESH', ID=0:1:2:*"
775 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
776 CORBA::Object_var obj = SObjectToObject( so );
777 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
778 if ( isGeomModifIcon( mesh ))
780 txt << "The geometry was changed and the mesh needs to be recomputed";
785 CORBA::String_var compType = ComponentDataType();
786 txt << "module '" << compType << "', ID=" << entry;
788 return CORBA::string_dup( txt );
791 //=============================================================================
793 * SMESH_Gen_i::GetStudyContext
797 //=============================================================================
798 StudyContext* SMESH_Gen_i::GetStudyContext()
800 return myStudyContext;
803 //=============================================================================
805 * SMESH_Gen_i::CreateHypothesis
807 * Create hypothesis/algorithm of given type and publish it in the study
809 //=============================================================================
811 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
812 const char* theLibName )
813 throw ( SALOME::SALOME_Exception )
815 Unexpect aCatch(SALOME_SalomeException);
816 // Create hypothesis/algorithm
817 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
819 // Publish hypothesis/algorithm in the study
820 if ( CanPublishInStudy( hyp ) ) {
821 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
822 if ( !aSO->_is_nil() ) {
823 // Update Python script
824 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
825 << theHypName << "', '" << theLibName << "')";
832 //================================================================================
834 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
835 * existing on the given geometry or to size of the geometry.
836 * \param theHypType - hypothesis type name
837 * \param theLibName - plugin library name
838 * \param theMesh - The mesh of interest
839 * \param theGeom - The shape to get parameter values from
840 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
841 * in a study and used to compute the mesh, or a temporary one created just to pass
844 //================================================================================
846 SMESH::SMESH_Hypothesis_ptr
847 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
848 const char* theLibName,
849 SMESH::SMESH_Mesh_ptr theMesh,
850 GEOM::GEOM_Object_ptr theGeom,
851 CORBA::Boolean byMesh)
852 throw ( SALOME::SALOME_Exception )
854 Unexpect aCatch(SALOME_SalomeException);
855 if ( byMesh && CORBA::is_nil( theMesh ) )
856 return SMESH::SMESH_Hypothesis::_nil();
857 if ( byMesh && CORBA::is_nil( theGeom ) )
858 return SMESH::SMESH_Hypothesis::_nil();
860 // -----------------------------------------------
861 // find hypothesis used to mesh theGeom
862 // -----------------------------------------------
864 // get mesh and shape
865 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
866 TopoDS_Shape shape = GeomObjectToShape( theGeom );
867 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
868 return SMESH::SMESH_Hypothesis::_nil();
869 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
871 // create a temporary hypothesis to know its dimension
872 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
873 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
875 return SMESH::SMESH_Hypothesis::_nil();
876 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
879 // look for a hypothesis of theHypType used to mesh the shape
880 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
883 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
884 int nbLocalHyps = aHypList->length();
885 for ( int i = 0; i < nbLocalHyps; i++ ) {
886 CORBA::String_var hypName = aHypList[i]->GetName();
887 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
888 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
890 // check super shapes
891 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
892 while ( nbLocalHyps == 0 && itShape.More() ) {
893 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
894 if ( ! CORBA::is_nil( geomObj )) {
895 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
896 nbLocalHyps = aHypList->length();
897 for ( int i = 0; i < nbLocalHyps; i++ )
898 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
899 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
905 // let the temporary hypothesis find out somehow parameter values by mesh
906 if ( hyp->SetParametersByMesh( mesh, shape ))
907 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
912 diagonal = mesh->GetShapeDiagonalSize();
914 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
915 ::SMESH_Hypothesis::TDefaults dflts;
916 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
917 dflts._nbSegments = myGen.GetDefaultNbSegments();
918 dflts._shape = &shape;
919 // let the temporary hypothesis initialize it's values
920 if ( hyp->SetParametersByDefaults( dflts, mesh ))
921 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
924 return SMESH::SMESH_Hypothesis::_nil();
927 //=============================================================================
929 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
930 * \param [in] theHyp - the hypothesis of interest
931 * \param [out] theMesh - the sole mesh using \a theHyp
932 * \param [out] theShape - the sole geometry \a theHyp is assigned to
933 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
935 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
936 * considered as SAME sub-mesh => result is \c true.
937 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
938 * a shape to which an hyp being edited is assigned.
940 //=============================================================================
942 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
943 SMESH::SMESH_Mesh_out theMesh,
944 GEOM::GEOM_Object_out theShape)
946 if ( CORBA::is_nil( theHyp ))
949 // get Mesh component SO
950 CORBA::String_var compDataType = ComponentDataType();
951 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
952 if ( CORBA::is_nil( comp ))
955 // look for child SO of meshes
956 SMESH::SMESH_Mesh_var foundMesh;
957 TopoDS_Shape foundShape;
959 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
960 for ( ; meshIter->More() && isSole; meshIter->Next() )
962 SALOMEDS::SObject_wrap curSO = meshIter->Value();
963 CORBA::Object_var obj = SObjectToObject( curSO );
964 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
968 // look for a sole shape where theHyp is assigned
969 bool isHypFound = false;
970 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
971 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
972 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
974 const THypList& hyps = s2hypsIt.Value();
975 THypList::const_iterator h = hyps.begin();
976 for ( ; h != hyps.end(); ++h )
977 if ( (*h)->GetID() == theHyp->GetId() )
979 if ( h != hyps.end()) // theHyp found
982 if ( ! foundShape.IsNull() &&
983 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
985 foundShape.Nullify();
989 foundShape = s2hypsIt.Key();
991 } // loop on assigned hyps
993 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
995 if ( !foundMesh->_is_nil() ) // not a sole mesh
997 if ( !foundMesh->HasShapeToMesh() ||
998 !mesh_i ->HasShapeToMesh() )
1000 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1004 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1005 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1006 isSole = s1->IsSame( s2 );
1009 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1015 ! foundMesh->_is_nil() &&
1016 ! foundShape.IsNull() )
1018 theMesh = foundMesh._retn();
1019 theShape = ShapeToGeomObject( foundShape );
1020 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1025 //=============================================================================
1027 * Sets number of segments per diagonal of boundary box of geometry by which
1028 * default segment length of appropriate 1D hypotheses is defined
1030 //=============================================================================
1032 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1033 throw ( SALOME::SALOME_Exception )
1035 if ( theNbSegments > 0 )
1036 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1038 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1040 //=============================================================================
1042 * \brief Sets default number of segments per edge
1044 //=============================================================================
1045 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1046 throw ( SALOME::SALOME_Exception )
1048 if ( theNbSegments > 0 )
1049 myGen.SetDefaultNbSegments( int(theNbSegments) );
1051 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1054 //=============================================================================
1058 //=============================================================================
1060 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1062 if ( name && value && strlen( value ) > 0 )
1065 if ( strcmp(name, "historical_python_dump") == 0 )
1067 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1068 msgToGUI = "preferences/SMESH/historical_python_dump/";
1069 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1071 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1073 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1074 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1075 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1077 else if ( strcmp(name, "default_grp_color") == 0 )
1081 // color must be presented as a string of following form:
1082 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1083 str = str.substr(1);
1084 for ( size_t i = 0; i < str.length()/2; i++ )
1085 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1086 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1088 else if ( value ) { // rgb color ("255,170,0", for example)
1089 string tempValue( value );
1090 char* colorValue = strtok( &tempValue[0], "," );
1091 while ( colorValue != NULL ) {
1092 int c_value = atoi( colorValue );
1093 if ( c_value >= 0 && c_value <= 255 )
1094 color.push_back( c_value );
1095 colorValue = strtok( NULL, "," );
1098 if ( color.size() == 3 ) { // color must have three valid component
1099 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1100 myDefaultGroupColor = value;
1101 msgToGUI = "preferences/SMESH/default_grp_color/";
1106 // update preferences in case if SetOption() is invoked from python console
1107 if ( !msgToGUI.empty() )
1109 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1110 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1111 if ( !CORBA::is_nil( session ) )
1112 session->emitMessageOneWay(msgToGUI.c_str());
1117 //=============================================================================
1119 Return an option value
1121 //=============================================================================
1123 char* SMESH_Gen_i::GetOption(const char* name)
1127 if ( strcmp(name, "historical_python_dump") == 0 )
1129 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1131 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1133 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1135 if ( strcmp(name, "default_grp_color") == 0 )
1137 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1140 return CORBA::string_dup( "" );
1143 //=============================================================================
1145 * SMESH_Gen_i::CreateMesh
1147 * Create empty mesh on a shape and publish it in the study
1149 //=============================================================================
1151 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1152 throw ( SALOME::SALOME_Exception )
1154 Unexpect aCatch(SALOME_SalomeException);
1155 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1157 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1159 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1160 ASSERT( meshServant );
1161 meshServant->SetShape( theShapeObject );
1163 // publish mesh in the study
1164 if ( CanPublishInStudy( mesh ) ) {
1165 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1166 aStudyBuilder->NewCommand(); // There is a transaction
1167 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1168 aStudyBuilder->CommitCommand();
1169 if ( !aSO->_is_nil() ) {
1170 // Update Python script
1171 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1175 return mesh._retn();
1178 //=============================================================================
1180 * SMESH_Gen_i::CreateEmptyMesh
1184 //=============================================================================
1186 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1187 throw ( SALOME::SALOME_Exception )
1189 Unexpect aCatch(SALOME_SalomeException);
1190 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1192 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1194 // publish mesh in the study
1195 if ( CanPublishInStudy( mesh ) ) {
1196 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1197 aStudyBuilder->NewCommand(); // There is a transaction
1198 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1199 aStudyBuilder->CommitCommand();
1200 if ( !aSO->_is_nil() ) {
1201 // Update Python script
1202 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1206 return mesh._retn();
1211 //================================================================================
1213 * \brief Throws an exception in case if the file can't be read
1215 //================================================================================
1217 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1219 SMESH_File f ( theFileName );
1222 if ( !f.error().empty() )
1223 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1225 THROW_SALOME_CORBA_EXCEPTION
1226 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1227 SALOME::BAD_PARAM );
1232 //=============================================================================
1234 * SMESH_Gen_i::CreateMeshFromUNV
1236 * Create mesh and import data from UNV file
1238 //=============================================================================
1240 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1241 throw ( SALOME::SALOME_Exception )
1243 Unexpect aCatch(SALOME_SalomeException);
1245 checkFileReadable( theFileName );
1247 SMESH::SMESH_Mesh_var aMesh = createMesh();
1249 // publish mesh in the study
1250 if ( CanPublishInStudy( aMesh ) ) {
1251 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1252 aStudyBuilder->NewCommand(); // There is a transaction
1253 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1254 aStudyBuilder->CommitCommand();
1255 if ( !aSO->_is_nil() ) {
1256 // Update Python script
1257 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1261 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1263 aServant->ImportUNVFile( theFileName );
1265 // Dump creation of groups
1266 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1268 aServant->GetImpl().GetMeshDS()->Modified();
1269 return aMesh._retn();
1272 //=============================================================================
1274 * SMESH_Gen_i::CreateMeshFromMED
1276 * Create mesh and import data from MED file
1278 //=============================================================================
1280 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1281 SMESH::DriverMED_ReadStatus& theStatus,
1282 const char* theCommandNameForPython,
1283 const char* theFileNameForPython)
1286 char bname[ _MAX_FNAME ];
1287 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1288 string aFileName = bname;
1290 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1292 // Retrieve mesh names from the file
1293 DriverMED_R_SMESHDS_Mesh myReader;
1294 myReader.SetFile( theFileName );
1295 myReader.SetMeshId( -1 );
1296 Driver_Mesh::Status aStatus;
1297 list<string> aNames = myReader.GetMeshNames(aStatus);
1298 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1299 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1301 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1304 TPythonDump aPythonDump;
1305 aPythonDump << "([";
1307 if (theStatus == SMESH::DRS_OK) {
1308 SALOMEDS::StudyBuilder_var aStudyBuilder;
1309 aStudyBuilder = getStudyServant()->NewBuilder();
1310 aStudyBuilder->NewCommand(); // There is a transaction
1312 aResult->length( aNames.size() );
1315 // Iterate through all meshes and create mesh objects
1316 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1319 if (i > 0) aPythonDump << ", ";
1322 SMESH::SMESH_Mesh_var mesh = createMesh();
1324 // publish mesh in the study
1325 SALOMEDS::SObject_wrap aSO;
1326 if ( CanPublishInStudy( mesh ) )
1327 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1328 // - as names of meshes are stored in MED file, we use them for data publishing
1329 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1330 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1333 if ( !aSO->_is_nil() ) {
1336 aPythonDump << "mesh_" << i;
1339 // Read mesh data (groups are published automatically by ImportMEDFile())
1340 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1341 ASSERT( meshServant );
1342 SMESH::DriverMED_ReadStatus status1 =
1343 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1344 if (status1 > theStatus)
1345 theStatus = status1;
1347 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1348 meshServant->GetImpl().GetMeshDS()->Modified();
1350 if ( !aStudyBuilder->_is_nil() )
1351 aStudyBuilder->CommitCommand();
1354 // Update Python script
1355 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1357 // Dump creation of groups
1358 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1359 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1361 return aResult._retn();
1364 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1365 SMESH::DriverMED_ReadStatus& theStatus)
1366 throw ( SALOME::SALOME_Exception )
1368 Unexpect aCatch(SALOME_SalomeException);
1369 checkFileReadable( theFileName );
1371 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1375 //=============================================================================
1377 * SMESH_Gen_i::CreateMeshFromSAUV
1379 * Create mesh and import data from SAUV file
1381 //=============================================================================
1383 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1384 SMESH::DriverMED_ReadStatus& theStatus)
1385 throw ( SALOME::SALOME_Exception )
1387 Unexpect aCatch(SALOME_SalomeException);
1388 checkFileReadable( theFileName );
1390 std::string sauvfilename(theFileName);
1391 std::string medfilename(theFileName);
1392 medfilename += ".med";
1395 cmd = "%PYTHONBIN% ";
1400 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1402 system(cmd.c_str());
1403 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1405 cmd = "%PYTHONBIN% ";
1410 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1412 system(cmd.c_str());
1416 //=============================================================================
1418 * SMESH_Gen_i::CreateMeshFromSTL
1420 * Create mesh and import data from STL file
1422 //=============================================================================
1424 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1425 throw ( SALOME::SALOME_Exception )
1427 Unexpect aCatch(SALOME_SalomeException);
1428 checkFileReadable( theFileName );
1430 SMESH::SMESH_Mesh_var aMesh = createMesh();
1433 char bname[ _MAX_FNAME ];
1434 _splitpath( theFileName, NULL, NULL, bname, NULL );
1435 string aFileName = bname;
1437 string aFileName = basename( const_cast<char *>(theFileName) );
1439 // publish mesh in the study
1440 if ( CanPublishInStudy( aMesh ) ) {
1441 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1442 aStudyBuilder->NewCommand(); // There is a transaction
1443 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1444 aStudyBuilder->CommitCommand();
1445 if ( !aSO->_is_nil() ) {
1446 // Update Python script
1447 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1451 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1453 aServant->ImportSTLFile( theFileName );
1454 aServant->GetImpl().GetMeshDS()->Modified();
1455 return aMesh._retn();
1458 //================================================================================
1460 * \brief Create meshes and import data from the CGSN file
1462 //================================================================================
1464 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1465 SMESH::DriverMED_ReadStatus& theStatus)
1466 throw ( SALOME::SALOME_Exception )
1468 Unexpect aCatch(SALOME_SalomeException);
1469 checkFileReadable( theFileName );
1471 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1474 // Retrieve nb meshes from the file
1475 DriverCGNS_Read myReader;
1476 myReader.SetFile( theFileName );
1477 Driver_Mesh::Status aStatus;
1478 int nbMeshes = myReader.GetNbMeshes(aStatus);
1479 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1481 aResult->length( nbMeshes );
1483 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1486 TPythonDump aPythonDump;
1487 aPythonDump << "([";
1489 if (theStatus == SMESH::DRS_OK)
1491 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1492 aStudyBuilder->NewCommand(); // There is a transaction
1496 // Iterate through all meshes and create mesh objects
1497 for ( ; i < nbMeshes; ++i )
1500 if (i > 0) aPythonDump << ", ";
1503 SMESH::SMESH_Mesh_var mesh = createMesh();
1504 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1506 // Read mesh data (groups are published automatically by ImportMEDFile())
1507 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1508 ASSERT( meshServant );
1510 SMESH::DriverMED_ReadStatus status1 =
1511 meshServant->ImportCGNSFile( theFileName, i, meshName );
1512 if (status1 > theStatus)
1513 theStatus = status1;
1515 meshServant->GetImpl().GetMeshDS()->Modified();
1516 // publish mesh in the study
1517 SALOMEDS::SObject_wrap aSO;
1518 if ( CanPublishInStudy( mesh ) )
1519 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1522 if ( !aSO->_is_nil() ) {
1526 aPythonDump << "mesh_" << i;
1529 aStudyBuilder->CommitCommand();
1532 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1534 // Dump creation of groups
1535 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1536 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1538 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1541 return aResult._retn();
1544 //================================================================================
1546 * \brief Create a mesh and import data from a GMF file
1548 //================================================================================
1550 SMESH::SMESH_Mesh_ptr
1551 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1552 CORBA::Boolean theMakeRequiredGroups,
1553 SMESH::ComputeError_out theError)
1554 throw ( SALOME::SALOME_Exception )
1556 Unexpect aCatch(SALOME_SalomeException);
1557 checkFileReadable( theFileName );
1559 SMESH::SMESH_Mesh_var aMesh = createMesh();
1561 char bname[ _MAX_FNAME ];
1562 _splitpath( theFileName, NULL, NULL, bname, NULL );
1563 string aFileName = bname;
1565 string aFileName = basename( const_cast<char *>(theFileName) );
1567 // publish mesh in the study
1568 if ( CanPublishInStudy( aMesh ) ) {
1569 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1570 aStudyBuilder->NewCommand(); // There is a transaction
1571 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1572 aStudyBuilder->CommitCommand();
1573 if ( !aSO->_is_nil() ) {
1574 // Update Python script
1575 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1576 << theFileName << "', "
1577 << theMakeRequiredGroups << " )";
1580 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1582 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1583 aServant->GetImpl().GetMeshDS()->Modified();
1584 return aMesh._retn();
1588 //=============================================================================
1590 * SMESH_Gen_i::IsReadyToCompute
1592 * Returns true if mesh contains enough data to be computed
1594 //=============================================================================
1596 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1597 GEOM::GEOM_Object_ptr theShapeObject )
1598 throw ( SALOME::SALOME_Exception )
1600 Unexpect aCatch(SALOME_SalomeException);
1601 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1603 if ( CORBA::is_nil( theShapeObject ) )
1604 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1605 SALOME::BAD_PARAM );
1607 if ( CORBA::is_nil( theMesh ) )
1608 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1609 SALOME::BAD_PARAM );
1613 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1614 ASSERT( meshServant );
1615 if ( meshServant ) {
1616 // get local TopoDS_Shape
1617 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1618 // call implementation
1619 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1620 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1623 catch ( SALOME_Exception& S_ex ) {
1624 INFOS( "catch exception "<< S_ex.what() );
1629 //================================================================================
1631 * \brief Find SObject for an algo
1633 //================================================================================
1635 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1638 SALOMEDS::Study_var aStudy = getStudyServant();
1639 if ( !aStudy->_is_nil() ) {
1640 // find algo in the study
1641 CORBA::String_var compDataType = ComponentDataType();
1642 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1643 if ( !father->_is_nil() ) {
1644 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1645 for ( ; itBig->More(); itBig->Next() ) {
1646 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1647 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1648 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1649 for ( ; algoIt->More(); algoIt->Next() ) {
1650 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1651 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1652 if ( !CORBA::is_nil( algoIOR )) {
1653 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1654 if ( impl && impl->GetImpl() == algo )
1655 return algoSO._retn();
1657 } // loop on algo SO's
1660 } // SMESH component iterator
1664 return SALOMEDS::SObject::_nil();
1667 //================================================================================
1669 * \brief Return errors of mesh computation
1671 //================================================================================
1673 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1674 GEOM::GEOM_Object_ptr theSubObject )
1675 throw ( SALOME::SALOME_Exception )
1677 Unexpect aCatch(SALOME_SalomeException);
1678 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1680 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1681 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1683 if ( CORBA::is_nil( theMesh ) )
1684 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1686 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1688 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1691 if(theMesh->HasShapeToMesh())
1692 shape = GeomObjectToShape( theSubObject );
1694 shape = SMESH_Mesh::PseudoShape();
1696 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1698 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1701 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1702 const bool includeSelf = true, complexShapeFirst = true;
1703 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1705 while ( smIt->more() )
1708 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1710 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1711 if ( error && !error->IsOK() )
1713 if ( !( error->myAlgo ) &&
1714 !( error->myAlgo = sm->GetAlgo() ))
1716 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1717 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1718 errStruct.comment = error->myComment.c_str();
1719 errStruct.subShapeID = sm->GetId();
1720 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1721 if ( !algoSO->_is_nil() ) {
1722 CORBA::String_var algoName = algoSO->GetName();
1723 errStruct.algoName = algoName;
1726 errStruct.algoName = error->myAlgo->GetName();
1728 errStruct.hasBadMesh = error->HasBadElems();
1731 error_array->length( nbErr );
1734 catch ( SALOME_Exception& S_ex ) {
1735 INFOS( "catch exception "<< S_ex.what() );
1738 return error_array._retn();
1741 //================================================================================
1743 * \brief Return mesh elements preventing computation of a subshape
1745 //================================================================================
1747 SMESH::MeshPreviewStruct*
1748 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1749 CORBA::Short theSubShapeID )
1750 throw ( SALOME::SALOME_Exception )
1752 Unexpect aCatch(SALOME_SalomeException);
1753 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1755 if ( CORBA::is_nil( theMesh ) )
1756 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1758 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1761 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1763 // mesh implementation
1764 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1765 // submesh by subshape id
1766 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1769 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1770 if ( error && error->HasBadElems() )
1772 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1773 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1775 // get nodes of elements and count elements
1776 TNode2LocalIDMap mapNode2LocalID;
1777 list< TNodeLocalID > connectivity;
1778 int i, nbElements = 0, nbConnNodes = 0;
1780 const list<const SMDS_MeshElement*>& badElems =
1781 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1782 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1783 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1784 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1786 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1787 while ( nIt->more() )
1788 connectivity.push_back
1789 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1791 // fill node coords and assign local ids to the nodes
1792 int nbNodes = mapNode2LocalID.size();
1793 result->nodesXYZ.length( nbNodes );
1794 TNodeLocalID node2ID = mapNode2LocalID.begin();
1795 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1796 node2ID->second = i;
1797 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1798 result->nodesXYZ[i].x = node->X();
1799 result->nodesXYZ[i].y = node->Y();
1800 result->nodesXYZ[i].z = node->Z();
1802 // fill connectivity
1803 result->elementConnectivities.length( nbConnNodes );
1804 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1805 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1806 result->elementConnectivities[i] = (*connIt)->second;
1808 // fill element types
1809 result->elementTypes.length( nbElements );
1810 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1812 const SMDS_MeshElement* elem = *elemIt;
1813 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1814 result->elementTypes[i].isPoly = elem->IsPoly();
1815 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1821 catch ( SALOME_Exception& S_ex ) {
1822 INFOS( "catch exception "<< S_ex.what() );
1825 return result._retn();
1828 //================================================================================
1830 * \brief Create a group of elements preventing computation of a sub-shape
1832 //================================================================================
1834 SMESH::ListOfGroups*
1835 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1836 CORBA::Short theSubShapeID,
1837 const char* theGroupName )
1838 throw ( SALOME::SALOME_Exception )
1840 Unexpect aCatch(SALOME_SalomeException);
1842 SMESH::ListOfGroups_var groups;
1844 if ( CORBA::is_nil( theMesh ) )
1845 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1848 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1850 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1851 TPythonDump() << groups << " = " << this
1852 << ".MakeGroupsOfBadInputElements( "
1853 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1856 catch ( SALOME_Exception& S_ex ) {
1857 INFOS( "catch exception "<< S_ex.what() );
1859 return groups._retn();
1862 //================================================================================
1864 * \brief Returns errors of hypotheses definition
1865 * \param theMesh - the mesh
1866 * \param theSubObject - the main or sub- shape
1867 * \retval SMESH::algo_error_array* - sequence of errors
1869 //================================================================================
1871 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1872 GEOM::GEOM_Object_ptr theSubObject )
1873 throw ( SALOME::SALOME_Exception )
1875 Unexpect aCatch(SALOME_SalomeException);
1876 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1878 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1879 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1881 if ( CORBA::is_nil( theMesh ) )
1882 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1884 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1886 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1887 ASSERT( meshServant );
1888 if ( meshServant ) {
1889 TopoDS_Shape myLocShape;
1890 if(theMesh->HasShapeToMesh())
1891 myLocShape = GeomObjectToShape( theSubObject );
1893 myLocShape = SMESH_Mesh::PseudoShape();
1895 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1896 list< ::SMESH_Gen::TAlgoStateError > error_list;
1897 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1898 // call ::SMESH_Gen::GetAlgoState()
1899 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1900 error_array->length( error_list.size() );
1902 for ( error = error_list.begin(); error != error_list.end(); ++error )
1904 // fill AlgoStateError structure
1905 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1906 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1907 errStruct.algoDim = error->_algoDim;
1908 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1909 errStruct.algoName = "";
1910 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1911 if ( !algoSO->_is_nil() ) {
1912 CORBA::String_var algoName = algoSO->GetName();
1913 errStruct.algoName = algoName.in();
1918 catch ( SALOME_Exception& S_ex ) {
1919 INFOS( "catch exception "<< S_ex.what() );
1921 return error_array._retn();
1924 //=============================================================================
1926 * SMESH_Gen_i::GetSubShapesId
1928 * Get sub-shapes unique ID's list
1930 //=============================================================================
1933 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1934 const SMESH::object_array& theListOfSubShapeObject )
1935 throw ( SALOME::SALOME_Exception )
1937 Unexpect aCatch(SALOME_SalomeException);
1938 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1940 SMESH::long_array_var shapesId = new SMESH::long_array;
1943 if ( CORBA::is_nil( theMainShapeObject ) )
1944 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1948 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1949 TopTools_IndexedMapOfShape myIndexToShape;
1950 TopExp::MapShapes(myMainShape,myIndexToShape);
1952 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1954 GEOM::GEOM_Object_var aShapeObject
1955 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1956 if ( CORBA::is_nil( aShapeObject ) )
1957 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1958 SALOME::BAD_PARAM );
1960 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1961 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1963 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1964 setId.insert(myIndexToShape.FindIndex(F));
1965 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1967 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1969 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1970 setId.insert(myIndexToShape.FindIndex(E));
1971 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1973 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1975 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1976 setId.insert(myIndexToShape.FindIndex(V));
1977 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1980 shapesId->length(setId.size());
1981 set<int>::iterator iind;
1983 for (iind = setId.begin(); iind != setId.end(); iind++)
1985 if(MYDEBUG) SCRUTE((*iind));
1986 shapesId[i] = (*iind);
1987 if(MYDEBUG) SCRUTE(shapesId[i]);
1991 catch (SALOME_Exception& S_ex)
1993 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1996 return shapesId._retn();
1999 //=============================================================================
2001 * SMESH_Gen_i::Compute
2003 * Compute mesh on a shape
2005 //=============================================================================
2007 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2008 GEOM::GEOM_Object_ptr theShapeObject )
2009 throw ( SALOME::SALOME_Exception )
2012 Unexpect aCatch(SALOME_SalomeException);
2013 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2015 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2016 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2017 SALOME::BAD_PARAM );
2019 if ( CORBA::is_nil( theMesh ) )
2020 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2021 SALOME::BAD_PARAM );
2023 // Update Python script
2024 TPythonDump() << "isDone = " << this << ".Compute( "
2025 << theMesh << ", " << theShapeObject << ")";
2029 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2030 ASSERT( meshServant );
2031 if ( meshServant ) {
2032 if ( isGeomModifIcon( theMesh ))
2033 meshServant->Clear();
2035 meshServant->Load();
2036 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2037 meshServant->CheckGeomModif();
2038 // get local TopoDS_Shape
2039 TopoDS_Shape myLocShape;
2040 if(theMesh->HasShapeToMesh())
2041 myLocShape = GeomObjectToShape( theShapeObject );
2043 myLocShape = SMESH_Mesh::PseudoShape();
2044 // call implementation compute
2045 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2046 myGen.PrepareCompute( myLocMesh, myLocShape );
2047 int how = ::SMESH_Gen::COMPACT_MESH;
2048 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2049 how |= ::SMESH_Gen::SHAPE_ONLY;
2050 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2051 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2052 myLocMesh.GetMeshDS()->Modified();
2053 UpdateIcons( theMesh );
2055 HighLightInvalid( theMesh, /*isInvalid=*/false );
2059 catch ( std::bad_alloc ) {
2060 INFOS( "Compute(): lack of memory" );
2062 catch ( SALOME_Exception& S_ex ) {
2063 INFOS( "Compute(): catch exception "<< S_ex.what() );
2066 INFOS( "Compute(): unknown exception " );
2071 //=============================================================================
2073 * SMESH_Gen_i::CancelCompute
2075 * Cancel Compute mesh on a shape
2077 //=============================================================================
2079 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2080 GEOM::GEOM_Object_ptr theShapeObject )
2082 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2084 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2085 TopoDS_Shape myLocShape;
2086 if(theMesh->HasShapeToMesh())
2087 myLocShape = GeomObjectToShape( theShapeObject );
2089 myLocShape = SMESH_Mesh::PseudoShape();
2090 myGen.CancelCompute( myLocMesh, myLocShape);
2094 //=============================================================================
2096 * SMESH_Gen_i::Precompute
2098 * Compute mesh as preview till indicated dimension on shape
2100 //=============================================================================
2102 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2103 GEOM::GEOM_Object_ptr theShapeObject,
2104 SMESH::Dimension theDimension,
2105 SMESH::long_array& theShapesId)
2106 throw ( SALOME::SALOME_Exception )
2108 Unexpect aCatch(SALOME_SalomeException);
2109 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2111 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2112 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2113 SALOME::BAD_PARAM );
2115 if ( CORBA::is_nil( theMesh ) )
2116 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2117 SALOME::BAD_PARAM );
2119 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2122 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2123 meshServant->Load();
2124 ASSERT( meshServant );
2125 if ( meshServant ) {
2126 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2127 meshServant->CheckGeomModif();
2128 // get local TopoDS_Shape
2129 TopoDS_Shape myLocShape;
2130 if(theMesh->HasShapeToMesh())
2131 myLocShape = GeomObjectToShape( theShapeObject );
2133 return result._retn();;
2135 // call implementation compute
2136 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2138 ::MeshDimension aDim = (MeshDimension)theDimension;
2139 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2141 int nbShapeId = shapeIds.size();
2142 theShapesId.length( nbShapeId );
2143 // iterates on shapes and collect mesh entities into mesh preview
2144 TSetOfInt::const_iterator idIt = shapeIds.begin();
2145 TSetOfInt::const_iterator idEnd = shapeIds.end();
2146 std::map< int, int > mapOfShIdNb;
2147 std::set< SMESH_TLink > setOfEdge;
2148 std::list< SMDSAbs_ElementType > listOfElemType;
2149 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2150 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2151 TNode2LocalIDMap mapNode2LocalID;
2152 list< TNodeLocalID > connectivity;
2153 int i, nbConnNodes = 0;
2154 std::set< const SMESH_subMesh* > setOfVSubMesh;
2155 // iterates on shapes
2156 for ( ; idIt != idEnd; idIt++ )
2158 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2160 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2161 if ( !sm || !sm->IsMeshComputed() )
2164 const TopoDS_Shape& aSh = sm->GetSubShape();
2165 const int shDim = myGen.GetShapeDim( aSh );
2166 if ( shDim < 1 || shDim > theDimension )
2169 mapOfShIdNb[ *idIt ] = 0;
2170 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2172 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2173 if ( !smDS ) continue;
2175 if ( theDimension == SMESH::DIM_2D )
2177 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2178 while ( faceIt->more() )
2180 const SMDS_MeshElement* face = faceIt->next();
2181 int aNbNode = face->NbNodes();
2183 aNbNode /= 2; // do not take into account additional middle nodes
2185 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2186 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2188 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2189 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2191 listOfElemType.push_back( SMDSAbs_Edge );
2192 connectivity.push_back
2193 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2194 connectivity.push_back
2195 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2201 else if ( theDimension == SMESH::DIM_1D )
2203 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2204 while ( nodeIt->more() )
2206 listOfElemType.push_back( SMDSAbs_Node );
2207 connectivity.push_back
2208 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2210 // add corner nodes by first vertex from edge
2211 SMESH_subMeshIteratorPtr edgeSmIt =
2212 sm->getDependsOnIterator(/*includeSelf*/false,
2213 /*complexShapeFirst*/false);
2214 while ( edgeSmIt->more() )
2216 SMESH_subMesh* vertexSM = edgeSmIt->next();
2217 // check that vertex is not already treated
2218 if ( !setOfVSubMesh.insert( vertexSM ).second )
2220 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2223 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2224 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2225 while ( nodeIt->more() )
2227 listOfElemType.push_back( SMDSAbs_Node );
2228 connectivity.push_back
2229 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2235 // fill node coords and assign local ids to the nodes
2236 int nbNodes = mapNode2LocalID.size();
2237 result->nodesXYZ.length( nbNodes );
2238 TNodeLocalID node2ID = mapNode2LocalID.begin();
2239 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2240 node2ID->second = i;
2241 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2242 result->nodesXYZ[i].x = node->X();
2243 result->nodesXYZ[i].y = node->Y();
2244 result->nodesXYZ[i].z = node->Z();
2246 // fill connectivity
2247 result->elementConnectivities.length( nbConnNodes );
2248 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2249 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2250 result->elementConnectivities[i] = (*connIt)->second;
2253 // fill element types
2254 result->elementTypes.length( listOfElemType.size() );
2255 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2256 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2257 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2259 SMDSAbs_ElementType elemType = *typeIt;
2260 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2261 result->elementTypes[i].isPoly = false;
2262 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2265 // correct number of shapes
2266 theShapesId.length( mapOfShIdNb.size() );
2270 catch ( std::bad_alloc ) {
2271 INFOS( "Precompute(): lack of memory" );
2273 catch ( SALOME_Exception& S_ex ) {
2274 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2277 INFOS( "Precompute(): unknown exception " );
2279 return result._retn();
2283 //=============================================================================
2285 * SMESH_Gen_i::Evaluate
2287 * Evaluate mesh on a shape
2289 //=============================================================================
2291 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2292 GEOM::GEOM_Object_ptr theShapeObject)
2293 // SMESH::long_array& theNbElems)
2294 throw ( SALOME::SALOME_Exception )
2296 Unexpect aCatch(SALOME_SalomeException);
2297 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2299 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2300 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2301 SALOME::BAD_PARAM );
2303 if ( CORBA::is_nil( theMesh ) )
2304 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2305 SALOME::BAD_PARAM );
2307 SMESH::long_array_var nbels = new SMESH::long_array;
2308 nbels->length(SMESH::Entity_Last);
2309 int i = SMESH::Entity_Node;
2310 for (; i < SMESH::Entity_Last; i++)
2313 // Update Python script
2314 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2315 << theMesh << ", " << theShapeObject << ")";
2319 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2320 ASSERT( meshServant );
2321 if ( meshServant ) {
2322 meshServant->Load();
2323 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2324 meshServant->CheckGeomModif();
2325 // get local TopoDS_Shape
2326 TopoDS_Shape myLocShape;
2327 if(theMesh->HasShapeToMesh())
2328 myLocShape = GeomObjectToShape( theShapeObject );
2330 myLocShape = SMESH_Mesh::PseudoShape();
2331 // call implementation compute
2332 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2333 MapShapeNbElems aResMap;
2334 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2335 MapShapeNbElemsItr anIt = aResMap.begin();
2336 for(; anIt!=aResMap.end(); anIt++) {
2337 const vector<int>& aVec = (*anIt).second;
2338 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2339 int nbElem = aVec[i];
2340 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2342 SMESH_subMesh* sm = anIt->first;
2343 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2344 const SMESH_Algo* algo = sm->GetAlgo();
2345 if ( (algo && !error.get()) || error->IsOK() )
2346 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2350 nbels[i] += aVec[i];
2354 return nbels._retn();
2357 catch ( std::bad_alloc ) {
2358 INFOS( "Evaluate(): lack of memory" );
2360 catch ( SALOME_Exception& S_ex ) {
2361 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2364 INFOS( "Evaluate(): unknown exception " );
2367 return nbels._retn();
2370 //================================================================================
2372 * \brief Return geometrical object the given element is built on
2373 * \param theMesh - the mesh the element is in
2374 * \param theElementID - the element ID
2375 * \param theGeomName - the name of the result geom object if it is not yet published
2376 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2378 //================================================================================
2380 GEOM::GEOM_Object_ptr
2381 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2382 CORBA::Long theElementID,
2383 const char* theGeomName)
2384 throw ( SALOME::SALOME_Exception )
2386 Unexpect aCatch(SALOME_SalomeException);
2388 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2389 if ( !geom->_is_nil() ) {
2390 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2391 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2393 // try to find the corresponding SObject
2394 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2395 if ( SObj->_is_nil() ) // submesh can be not found even if published
2397 // try to find published submesh
2398 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2399 if ( !geom->IsMainShape() && list->length() == 1 ) {
2400 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2401 SALOMEDS::ChildIterator_wrap it;
2402 if ( !mainSO->_is_nil() ) {
2403 it = getStudyServant()->NewChildIterator( mainSO );
2405 if ( !it->_is_nil() ) {
2406 for ( it->InitEx(true); it->More(); it->Next() ) {
2407 SALOMEDS::SObject_wrap so = it->Value();
2408 CORBA::Object_var obj = SObjectToObject( so );
2409 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2410 if ( !subGeom->_is_nil() ) {
2411 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2412 if ( subList->length() == 1 && list[0] == subList[0] ) {
2422 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2423 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2425 // return only published geometry
2426 if ( !SObj->_is_nil() ) {
2427 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2428 CORBA::Object_var obj = SObjectToObject( SObj );
2429 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2433 return GEOM::GEOM_Object::_nil();
2436 //================================================================================
2438 * \brief Return geometrical object the given element is built on.
2439 * \param theMesh - the mesh the element is in
2440 * \param theElementID - the element ID
2441 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2443 //================================================================================
2445 GEOM::GEOM_Object_ptr
2446 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2447 CORBA::Long theElementID)
2448 throw ( SALOME::SALOME_Exception )
2450 Unexpect aCatch(SALOME_SalomeException);
2451 if ( CORBA::is_nil( theMesh ) )
2452 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2454 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2455 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2457 // get a core mesh DS
2458 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2459 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2461 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2462 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2463 // find the element in mesh
2464 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2465 // find a shape id by the element
2466 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2467 // get a geom object by the shape id
2468 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2469 if ( geom->_is_nil() ) {
2470 // try to find a published sub-shape
2471 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2472 SALOMEDS::ChildIterator_wrap it;
2473 if ( !mainSO->_is_nil() ) {
2474 it = getStudyServant()->NewChildIterator( mainSO );
2476 if ( !it->_is_nil() ) {
2477 for ( it->InitEx(true); it->More(); it->Next() ) {
2478 SALOMEDS::SObject_wrap so = it->Value();
2479 CORBA::Object_var obj = SObjectToObject( so );
2480 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2481 if ( !subGeom->_is_nil() ) {
2482 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2483 if ( subList->length() == 1 && shapeID == subList[0] ) {
2491 if ( geom->_is_nil() ) {
2493 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2494 if ( !op->_is_nil() )
2495 geom = op->GetSubShape( mainShape, shapeID );
2500 if ( !geom->_is_nil() ) {
2501 GeomObjectToShape( geom ); // let geom client remember the found shape
2502 return geom._retn();
2507 return GEOM::GEOM_Object::_nil();
2510 //================================================================================
2512 * SMESH_Gen_i::Concatenate
2514 * Concatenate the given meshes into one mesh
2516 //================================================================================
2518 SMESH::SMESH_Mesh_ptr
2519 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2520 CORBA::Boolean theUniteIdenticalGroups,
2521 CORBA::Boolean theMergeNodesAndElements,
2522 CORBA::Double theMergeTolerance,
2523 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2524 throw ( SALOME::SALOME_Exception )
2526 return ConcatenateCommon(theMeshesArray,
2527 theUniteIdenticalGroups,
2528 theMergeNodesAndElements,
2534 //================================================================================
2536 * SMESH_Gen_i::ConcatenateWithGroups
2538 * Concatenate the given meshes into one mesh
2539 * Create the groups of all elements from initial meshes
2541 //================================================================================
2543 SMESH::SMESH_Mesh_ptr
2544 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2545 CORBA::Boolean theUniteIdenticalGroups,
2546 CORBA::Boolean theMergeNodesAndElements,
2547 CORBA::Double theMergeTolerance,
2548 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2549 throw ( SALOME::SALOME_Exception )
2551 return ConcatenateCommon(theMeshesArray,
2552 theUniteIdenticalGroups,
2553 theMergeNodesAndElements,
2559 //================================================================================
2561 * SMESH_Gen_i::ConcatenateCommon
2563 * Concatenate the given meshes into one mesh
2565 //================================================================================
2567 SMESH::SMESH_Mesh_ptr
2568 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2569 CORBA::Boolean theUniteIdenticalGroups,
2570 CORBA::Boolean theMergeNodesAndElements,
2571 CORBA::Double theMergeTolerance,
2572 CORBA::Boolean theCommonGroups,
2573 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2574 throw ( SALOME::SALOME_Exception )
2576 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2577 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2579 // create mesh if theMeshToAppendTo not provided
2580 SMESH::SMESH_Mesh_var newMesh;
2581 if ( CORBA::is_nil( theMeshToAppendTo ))
2582 newMesh = CreateEmptyMesh();
2584 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2585 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2586 if ( !newImpl ) return newMesh._retn();
2589 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2590 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2592 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2593 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2594 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2595 TGroupsMap groupsMap;
2596 TListOfNewGroups listOfNewGroups;
2598 if ( !CORBA::is_nil( theMeshToAppendTo ))
2600 // fill groupsMap with existing groups
2601 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2602 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2604 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2605 if ( !group->_is_nil() )
2607 CORBA::String_var name = group->GetName();
2608 SMESH::ElementType type = group->GetType();
2609 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2614 ::SMESH_MeshEditor newEditor( &locMesh );
2615 ::SMESH_MeshEditor::ElemFeatures elemType;
2617 // loop on sub-meshes
2618 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2620 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2621 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2622 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2623 if ( !initImpl ) continue;
2624 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2628 // assure that IDs increment by one during iteration
2629 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2630 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2631 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2632 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2634 initMeshDS->Modified();
2635 initMeshDS->CompactMesh();
2638 // remember nb of elements before filling in
2639 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2643 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2644 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2645 while ( elemIt->more() )
2647 SMESH_NodeXYZ node = elemIt->next();
2648 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2653 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2654 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2656 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2657 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2658 while ( elemIt->more() )
2660 const SMDS_MeshElement* elem = elemIt->next();
2661 elemType.myNodes.resize( elem->NbNodes() );
2663 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2664 for ( int k = 0; itNodes->more(); k++)
2666 const SMDS_MeshNode* node = itNodes->next();
2667 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2670 // creates a corresponding element on existent nodes in new mesh
2671 newElems[ elem->GetID() ] =
2672 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2674 newEditor.ClearLastCreated(); // forget the history
2677 // create groups of just added elements
2678 SMESH::SMESH_Group_var newGroup;
2679 SMESH::ElementType groupType;
2680 if ( theCommonGroups )
2683 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2684 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2685 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2686 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2689 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2691 for( groupType = SMESH::NODE;
2692 groupType < SMESH::NB_ELEMENT_TYPES;
2693 groupType = (SMESH::ElementType)( groupType + 1 ))
2695 if ( curState[ groupType ] <= prevState[ groupType ])
2696 continue; // no elements of groupType added from the i-th mesh
2698 // make a group name
2699 std::string groupName = "Gr";
2700 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2702 CORBA::String_var name = meshSO->GetName();
2706 groupName += typeNames[ groupType ];
2708 // make and fill a group
2709 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2710 std::vector< const SMDS_MeshElement* > & elemVec =
2711 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2712 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2714 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2716 for ( size_t j = 0; j < elemVec.size(); ++j )
2718 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2719 grpDS->Add( elemVec[j] );
2723 listOfNewGroups.clear();
2724 listOfNewGroups.push_back( newGroup );
2725 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2730 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2734 SMESH::SMESH_GroupBase_ptr group;
2735 CORBA::String_var groupName;
2736 SMESH::long_array_var newIDs = new SMESH::long_array();
2738 // loop on groups of a source mesh
2739 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2740 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2742 group = listOfGroups[iG];
2743 groupType = group->GetType();
2744 groupName = group->GetName();
2745 std::string name = groupName.in();
2747 // convert a list of IDs
2748 newIDs->length( group->Size() );
2749 std::vector< const SMDS_MeshElement* > & elemVec =
2750 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2751 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2753 while ( itGrElems->more() )
2755 const SMDS_MeshElement* elem = itGrElems->next();
2756 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2758 newIDs[ nbElems++ ] = newElem->GetID();
2760 newIDs->length( nbElems );
2762 // check that a current group name and type don't have identical ones in final mesh
2763 listOfNewGroups.clear();
2764 TNameAndType nameAndType( name, groupType );
2765 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2766 if ( anIter == groupsMap.end() )
2768 // add a new group in the mesh
2769 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2770 newGroup->Add( newIDs );
2772 listOfNewGroups.push_back( newGroup );
2773 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2775 else if ( theUniteIdenticalGroups )
2777 // unite identical groups
2778 TListOfNewGroups& aNewGroups = anIter->second;
2779 aNewGroups.front()->Add( newIDs );
2783 // rename identical groups
2784 newGroup = newImpl->CreateGroup( groupType, groupName );
2785 newGroup->Add( newIDs );
2787 TListOfNewGroups& newGroups = anIter->second;
2788 std::string newGroupName;
2789 if ( newGroups.size() == 1 )
2791 newGroupName = name + "_1";
2792 newGroups.front()->SetName( newGroupName.c_str() );
2794 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2795 newGroup->SetName( newGroupName.c_str() );
2796 newGroups.push_back( newGroup );
2799 } // if an IDSource is a mesh
2802 if ( theMergeNodesAndElements ) // merge nodes
2804 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2805 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2806 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2807 /*SeparateCornersAndMedium=*/ false );
2808 newEditor.MergeNodes( groupsOfNodes );
2810 newEditor.MergeEqualElements();
2813 // Update Python script
2814 pythonDump << newMesh << " = " << this
2815 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2816 << theMeshesArray << ", "
2817 << theUniteIdenticalGroups << ", "
2818 << theMergeNodesAndElements << ", "
2819 << TVar( theMergeTolerance ) << ", "
2820 << theMeshToAppendTo << " )";
2822 pPythonDump.reset(); // enable python dump from GetGroups()
2824 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2825 if ( !newMesh->_is_nil() )
2827 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2830 // IPAL21468 Change icon of compound because it need not be computed.
2831 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2832 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2834 newMeshDS->Modified();
2836 return newMesh._retn();
2839 //================================================================================
2841 * \brief Create a mesh by copying a part of another mesh
2842 * \param meshPart - a part of mesh to copy
2843 * \param toCopyGroups - to create in the new mesh groups
2844 * the copied elements belongs to
2845 * \param toKeepIDs - to preserve IDs of the copied elements or not
2846 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2848 //================================================================================
2850 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2851 const char* meshName,
2852 CORBA::Boolean toCopyGroups,
2853 CORBA::Boolean toKeepIDs)
2854 throw ( SALOME::SALOME_Exception )
2856 Unexpect aCatch(SALOME_SalomeException);
2858 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2859 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2861 // 1. Get source mesh
2863 if ( CORBA::is_nil( meshPart ))
2864 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2866 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2867 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2869 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2871 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2873 // 2. Make a new mesh
2875 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2876 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2878 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2879 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2880 if ( !meshSO->_is_nil() )
2882 SetName( meshSO, meshName, "Mesh" );
2883 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2885 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2886 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2887 ::SMESH_MeshEditor::ElemFeatures elemType;
2889 // 3. Get elements to copy
2891 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2892 TIDSortedElemSet srcElems;
2893 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2894 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2897 srcElemIt = srcMeshDS->elementsIterator();
2898 srcNodeIt = srcMeshDS->nodesIterator();
2902 SMESH::long_array_var ids = meshPart->GetIDs();
2903 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2905 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2906 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2907 srcElems.insert( elem );
2911 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2912 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2913 srcElems.insert( elem );
2915 if ( srcElems.empty() )
2916 return newMesh._retn();
2918 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2919 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2924 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2925 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2926 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2928 const SMDS_MeshNode *nSrc, *nTgt;
2929 vector< const SMDS_MeshNode* > nodes;
2930 while ( srcElemIt->more() )
2932 const SMDS_MeshElement * elem = srcElemIt->next();
2934 nodes.resize( elem->NbNodes());
2935 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2937 for ( iN = 0; nIt->more(); ++iN )
2939 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2940 nTgt = newMeshDS->FindNode( nSrc->GetID());
2942 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2947 for ( iN = 0; nIt->more(); ++iN )
2949 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2950 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2952 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2953 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2957 if ( elem->GetType() != SMDSAbs_Node )
2959 elemType.Init( elem, /*basicOnly=*/false );
2960 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2962 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2963 if ( toCopyGroups && !toKeepIDs )
2964 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2966 } // while ( srcElemIt->more() )
2968 // 4(b). Copy free nodes
2970 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2972 while ( srcNodeIt->more() )
2974 nSrc = srcNodeIt->next();
2975 if ( nSrc->NbInverseElements() == 0 )
2978 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2980 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2987 int nbNewGroups = 0;
2990 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2991 while ( gIt->more() )
2993 SMESH_Group* group = gIt->next();
2994 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2996 // Check group type. We copy nodal groups containing nodes of copied element
2997 SMDSAbs_ElementType groupType = groupDS->GetType();
2998 if ( groupType != SMDSAbs_Node &&
2999 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3000 continue; // group type differs from types of meshPart
3002 // Find copied elements in the group
3003 vector< const SMDS_MeshElement* > groupElems;
3004 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3007 const SMDS_MeshElement* foundElem;
3008 if ( groupType == SMDSAbs_Node )
3010 while ( eIt->more() )
3011 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3012 groupElems.push_back( foundElem );
3016 while ( eIt->more() )
3017 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3018 groupElems.push_back( foundElem );
3023 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3024 if ( e2eMap.empty() ) continue;
3025 int minID = e2eMap.begin()->first->GetID();
3026 int maxID = e2eMap.rbegin()->first->GetID();
3027 TE2EMap::iterator e2e;
3028 while ( eIt->more() && groupElems.size() < e2eMap.size())
3030 const SMDS_MeshElement* e = eIt->next();
3031 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3032 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3033 groupElems.push_back( e2e->second );
3037 if ( !groupElems.empty() )
3039 SMESH::SMESH_Group_var newGroupObj =
3040 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3041 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3043 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3044 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3045 for ( unsigned i = 0; i < groupElems.size(); ++i )
3046 smdsGroup.Add( groupElems[i] );
3054 newMeshDS->Modified();
3056 *pyDump << newMesh << " = " << this
3057 << ".CopyMesh( " << meshPart << ", "
3058 << "'" << meshName << "', "
3059 << toCopyGroups << ", "
3060 << toKeepIDs << ")";
3062 pyDumpDeleter.reset(); // allow dump in GetGroups()
3064 if ( nbNewGroups > 0 ) // dump created groups
3065 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3067 return newMesh._retn();
3071 namespace // utils for CopyMeshWithGeom()
3073 typedef std::map< std::string, std::string > TStr2StrMap;
3074 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3075 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3076 typedef std::map< std::string, int > TName2IndexMap;
3078 //================================================================================
3080 * \brief Return a new sub-shape corresponding to an old one
3082 //================================================================================
3086 SMESH_Mesh_i* mySrcMesh_i;
3087 SMESH_Mesh_i* myNewMesh_i;
3088 SMESH_Gen_i* myGen_i;
3092 TStr2StrMap myOld2NewEntryMap; // map of study entries
3094 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3095 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3096 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3099 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3101 // not directly relating to shape search
3102 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3104 //================================================================================
3106 * \brief Constructor
3108 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3109 SMESH_Mesh_i* newMesh_i,
3110 SMESH_Gen_i* smeshGen_i )
3111 : mySrcMesh_i( srcMesh_i ),
3112 myNewMesh_i( newMesh_i ),
3113 myGen_i ( smeshGen_i ),
3114 myToPublish( smeshGen_i->IsEnablePublish() ),
3115 myGIPMapDone( false )
3117 // retrieve from the study shape mapping made thanks to
3118 // "Set presentation parameters and sub-shapes from arguments" option
3120 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3121 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3122 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3123 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3124 if ( newSO->_is_nil() )
3126 myToPublish = false;
3129 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3131 CORBA::String_var oldEntry = oldSO->GetID();
3132 CORBA::String_var newEntry = newSO->GetID();
3133 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3134 std::string( newEntry.in() )));
3135 std::string newMainEntry = newEntry.in();
3137 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3138 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3139 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3140 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3141 /*groupsOnly=*/false );
3142 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3144 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3145 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3146 bool refFound = false;
3147 for ( ; anIter->More(); anIter->Next() )
3149 SALOMEDS::SObject_wrap so = anIter->Value();
3150 if ( so->ReferencedObject( oldSO.inout() ))
3152 oldEntry = oldSO->GetID();
3153 newEntry = newSO->GetID();
3154 if (( refFound = ( newMainEntry != oldEntry.in() )))
3155 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3156 std::string( newEntry.in() )));
3161 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3162 if ( father->_is_equivalent( mainShapeNew ))
3164 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3165 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3166 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3167 CORBA::String_var name = newSO->GetName();
3169 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3175 //================================================================================
3177 * \brief Find a new sub-shape corresponding to an old one
3179 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3182 return GEOM::GEOM_Object::_duplicate( oldShape );
3184 GEOM::GEOM_Object_var newShape;
3186 if ( CORBA::is_nil( oldShape ))
3187 return newShape._retn();
3189 if ( !isChildOfOld( oldShape ))
3190 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3192 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3193 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3195 // try to find by entry or name
3198 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3199 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3200 if ( o2nID != myOld2NewEntryMap.end() )
3202 newShape = getShapeByEntry( o2nID->second );
3204 if ( newShape->_is_nil() )
3206 CORBA::String_var name = oldShape->GetName();
3207 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3208 if ( n2ind != myName2SubshapeIndex.end() )
3210 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3211 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3212 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3213 if ( oldIndices->length() == 0 ||
3214 newIndices->length() == 0 ||
3215 getShapeType( myNewMesh_i, newIndices[0] ) !=
3216 getShapeType( mySrcMesh_i, oldIndices[0] ))
3217 newShape = GEOM::GEOM_Object::_nil();
3222 if ( newShape->_is_nil() )
3224 // try to construct a new sub-shape using myGIPMap
3226 std::vector< int > newIndices;
3227 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3228 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3230 findNewIDs( oldIndices[i], newIndices );
3232 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3235 newShape = getInPlace( oldShape );
3237 if ( !newIndices.empty() && newShape->_is_nil() )
3239 // search for a sub-shape with same ids
3240 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3241 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3242 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3243 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3245 if ( newShape->_is_nil() )
3248 // create a new shape
3249 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3251 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3253 GEOM::GEOM_IGroupOperations_ptr grOp = geomGen->GetIGroupOperations();
3254 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3256 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3257 newIndicesList->length( newIndices.size() );
3258 for ( size_t i = 0; i < newIndices.size(); ++i )
3259 newIndicesList[ i ] = newIndices[ i ];
3260 grOp->UnionIDs( newShape, newIndicesList );
3264 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3265 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3274 if ( !newShape->_is_nil() && myToPublish )
3276 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3277 if ( !newEntry.in() || !newEntry.in()[0] )
3279 CORBA::String_var name = oldShape->GetName();
3280 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3281 newEntry = newShape->GetStudyEntry();
3282 oldEntry = oldShape->GetStudyEntry();
3283 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3284 std::string( newEntry.in() )));
3288 return newShape._retn();
3291 //================================================================================
3293 * \brief Return a study entry of a new shape by study entry of the old one
3295 std::string FindNew( const std::string & oldEntry )
3300 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3301 if ( o2nID != myOld2NewEntryMap.end() )
3302 return o2nID->second;
3304 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3305 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3308 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3309 if ( newShape->_is_nil() )
3310 return std::string();
3312 CORBA::String_var newEntry = newShape->GetStudyEntry();
3313 return newEntry.in();
3316 //================================================================================
3318 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3319 * Return zero if not found or there are more than one new ID
3321 int FindNew( int oldID )
3330 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3332 if ( myGIPMap[ oldID ].length() == 1 )
3334 newID = myGIPMap[ oldID ][ 0 ];
3336 else if ( myGIPMap[ oldID ].length() > 1 &&
3337 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3339 // select a meshed VERTEX
3340 SMESH_subMesh* newSM;
3341 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3342 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3343 ( !newSM->IsEmpty() ))
3344 newID = myGIPMap[ oldID ][ i ];
3350 //================================================================================
3352 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3353 * Return zero if the old shape is not kept as is in the new shape.
3355 int FindNewNotChanged( SMESH_subMesh* oldSM )
3358 return oldSM->GetId();
3360 int newID = FindNew( oldSM->GetId() );
3364 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3368 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3369 // one new sub-shape of the same type.
3371 if ( oldSM->DependsOn().size() !=
3372 newSM->DependsOn().size() )
3375 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3376 while ( srcSMIt->more() )
3378 oldSM = srcSMIt->next();
3379 int newSubID = FindNew( oldSM->GetId() );
3380 if ( getShapeType( myNewMesh_i, newSubID ) !=
3381 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3387 //================================================================================
3389 * \brief Return shape by study entry
3391 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3393 GEOM::GEOM_Object_var shape;
3394 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3395 if ( !so->_is_nil() )
3397 CORBA::Object_var obj = so->GetObject();
3398 shape = GEOM::GEOM_Object::_narrow( obj );
3400 return shape._retn();
3403 //================================================================================
3405 * \brief Fill myGIPMap by calling GetInPlaceMap()
3409 if ( !myGIPMapDone )
3411 myGIPMapDone = true;
3413 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3414 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3415 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3416 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3419 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3423 myGIPMap = new GEOM::ListOfListOfLong();
3428 //================================================================================
3430 * \brief Get new sub-shape by calling GetInPlace()
3432 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3434 GEOM::GEOM_Object_var newShape;
3436 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3437 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3438 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3441 newShape = op->GetInPlace( mainShapeNew, oldShape );
3446 return newShape._retn();
3449 //================================================================================
3451 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3452 * number of found IDs
3454 int findNewIDs( int oldID, std::vector< int >& newIDs )
3456 size_t prevNbIDs = newIDs.size();
3458 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3460 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3461 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3463 return newIDs.size() - prevNbIDs;
3466 //================================================================================
3468 * \brief Check if an object relates to the old shape
3470 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3472 if ( CORBA::is_nil( oldShape ))
3474 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3475 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3476 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3477 mainShapeOld1->_is_equivalent( oldShape ));
3480 //================================================================================
3482 * \brief Return shape type by shape ID
3484 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3486 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3487 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3488 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3491 //================================================================================
3493 * \brief Store a source sub-shape for which a counterpart not found and
3494 * a smesh object invalid due to that
3496 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3497 SALOMEDS::SObject_wrap smeshSO )
3499 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3500 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3502 CORBA::String_var smeshEntry = smeshSO->GetID();
3503 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3507 //================================================================================
3509 * \brief Store a source sub-shape for which a counterpart not found and
3510 * a smesh object invalid due to that
3512 void AddInvalid( std::string geomEntry,
3513 SALOMEDS::SObject_wrap smeshSO )
3515 if ( !geomEntry.empty() )
3517 CORBA::String_var smeshEntry = smeshSO->GetID();
3518 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3522 //================================================================================
3524 * \brief Store a source sub-shape for which a counterpart not found and
3525 * a smesh object invalid due to that
3527 void AddInvalid( int oldGeomID,
3528 SALOMEDS::SObject_wrap smeshSO )
3530 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3531 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3534 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3535 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3537 SMESH_Comment geomName( typeName[ shapeType ]);
3538 geomName << " #" << oldGeomID;
3540 CORBA::String_var smeshEntry = smeshSO->GetID();
3541 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3544 //================================================================================
3546 * \brief Return entries of a source sub-shape for which a counterpart not found and
3547 * of smesh objects invalid due to that
3549 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3550 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3553 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3554 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3556 nbSO += 1 + entry2entrySet->second.size();
3558 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3559 theInvalidEntries->length ( nbSO );
3560 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3562 entry2entrySet = myInvalidMap.begin();
3563 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3565 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3567 std::set< std::string > & entrySet = entry2entrySet->second;
3568 std::set< std::string >::iterator entry = entrySet.begin();
3569 for ( ; entry != entrySet.end(); ++entry )
3571 theInvalidEntries[ iEntry++ ] = entry->c_str();
3573 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3574 if ( !so->_is_nil() )
3575 theInvalidMeshSObjects[ iSO++ ] = so;
3580 }; // struct ShapeMapper
3582 //================================================================================
3584 * \brief Append an item to a CORBA sequence
3586 template < class CORBA_seq, class ITEM >
3587 void append( CORBA_seq& seq, ITEM item )
3589 if ( !CORBA::is_nil( item ))
3591 seq->length( 1 + seq->length() );
3592 seq[ seq->length() - 1 ] = item;
3595 } // namespace // utils for CopyMeshWithGeom()
3597 //================================================================================
3599 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3600 * \param [in] sourceMesh - a mesh to copy
3601 * \param [in] newGeometry - a new geometry
3602 * \param [in] toCopyGroups - to create groups in the new mesh
3603 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3604 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3605 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3606 * \param [out] newMesh - return a new mesh
3607 * \param [out] newGroups - return new groups
3608 * \param [out] newSubmeshes - return new sub-meshes
3609 * \param [out] newHypotheses - return new algorithms and hypotheses
3610 * \param [out] invalidEntries - return study entries of objects whose
3611 * counterparts are not found in the newGeometry, followed by entries
3612 * of mesh sub-objects that are invalid because they depend on a not found
3613 * preceding sub-shape
3614 * \return CORBA::Boolean - is a success
3616 //================================================================================
3618 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3619 GEOM::GEOM_Object_ptr theNewGeometry,
3620 const char* theMeshName,
3621 CORBA::Boolean theToCopyGroups,
3622 CORBA::Boolean theToReuseHypotheses,
3623 CORBA::Boolean theToCopyElements,
3624 SMESH::SMESH_Mesh_out theNewMesh,
3625 SMESH::ListOfGroups_out theNewGroups,
3626 SMESH::submesh_array_out theNewSubmeshes,
3627 SMESH::ListOfHypothesis_out theNewHypotheses,
3628 SMESH::string_array_out theInvalidEntries)
3629 throw ( SALOME::SALOME_Exception )
3631 if ( CORBA::is_nil( theSourceMesh ) ||
3632 CORBA::is_nil( theNewGeometry ))
3633 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3635 if ( !theSourceMesh->HasShapeToMesh() )
3636 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3641 TPythonDump pyDump; // prevent dump from CreateMesh()
3643 theNewMesh = CreateMesh( theNewGeometry );
3644 theNewGroups = new SMESH::ListOfGroups();
3645 theNewSubmeshes = new SMESH::submesh_array();
3646 theNewHypotheses = new SMESH::ListOfHypothesis();
3647 theInvalidEntries = new SMESH::string_array();
3649 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3651 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3652 GEOM::GEOM_Object_var geom, newGeom;
3653 SALOMEDS::SObject_wrap so;
3655 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3656 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3659 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3661 // treat hypotheses of mesh and sub-meshes
3662 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3663 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3665 bool isSubMesh = ( iSM < smList->length() );
3668 // create a new sub-mesh
3669 SMESH::SMESH_subMesh_var newSM;
3670 geom = smList[iSM]->GetSubShape();
3671 so = ObjectToSObject( smList[iSM] );
3672 CORBA::String_var name;
3673 if ( !so->_is_nil() )
3674 name = so->GetName();
3675 newGeom = shapeMapper.FindNew( geom );
3676 if ( newGeom->_is_nil() )
3678 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3679 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3684 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3686 append( theNewSubmeshes, newSM );
3688 if ( newGeom->_is_nil() )
3689 continue; // don't assign hypotheses
3693 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3695 so = ObjectToSObject( theNewMesh );
3696 SetName( so, theMeshName, "Mesh" );
3699 // assign hypotheses
3700 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3701 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3703 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3704 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3706 // get geometry hyp depends on
3707 std::vector< std::string > entryArray;
3708 std::vector< int > subIDArray;
3709 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3711 if ( !theToReuseHypotheses || dependsOnGeom )
3713 // create a new hypothesis
3714 CORBA::String_var type = hyp->GetName();
3715 CORBA::String_var lib = hyp->GetLibName();
3716 CORBA::String_var data = hyp_i->SaveTo();
3719 hyp = CreateHypothesis( type, lib );
3720 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3721 hyp_i->LoadFrom( data.in() );
3722 append( theNewHypotheses, hyp );
3726 // update geometry hyp depends on
3727 if ( dependsOnGeom )
3729 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3731 if ( !entryArray[ iGeo ].empty() )
3733 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3734 if ( newEntry.empty() )
3737 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3738 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3740 entryArray[ iGeo ] = newEntry;
3743 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3745 if ( subIDArray[ iGeo ] > 0 )
3747 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3751 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3752 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3754 subIDArray[ iGeo ] = newID;
3757 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3761 CORBA::String_var errorText;
3762 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3763 if ( errorText.in()[0] )
3766 } // loop on hypotheses
3767 } // loop on sub-meshes and mesh
3770 // copy mesh elements, keeping IDs
3771 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3772 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3774 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3775 ::SMESH_MeshEditor::ElemFeatures elemData;
3777 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3778 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3779 /*vertexLast=*/false);
3780 while ( srcSMIt->more() )
3782 SMESH_subMesh* srcSM = srcSMIt->next();
3783 if ( srcSM->IsEmpty() )
3784 continue; // not yet computed
3785 int newID = shapeMapper.FindNewNotChanged( srcSM );
3789 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3790 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3791 while ( nIt->more() )
3793 SMESH_NodeXYZ node( nIt->next() );
3794 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3796 const SMDS_PositionPtr pos = node->GetPosition();
3797 const double* uv = pos->GetParameters();
3798 switch ( pos->GetTypeOfPosition() )
3800 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3801 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3802 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3803 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3807 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3808 while( eIt->more() )
3810 const SMDS_MeshElement* e = eIt->next();
3811 elemData.Init( e, /*basicOnly=*/false );
3812 elemData.SetID( e->GetID() );
3813 elemData.myNodes.resize( e->NbNodes() );
3814 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3816 for ( iN = 0; nnIt->more(); ++iN )
3818 const SMDS_MeshNode* srcNode = nnIt->next();
3819 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3820 if ( !elemData.myNodes[ iN ])
3823 if ( iN == elemData.myNodes.size() )
3824 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3825 newMeshDS->SetMeshElementOnShape( newElem, newID );
3827 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3828 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3831 newMeshDS->Modified();
3837 TStr2StrMap old2newGroupMap;
3839 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3841 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3842 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3843 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3845 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3846 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3847 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3849 CORBA::String_var name = groups[ i ]->GetName();
3850 SMESH::ElementType elemType = groups[ i ]->GetType();
3852 SMESH::SMESH_GroupBase_var newGroup;
3854 if ( !stdlGroup->_is_nil() )
3856 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3858 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3859 const bool isElem = ( elemType != SMESH::NODE );
3860 CORBA::ULong iE = 0;
3861 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3862 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3864 if ( iE < elemIDs->length() )
3866 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3867 stdlGroup->Add( elemIDs );
3868 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3872 else if ( !geomGroup->_is_nil() )
3874 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3875 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3876 if ( newGeom->_is_nil() )
3878 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3879 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3884 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3887 else if ( !fltrGroup->_is_nil() )
3889 // replace geometry in a filter
3890 SMESH::Filter_var filter = fltrGroup->GetFilter();
3891 SMESH::Filter::Criteria_var criteria;
3892 filter->GetCriteria( criteria.out() );
3894 bool isMissingGroup = false;
3895 std::vector< std::string > badEntries;
3897 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3899 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3900 switch ( criteria[ iCr ].Type )
3902 case SMESH::FT_BelongToMeshGroup:
3904 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3905 btgg->SetGroupID( thresholdID );
3906 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3907 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3908 if ( refGroupSO->_is_nil() )
3910 CORBA::String_var refID = refGroupSO->GetID();
3911 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3912 if ( o2nID == old2newGroupMap.end() )
3914 isMissingGroup = true; // corresponding new group not yet created
3917 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3919 if ( o2nID->second.empty() ) // new referred group is invalid
3920 badEntries.push_back( refID.in() );
3923 case SMESH::FT_BelongToGeom:
3924 case SMESH::FT_BelongToPlane:
3925 case SMESH::FT_BelongToCylinder:
3926 case SMESH::FT_BelongToGenSurface:
3927 case SMESH::FT_LyingOnGeom:
3929 std::string newID = shapeMapper.FindNew( thresholdID );
3930 criteria[ iCr ].ThresholdID = newID.c_str();
3931 if ( newID.empty() )
3932 badEntries.push_back( thresholdID );
3935 case SMESH::FT_ConnectedElements:
3937 if ( thresholdID && thresholdID[0] )
3939 std::string newID = shapeMapper.FindNew( thresholdID );
3940 criteria[ iCr ].ThresholdID = newID.c_str();
3941 if ( newID.empty() )
3942 badEntries.push_back( thresholdID );
3948 } // loop on criteria
3950 if ( isMissingGroup && i < nbGroups )
3952 // to treat the group again
3953 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3957 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3958 newFilter->SetCriteria( criteria );
3960 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3961 newFilter->UnRegister();
3963 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3964 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3965 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3967 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3969 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3972 if ( !badEntries.empty() )
3975 } // treat a group on filter
3977 append( theNewGroups, newGroup );
3979 // fill old2newGroupMap
3980 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3981 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3982 if ( !srcSO->_is_nil() )
3984 CORBA::String_var srcID, newID("");
3985 srcID = srcSO->GetID();
3986 if ( !newSO->_is_nil() )
3987 newID = newSO->GetID();
3988 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3989 std::string( newID.in() )));
3992 if ( newGroup->_is_nil() )
3997 newMeshDS->CompactMesh();
4000 if ( !theMeshName || !theMeshName[0] )
4002 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4003 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4004 CORBA::String_var oldName = soOld->GetName();
4005 SetName( soNew, oldName.in(), "Mesh" );
4007 // mark invalid objects
4008 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4010 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4011 highLightInvalid( invalidSObjects[i].in(), true );
4014 << theNewMesh << ", "
4015 << theNewGroups << ", "
4016 << *theNewSubmeshes.ptr() << ", "
4017 << *theNewHypotheses.ptr() << ", "
4018 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4019 << theSourceMesh << ", "
4020 << theNewGeometry << ", "
4021 << "'" << theMeshName << "', "
4022 << theToCopyGroups << ", "
4023 << theToReuseHypotheses << ", "
4024 << theToCopyElements << " )";
4026 SMESH_CATCH( SMESH::throwCorbaException );
4031 //================================================================================
4033 * \brief Get version of MED format being used.
4035 //================================================================================
4037 char* SMESH_Gen_i::GetMEDFileVersion()
4039 MED::TInt majeur, mineur, release;
4040 majeur = mineur = release = 0;
4041 MED::GetVersionRelease(majeur, mineur, release);
4042 std::ostringstream version;
4043 version << majeur << "." << mineur << "." << release;
4044 return CORBA::string_dup( version.str().c_str() );
4047 //================================================================================
4049 * SMESH_Gen_i::GetMEDVersion
4051 * Get MED version of the file by its name
4053 //================================================================================
4054 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4056 std::string version = MED::GetMEDVersion( theFileName );
4057 return CORBA::string_dup( version.c_str() );
4060 //================================================================================
4062 * SMESH_Gen_i::CheckCompatibility
4064 * Check compatibility of file with MED format being used, read only.
4066 //================================================================================
4067 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4069 return MED::CheckCompatibility( theFileName );
4072 //================================================================================
4074 * SMESH_Gen_i::CheckWriteCompatibility
4076 * Check compatibility of file with MED format being used, for append on write.
4078 //================================================================================
4079 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4081 return MED::CheckCompatibility( theFileName, true );
4084 //================================================================================
4086 * SMESH_Gen_i::GetMeshNames
4088 * Get names of meshes defined in file with the specified name
4090 //================================================================================
4091 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4093 //MESSAGE("GetMeshNames " << theFileName);
4094 SMESH::string_array_var aResult = new SMESH::string_array();
4095 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4097 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4098 //MESSAGE("---" << aNbMeshes);
4100 aResult->length( aNbMeshes );
4101 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4102 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4103 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4106 return aResult._retn();
4109 //=============================================================================
4113 * Save SMESH module's data
4115 //=============================================================================
4116 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4121 Kernel_Utils::Localizer loc;
4123 if (!myStudyContext)
4126 // Store study contents as a set of python commands
4129 SALOMEDS::Study_var aStudy = getStudyServant();
4131 // Declare a byte stream
4132 SALOMEDS::TMPFile_var aStreamFile;
4134 // Obtain a temporary dir
4135 TCollection_AsciiString tmpDir =
4136 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4138 // Create a sequence of files processed
4139 SALOMEDS_Tool::ListOfFiles aFileSeq;
4140 aFileSeq.reserve( NUM_TMP_FILES );
4142 TCollection_AsciiString aStudyName( "" );
4144 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4146 // Set names of temporary files
4147 TCollection_AsciiString filename =
4148 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4149 TCollection_AsciiString meshfile =
4150 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4151 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4152 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4153 filename = tmpDir + filename;
4154 meshfile = tmpDir + meshfile;
4157 HDFdataset* aDataset;
4158 HDFgroup* aTopGroup;
4160 HDFgroup* aSubGroup;
4161 HDFgroup* aSubSubGroup;
4162 hdf_size aSize[ 1 ];
4165 //Remove the files if they exist: BugID: 11225
4166 #ifndef WIN32 /* unix functionality */
4167 TCollection_AsciiString cmd("rm -f \"");
4169 TCollection_AsciiString cmd("del /F \"");
4179 system(cmd.ToCString());
4181 // MED writer to be used by storage process
4182 DriverMED_W_SMESHDS_Mesh myWriter;
4183 myWriter.SetFile( meshfile.ToCString() );
4186 // SetStoreName() to groups before storing hypotheses to let them refer to
4187 // groups using "store name", which is "Group <group_persistent_id>"
4189 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4190 for ( ; itBig->More(); itBig->Next() ) {
4191 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4192 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4193 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4194 if ( !CORBA::is_nil( anObject ) ) {
4195 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4196 if ( !myMesh->_is_nil() ) {
4197 myMesh->Load(); // load from study file if not yet done
4198 TPythonDump pd; // not to dump GetGroups()
4199 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4200 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4202 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4205 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4206 int anId = myStudyContext->findId( string( objStr.in() ) );
4208 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4209 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4210 aGrpBaseDS->SetStoreName( grpName );
4220 // ---> create HDF file
4221 aFile = new HDFfile( (char*) filename.ToCString() );
4222 aFile->CreateOnDisk();
4224 // --> iterator for top-level objects
4225 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4226 for ( ; itBig->More(); itBig->Next() ) {
4227 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4229 // --> hypotheses root branch (only one for the study)
4230 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4231 // create hypotheses root HDF group
4232 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4233 aTopGroup->CreateOnDisk();
4235 // iterator for all hypotheses
4236 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4237 for ( ; it->More(); it->Next() ) {
4238 SALOMEDS::SObject_wrap mySObject = it->Value();
4239 CORBA::Object_var anObject = SObjectToObject( mySObject );
4240 if ( !CORBA::is_nil( anObject ) ) {
4241 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4242 if ( !myHyp->_is_nil() ) {
4243 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4245 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4246 std::string hypname = hn.in();
4247 std::string libname = ln.in();
4249 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4250 // WIN32 and ".so" for X-system) must be deleted
4251 int libname_len = libname.length();
4253 if( libname_len > 4 )
4254 libname.resize( libname_len - 4 );
4256 // PAL17753 (Regression: missing hypothesis in restored study)
4257 // "lib" also should be removed from the beginning
4258 //if( libname_len > 3 )
4259 //libname.resize( libname_len - 3 );
4260 if( libname_len > 6 )
4261 libname = libname.substr( 3, libname_len - 3 - 3 );
4263 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4264 CORBA::String_var hypdata = myImpl->SaveTo();
4265 int id = myStudyContext->findId( string( objStr.in() ));
4267 // for each hypothesis create HDF group basing on its id
4268 char hypGrpName[30];
4269 sprintf( hypGrpName, "Hypothesis %d", id );
4270 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4271 aGroup->CreateOnDisk();
4272 // --> type name of hypothesis
4273 aSize[ 0 ] = hypname.length() + 1;
4274 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4275 aDataset->CreateOnDisk();
4276 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4277 aDataset->CloseOnDisk();
4278 // --> server plugin library name of hypothesis
4279 aSize[ 0 ] = libname.length() + 1;
4280 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4281 aDataset->CreateOnDisk();
4282 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4283 aDataset->CloseOnDisk();
4284 // --> persistent data of hypothesis
4285 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4286 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4287 aDataset->CreateOnDisk();
4288 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4289 aDataset->CloseOnDisk();
4290 // close hypothesis HDF group
4291 aGroup->CloseOnDisk();
4296 // close hypotheses root HDF group
4297 aTopGroup->CloseOnDisk();
4299 // --> algorithms root branch (only one for the study)
4300 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4301 // create algorithms root HDF group
4302 aTopGroup = new HDFgroup( "Algorithms", aFile );
4303 aTopGroup->CreateOnDisk();
4305 // iterator for all algorithms
4306 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4307 for ( ; it->More(); it->Next() ) {
4308 SALOMEDS::SObject_wrap mySObject = it->Value();
4309 CORBA::Object_var anObject = SObjectToObject( mySObject );
4310 if ( !CORBA::is_nil( anObject ) ) {
4311 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4312 if ( !myHyp->_is_nil() ) {
4313 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4315 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4316 std::string hypname = hn.in();
4317 std::string libname = ln.in();
4319 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4320 // WIN32 and ".so" for X-system) must be deleted
4321 int libname_len = libname.length();
4323 if( libname_len > 4 )
4324 libname.resize( libname_len - 4 );
4326 // PAL17753 (Regression: missing hypothesis in restored study)
4327 // "lib" also should be removed from the beginning
4328 //if( libname_len > 3 )
4329 //libname.resize( libname_len - 3 );
4330 if( libname_len > 6 )
4331 libname = libname.substr( 3, libname_len - 3 - 3 );
4333 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4334 CORBA::String_var hypdata = myImpl->SaveTo();
4335 int id = myStudyContext->findId( string( objStr.in() ) );
4337 // for each algorithm create HDF group basing on its id
4338 char hypGrpName[30];
4339 sprintf( hypGrpName, "Algorithm %d", id );
4340 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4341 aGroup->CreateOnDisk();
4342 // --> type name of algorithm
4343 aSize[0] = hypname.length() + 1;
4344 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4345 aDataset->CreateOnDisk();
4346 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4347 aDataset->CloseOnDisk();
4348 // --> server plugin library name of hypothesis
4349 aSize[0] = libname.length() + 1;
4350 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4351 aDataset->CreateOnDisk();
4352 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4353 aDataset->CloseOnDisk();
4354 // --> persistent data of algorithm
4355 aSize[0] = strlen( hypdata.in() ) + 1;
4356 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4357 aDataset->CreateOnDisk();
4358 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4359 aDataset->CloseOnDisk();
4360 // close algorithm HDF group
4361 aGroup->CloseOnDisk();
4366 // close algorithms root HDF group
4367 aTopGroup->CloseOnDisk();
4369 // --> mesh objects roots branches
4370 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4371 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4372 if ( !CORBA::is_nil( anObject ) ) {
4373 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4374 if ( !myMesh->_is_nil() ) {
4375 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4377 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4378 int id = myStudyContext->findId( string( objStr.in() ) );
4379 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4380 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4381 bool hasShape = myLocMesh.HasShapeToMesh();
4383 // for each mesh open the HDF group basing on its id
4384 char meshGrpName[ 30 ];
4385 sprintf( meshGrpName, "Mesh %d", id );
4386 aTopGroup = new HDFgroup( meshGrpName, aFile );
4387 aTopGroup->CreateOnDisk();
4389 // --> put dataset to hdf file which is a flag that mesh has data
4390 string strHasData = "0";
4391 // check if the mesh is not empty
4392 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4393 // write mesh data to med file
4394 myWriter.SetMesh( mySMESHDSMesh );
4395 myWriter.SetMeshId( id );
4398 aSize[ 0 ] = strHasData.length() + 1;
4399 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4400 aDataset->CreateOnDisk();
4401 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4402 aDataset->CloseOnDisk();
4405 // for each mesh open the HDF group basing on its auto color parameter
4406 char meshAutoColorName[ 30 ];
4407 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4409 anAutoColor[0] = myImpl->GetAutoColor();
4411 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4412 aDataset->CreateOnDisk();
4413 aDataset->WriteOnDisk( anAutoColor );
4414 aDataset->CloseOnDisk();
4416 // issue 0020693. Store _isModified flag
4417 int isModified = myLocMesh.GetIsModified();
4419 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4420 aDataset->CreateOnDisk();
4421 aDataset->WriteOnDisk( &isModified );
4422 aDataset->CloseOnDisk();
4424 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4425 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4427 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4428 aDataset->CreateOnDisk();
4429 aDataset->WriteOnDisk( &meshPersistentId );
4430 aDataset->CloseOnDisk();
4432 // Store SMESH_Mesh_i::_mainShapeTick
4433 int shapeTick = myImpl->MainShapeTick();
4435 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4436 aDataset->CreateOnDisk();
4437 aDataset->WriteOnDisk( &shapeTick );
4438 aDataset->CloseOnDisk();
4440 // write reference on a shape if exists
4441 SALOMEDS::SObject_wrap myRef;
4442 bool shapeRefFound = false;
4443 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4445 SALOMEDS::SObject_wrap myShape;
4446 bool ok = myRef->ReferencedObject( myShape.inout() );
4448 CORBA::Object_var shapeObj = myShape->GetObject();
4449 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4450 CORBA::String_var myRefOnObject = myShape->GetID();
4451 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4452 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4453 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4454 aDataset->CreateOnDisk();
4455 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4456 aDataset->CloseOnDisk();
4462 std::string info = myImpl->FileInfoToString();
4463 if ( !info.empty() )
4465 aSize[ 0 ] = info.size();
4466 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4467 aDataset->CreateOnDisk();
4468 aDataset->WriteOnDisk( (char*) info.data() );
4469 aDataset->CloseOnDisk();
4472 // write applied hypotheses if exist
4473 SALOMEDS::SObject_wrap myHypBranch;
4474 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4475 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4476 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4478 if ( found && (shapeRefFound || !hasShape) ) {
4479 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4480 aGroup->CreateOnDisk();
4482 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4484 for ( ; it->More(); it->Next() ) {
4485 SALOMEDS::SObject_wrap mySObject = it->Value();
4486 SALOMEDS::SObject_wrap myRefOnHyp;
4487 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4489 // san - it is impossible to recover applied hypotheses
4490 // using their entries within Load() method,
4491 // for there are no AttributeIORs in the study when Load() is working.
4492 // Hence, it is better to store persistent IDs of hypotheses as references to them
4494 //string myRefOnObject = myRefOnHyp->GetID();
4495 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4496 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4497 int id = myStudyContext->findId( string( objStr.in() ) );
4498 //if ( myRefOnObject.length() > 0 ) {
4499 //aSize[ 0 ] = myRefOnObject.length() + 1;
4500 char hypName[ 30 ], hypId[ 30 ];
4501 sprintf( hypName, "Hyp %d", ++hypNb );
4502 sprintf( hypId, "%d", id );
4503 aSize[ 0 ] = strlen( hypId ) + 1;
4504 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4505 aDataset->CreateOnDisk();
4506 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4507 aDataset->WriteOnDisk( hypId );
4508 aDataset->CloseOnDisk();
4512 aGroup->CloseOnDisk();
4515 // write applied algorithms if exist
4516 SALOMEDS::SObject_wrap myAlgoBranch;
4517 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4518 myAlgoBranch.inout() );
4519 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4520 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4522 if ( found && (shapeRefFound || !hasShape)) {
4523 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4524 aGroup->CreateOnDisk();
4526 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4528 for ( ; it->More(); it->Next() ) {
4529 SALOMEDS::SObject_wrap mySObject = it->Value();
4530 SALOMEDS::SObject_wrap myRefOnAlgo;
4531 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4533 // san - it is impossible to recover applied algorithms
4534 // using their entries within Load() method,
4535 // for there are no AttributeIORs in the study when Load() is working.
4536 // Hence, it is better to store persistent IDs of algorithms as references to them
4538 //string myRefOnObject = myRefOnAlgo->GetID();
4539 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4540 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4541 int id = myStudyContext->findId( string( objStr.in() ) );
4542 //if ( myRefOnObject.length() > 0 ) {
4543 //aSize[ 0 ] = myRefOnObject.length() + 1;
4544 char algoName[ 30 ], algoId[ 30 ];
4545 sprintf( algoName, "Algo %d", ++algoNb );
4546 sprintf( algoId, "%d", id );
4547 aSize[ 0 ] = strlen( algoId ) + 1;
4548 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4549 aDataset->CreateOnDisk();
4550 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4551 aDataset->WriteOnDisk( algoId );
4552 aDataset->CloseOnDisk();
4556 aGroup->CloseOnDisk();
4559 // --> submesh objects sub-branches
4561 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4562 SALOMEDS::SObject_wrap mySubmeshBranch;
4563 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4565 if ( found ) // check if there is shape reference in submeshes
4567 bool hasShapeRef = false;
4568 SALOMEDS::ChildIterator_wrap itSM =
4569 aStudy->NewChildIterator( mySubmeshBranch );
4570 for ( ; itSM->More(); itSM->Next() ) {
4571 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4572 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4573 mySubRef->ReferencedObject( myShape.inout() );
4574 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4577 { // remove one submesh
4578 if ( shapeRefFound )
4579 { // unassign hypothesis
4580 SMESH::SMESH_subMesh_var mySubMesh =
4581 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4582 if ( !mySubMesh->_is_nil() ) {
4583 int shapeID = mySubMesh->GetId();
4584 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4585 const list<const SMESHDS_Hypothesis*>& hypList =
4586 mySMESHDSMesh->GetHypothesis( S );
4587 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4588 while ( hyp != hypList.end() ) {
4589 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4590 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4594 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4596 } // loop on submeshes of a type
4597 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4598 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4601 } // end check if there is shape reference in submeshes
4603 char name_meshgroup[ 30 ];
4604 if ( i == GetSubMeshOnVertexTag() )
4605 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4606 else if ( i == GetSubMeshOnEdgeTag() )
4607 strcpy( name_meshgroup, "SubMeshes On Edge" );
4608 else if ( i == GetSubMeshOnWireTag() )
4609 strcpy( name_meshgroup, "SubMeshes On Wire" );
4610 else if ( i == GetSubMeshOnFaceTag() )
4611 strcpy( name_meshgroup, "SubMeshes On Face" );
4612 else if ( i == GetSubMeshOnShellTag() )
4613 strcpy( name_meshgroup, "SubMeshes On Shell" );
4614 else if ( i == GetSubMeshOnSolidTag() )
4615 strcpy( name_meshgroup, "SubMeshes On Solid" );
4616 else if ( i == GetSubMeshOnCompoundTag() )
4617 strcpy( name_meshgroup, "SubMeshes On Compound" );
4619 // for each type of submeshes create container HDF group
4620 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4621 aGroup->CreateOnDisk();
4623 // iterator for all submeshes of given type
4624 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4625 for ( ; itSM->More(); itSM->Next() ) {
4626 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4627 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4628 if ( !CORBA::is_nil( anSubObject ))
4630 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4631 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4632 int subid = myStudyContext->findId( string( objStr.in() ) );
4634 // for each mesh open the HDF group basing on its id
4635 char submeshGrpName[ 30 ];
4636 sprintf( submeshGrpName, "SubMesh %d", subid );
4637 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4638 aSubGroup->CreateOnDisk();
4640 // write reference on a shape, already checked if it exists
4641 SALOMEDS::SObject_wrap mySubRef, myShape;
4642 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4643 mySubRef->ReferencedObject( myShape.inout() );
4644 string myRefOnObject = myShape->GetID();
4645 if ( myRefOnObject.length() > 0 ) {
4646 aSize[ 0 ] = myRefOnObject.length() + 1;
4647 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4648 aDataset->CreateOnDisk();
4649 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4650 aDataset->CloseOnDisk();
4653 // write applied hypotheses if exist
4654 SALOMEDS::SObject_wrap mySubHypBranch;
4655 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4656 mySubHypBranch.inout() );
4658 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4659 aSubSubGroup->CreateOnDisk();
4661 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4663 for ( ; it->More(); it->Next() ) {
4664 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4665 SALOMEDS::SObject_wrap myRefOnHyp;
4666 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4668 //string myRefOnObject = myRefOnHyp->GetID();
4669 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4670 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4671 int id = myStudyContext->findId( string( objStr.in() ) );
4672 //if ( myRefOnObject.length() > 0 ) {
4673 //aSize[ 0 ] = myRefOnObject.length() + 1;
4674 char hypName[ 30 ], hypId[ 30 ];
4675 sprintf( hypName, "Hyp %d", ++hypNb );
4676 sprintf( hypId, "%d", id );
4677 aSize[ 0 ] = strlen( hypId ) + 1;
4678 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4679 aDataset->CreateOnDisk();
4680 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4681 aDataset->WriteOnDisk( hypId );
4682 aDataset->CloseOnDisk();
4686 aSubSubGroup->CloseOnDisk();
4689 // write applied algorithms if exist
4690 SALOMEDS::SObject_wrap mySubAlgoBranch;
4691 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4692 mySubAlgoBranch.inout() );
4694 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4695 aSubSubGroup->CreateOnDisk();
4697 SALOMEDS::ChildIterator_wrap it =
4698 aStudy->NewChildIterator( mySubAlgoBranch );
4700 for ( ; it->More(); it->Next() ) {
4701 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4702 SALOMEDS::SObject_wrap myRefOnAlgo;
4703 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4705 //string myRefOnObject = myRefOnAlgo->GetID();
4706 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4707 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4708 int id = myStudyContext->findId( string( objStr.in() ) );
4709 //if ( myRefOnObject.length() > 0 ) {
4710 //aSize[ 0 ] = myRefOnObject.length() + 1;
4711 char algoName[ 30 ], algoId[ 30 ];
4712 sprintf( algoName, "Algo %d", ++algoNb );
4713 sprintf( algoId, "%d", id );
4714 aSize[ 0 ] = strlen( algoId ) + 1;
4715 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4716 aDataset->CreateOnDisk();
4717 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4718 aDataset->WriteOnDisk( algoId );
4719 aDataset->CloseOnDisk();
4723 aSubSubGroup->CloseOnDisk();
4725 // close submesh HDF group
4726 aSubGroup->CloseOnDisk();
4729 // close container of submeshes by type HDF group
4730 aGroup->CloseOnDisk();
4733 // All sub-meshes will be stored in MED file
4734 // .. will NOT (PAL 12992)
4735 //if ( shapeRefFound )
4736 //myWriter.AddAllSubMeshes();
4738 // store submesh order if any
4739 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4740 if ( theOrderIds.size() ) {
4741 char order_list[ 30 ];
4742 strcpy( order_list, "Mesh Order" );
4743 // count number of submesh ids
4745 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4746 for ( ; idIt != theOrderIds.end(); idIt++ )
4747 nbIDs += (*idIt).size();
4748 // number of values = number of IDs +
4749 // number of lists (for separators) - 1
4750 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4751 idIt = theOrderIds.begin();
4752 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4753 const TListOfInt& idList = *idIt;
4754 if (idIt != theOrderIds.begin()) // not first list
4755 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4756 // dump submesh ids from current list
4757 TListOfInt::const_iterator id_smId = idList.begin();
4758 for( ; id_smId != idList.end(); id_smId++ )
4759 smIDs[ i++ ] = *id_smId;
4762 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4764 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4765 aDataset->CreateOnDisk();
4766 aDataset->WriteOnDisk( smIDs );
4767 aDataset->CloseOnDisk();
4772 // groups root sub-branch
4773 SALOMEDS::SObject_wrap myGroupsBranch;
4774 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4775 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4777 char name_group[ 30 ];
4778 if ( i == GetNodeGroupsTag() )
4779 strcpy( name_group, "Groups of Nodes" );
4780 else if ( i == GetEdgeGroupsTag() )
4781 strcpy( name_group, "Groups of Edges" );
4782 else if ( i == GetFaceGroupsTag() )
4783 strcpy( name_group, "Groups of Faces" );
4784 else if ( i == GetVolumeGroupsTag() )
4785 strcpy( name_group, "Groups of Volumes" );
4786 else if ( i == Get0DElementsGroupsTag() )
4787 strcpy( name_group, "Groups of 0D Elements" );
4788 else if ( i == GetBallElementsGroupsTag() )
4789 strcpy( name_group, "Groups of Balls" );
4791 aGroup = new HDFgroup( name_group, aTopGroup );
4792 aGroup->CreateOnDisk();
4794 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4795 for ( ; it->More(); it->Next() ) {
4796 SALOMEDS::SObject_wrap mySObject = it->Value();
4797 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4798 if ( !CORBA::is_nil( aSubObject ) ) {
4799 SMESH_GroupBase_i* myGroupImpl =
4800 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4803 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4807 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4808 int anId = myStudyContext->findId( string( objStr.in() ) );
4810 // For each group, create a dataset named "Group <group_persistent_id>"
4811 // and store the group's user name into it
4812 const char* grpName = aGrpBaseDS->GetStoreName();
4813 CORBA::String_var aUserName = myGroupImpl->GetName();
4814 aSize[ 0 ] = strlen( aUserName ) + 1;
4816 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4817 aDataset->CreateOnDisk();
4818 aDataset->WriteOnDisk( aUserName );
4819 aDataset->CloseOnDisk();
4822 // For each group, create a dataset named "Group <group_persistent_id> Color"
4823 // and store the group's color into it
4824 char grpColorName[ 30 ];
4825 sprintf( grpColorName, "ColorGroup %d", anId );
4826 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4828 anRGB[ 0 ] = aColor.R;
4829 anRGB[ 1 ] = aColor.G;
4830 anRGB[ 2 ] = aColor.B;
4832 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4833 aDataset->CreateOnDisk();
4834 aDataset->WriteOnDisk( anRGB );
4835 aDataset->CloseOnDisk();
4837 // Pass SMESHDS_Group to MED writer
4838 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4840 myWriter.AddGroup( aGrpDS );
4842 // write reference on a shape if exists
4843 SMESHDS_GroupOnGeom* aGeomGrp =
4844 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4846 SALOMEDS::SObject_wrap mySubRef, myShape;
4847 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4848 mySubRef->ReferencedObject( myShape.inout() ) &&
4849 !CORBA::is_nil( myShape->GetObject() ))
4851 CORBA::String_var myRefOnObject = myShape->GetID();
4852 if ( myRefOnObject.in()[0] ) {
4853 char aRefName[ 30 ];
4854 sprintf( aRefName, "Ref on shape %d", anId);
4855 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4856 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4857 aDataset->CreateOnDisk();
4858 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4859 aDataset->CloseOnDisk();
4862 else // shape ref is invalid:
4864 // save a group on geometry as ordinary group
4865 myWriter.AddGroup( aGeomGrp );
4868 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4869 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4871 std::string str = aFilterGrp_i->FilterToString();
4872 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4873 aSize[ 0 ] = str.length() + 1;
4874 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4875 aDataset->CreateOnDisk();
4876 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4877 aDataset->CloseOnDisk();
4881 aGroup->CloseOnDisk();
4885 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4887 // Flush current mesh information into MED file
4890 // save info on nb of elements
4891 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4893 // maybe a shape was deleted in the study
4894 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4895 TopoDS_Shape nullShape;
4896 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4899 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4904 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4905 aGroup->CreateOnDisk();
4907 // each element belongs to one or none submesh,
4908 // so for each node/element, we store a submesh ID
4910 // Store submesh IDs
4911 for ( int isNode = 0; isNode < 2; ++isNode )
4913 SMDS_ElemIteratorPtr eIt =
4914 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4915 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4918 std::vector<int> smIDs; smIDs.reserve( nbElems );
4919 while ( eIt->more() )
4920 if ( const SMDS_MeshElement* e = eIt->next())
4921 smIDs.push_back( e->getshapeId() );
4923 aSize[ 0 ] = nbElems;
4924 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4925 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4926 aDataset->CreateOnDisk();
4927 aDataset->WriteOnDisk( & smIDs[0] );
4928 aDataset->CloseOnDisk();
4931 aGroup->CloseOnDisk();
4933 // Store node positions on sub-shapes (SMDS_Position):
4934 // ----------------------------------------------------
4936 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4937 aGroup->CreateOnDisk();
4939 // in aGroup, create 5 datasets to contain:
4940 // "Nodes on Edges" - ID of node on edge
4941 // "Edge positions" - U parameter on node on edge
4942 // "Nodes on Faces" - ID of node on face
4943 // "Face U positions" - U parameter of node on face
4944 // "Face V positions" - V parameter of node on face
4946 // Find out nb of nodes on edges and faces
4947 // Collect corresponding sub-meshes
4948 int nbEdgeNodes = 0, nbFaceNodes = 0;
4949 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4950 // loop on SMESHDS_SubMesh'es
4951 while ( smIt->more() )
4953 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4954 if ( aSubMesh->IsComplexSubmesh() )
4955 continue; // submesh containing other submeshs
4956 int nbNodes = aSubMesh->NbNodes();
4957 if ( nbNodes == 0 ) continue;
4959 int aShapeID = aSubMesh->GetID();
4960 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4962 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4963 // write only SMDS_FacePosition and SMDS_EdgePosition
4964 switch ( aShapeType ) {
4966 nbFaceNodes += nbNodes;
4967 aFaceSM.push_back( aSubMesh );
4970 nbEdgeNodes += nbNodes;
4971 aEdgeSM.push_back( aSubMesh );
4977 // Treat positions on edges or faces
4978 for ( int onFace = 0; onFace < 2; onFace++ )
4980 // Create arrays to store in datasets
4981 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4982 if (!nbNodes) continue;
4983 int* aNodeIDs = new int [ nbNodes ];
4984 double* aUPos = new double [ nbNodes ];
4985 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4988 // loop on sub-meshes
4989 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4990 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4991 for ( ; itSM != pListSM->end(); itSM++ )
4993 SMESHDS_SubMesh* aSubMesh = (*itSM);
4995 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4996 // loop on nodes in aSubMesh
4997 while ( itNode->more() )
5000 const SMDS_MeshNode* node = itNode->next();
5001 aNodeIDs [ iNode ] = node->GetID();
5004 const SMDS_PositionPtr pos = node->GetPosition();
5005 if ( onFace ) { // on FACE
5006 SMDS_FacePositionPtr fPos = pos;
5008 aUPos[ iNode ] = fPos->GetUParameter();
5009 aVPos[ iNode ] = fPos->GetVParameter();
5016 SMDS_EdgePositionPtr ePos = pos;
5018 aUPos[ iNode ] = ePos->GetUParameter();
5024 } // loop on nodes in aSubMesh
5025 } // loop on sub-meshes
5030 aSize[ 0 ] = nbNodes;
5032 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5033 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5034 aDataset->CreateOnDisk();
5035 aDataset->WriteOnDisk( aNodeIDs );
5036 aDataset->CloseOnDisk();
5039 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5040 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5041 aDataset->CreateOnDisk();
5042 aDataset->WriteOnDisk( aUPos );
5043 aDataset->CloseOnDisk();
5046 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5047 aDataset->CreateOnDisk();
5048 aDataset->WriteOnDisk( aVPos );
5049 aDataset->CloseOnDisk();
5054 if ( aVPos ) delete [] aVPos;
5056 } // treat positions on edges or faces
5058 // close "Node Positions" group
5059 aGroup->CloseOnDisk();
5061 } // if ( there are submeshes in SMESHDS_Mesh )
5064 // close mesh HDF group
5065 aTopGroup->CloseOnDisk();
5073 aFile->CloseOnDisk();
5076 // Convert temporary files to stream
5077 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5079 // Remove temporary files and directory
5081 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5083 return aStreamFile._retn();
5086 //=============================================================================
5088 * SMESH_Gen_i::SaveASCII
5090 * Save SMESH module's data in ASCII format
5092 //=============================================================================
5094 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5096 bool isMultiFile ) {
5097 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5098 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5099 return aStreamFile._retn();
5101 //after usual saving needs to encipher binary to text string
5102 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5103 int size = aStreamFile.in().length();
5104 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5105 for ( int i = 0; i < size; i++ )
5106 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5108 buffer[size * 3] = '\0';
5110 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5112 return anAsciiStreamFile._retn();
5115 //=============================================================================
5119 * Load SMESH module's data
5121 //=============================================================================
5123 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5124 const SALOMEDS::TMPFile& theStream,
5128 UpdateStudy(); // load geom data
5129 Kernel_Utils::Localizer loc;
5131 SALOMEDS::Study_var aStudy = getStudyServant();
5133 // Get temporary files location
5134 TCollection_AsciiString tmpDir =
5135 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5137 // Convert the stream into sequence of files to process
5138 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5141 TCollection_AsciiString aStudyName( "" );
5142 if ( isMultiFile ) {
5143 CORBA::WString_var url = aStudy->URL();
5144 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5146 // Set names of temporary files
5147 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5148 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5152 HDFdataset* aDataset;
5153 HDFgroup* aTopGroup;
5155 HDFgroup* aSubGroup;
5156 HDFgroup* aSubSubGroup;
5159 // ---> open HDF file
5160 aFile = new HDFfile( (char*) filename.ToCString() );
5162 aFile->OpenOnDisk( HDF_RDONLY );
5164 catch ( HDFexception ) {
5165 INFOS( "Load(): " << filename << " not found!" );
5169 TPythonDump pd; // prevent dump during loading
5171 // DriverMED_R_SMESHDS_Mesh myReader;
5172 // myReader.SetFile( meshfile.ToCString() );
5174 // For PAL13473 ("Repetitive mesh") implementation.
5175 // New dependencies between SMESH objects are established:
5176 // now hypotheses can refer to meshes, shapes and other hypotheses.
5177 // To keep data consistent, the following order of data restoration
5179 // 1. Create hypotheses
5180 // 2. Create all meshes
5181 // 3. Load hypotheses' data
5184 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5185 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5186 list< SMESH::Filter_var > filters;
5188 // get total number of top-level groups
5189 int aNbGroups = aFile->nInternalObjects();
5190 if ( aNbGroups > 0 ) {
5191 // --> in first turn we should read&create hypotheses
5192 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5193 // open hypotheses root HDF group
5194 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5195 aTopGroup->OpenOnDisk();
5197 // get number of hypotheses
5198 int aNbObjects = aTopGroup->nInternalObjects();
5199 for ( int j = 0; j < aNbObjects; j++ ) {
5200 // try to identify hypothesis
5201 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5202 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5204 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5205 // open hypothesis group
5206 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5207 aGroup->OpenOnDisk();
5209 // --> get hypothesis id
5210 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5215 // get number of datasets
5216 int aNbSubObjects = aGroup->nInternalObjects();
5217 for ( int k = 0; k < aNbSubObjects; k++ ) {
5219 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5220 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5221 // --> get hypothesis name
5222 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5223 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5224 aDataset->OpenOnDisk();
5225 size = aDataset->GetSize();
5226 char* hypname_str = new char[ size ];
5227 aDataset->ReadFromDisk( hypname_str );
5228 hypname = string( hypname_str );
5229 delete [] hypname_str;
5230 aDataset->CloseOnDisk();
5232 // --> get hypothesis plugin library name
5233 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5234 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5235 aDataset->OpenOnDisk();
5236 size = aDataset->GetSize();
5237 char* libname_str = new char[ size ];
5238 aDataset->ReadFromDisk( libname_str );
5239 if(MYDEBUG) SCRUTE( libname_str );
5240 libname = string( libname_str );
5241 delete [] libname_str;
5242 aDataset->CloseOnDisk();
5244 // --> get hypothesis data
5245 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5246 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5247 aDataset->OpenOnDisk();
5248 size = aDataset->GetSize();
5249 char* hypdata_str = new char[ size ];
5250 aDataset->ReadFromDisk( hypdata_str );
5251 hypdata = string( hypdata_str );
5252 delete [] hypdata_str;
5253 aDataset->CloseOnDisk();
5256 // close hypothesis HDF group
5257 aGroup->CloseOnDisk();
5259 // --> restore hypothesis from data
5260 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5261 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5262 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5263 SMESH::SMESH_Hypothesis_var myHyp;
5265 try { // protect persistence mechanism against exceptions
5266 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5269 INFOS( "Exception during hypothesis creation" );
5272 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5274 // myImpl->LoadFrom( hypdata.c_str() );
5275 hypDataList.push_back( make_pair( myImpl, hypdata ));
5276 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5277 int newId = myStudyContext->findId( iorString.in() );
5278 myStudyContext->mapOldToNew( id, newId );
5281 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5285 // close hypotheses root HDF group
5286 aTopGroup->CloseOnDisk();
5290 // --> then we should read&create algorithms
5291 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5292 // open algorithms root HDF group
5293 aTopGroup = new HDFgroup( "Algorithms", aFile );
5294 aTopGroup->OpenOnDisk();
5296 // get number of algorithms
5297 int aNbObjects = aTopGroup->nInternalObjects();
5298 for ( int j = 0; j < aNbObjects; j++ ) {
5299 // try to identify algorithm
5300 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5301 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5303 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5304 // open algorithm group
5305 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5306 aGroup->OpenOnDisk();
5308 // --> get algorithm id
5309 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5314 // get number of datasets
5315 int aNbSubObjects = aGroup->nInternalObjects();
5316 for ( int k = 0; k < aNbSubObjects; k++ ) {
5318 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5319 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5320 // --> get algorithm name
5321 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5322 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5323 aDataset->OpenOnDisk();
5324 size = aDataset->GetSize();
5325 char* hypname_str = new char[ size ];
5326 aDataset->ReadFromDisk( hypname_str );
5327 hypname = string( hypname_str );
5328 delete [] hypname_str;
5329 aDataset->CloseOnDisk();
5331 // --> get algorithm plugin library name
5332 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5333 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5334 aDataset->OpenOnDisk();
5335 size = aDataset->GetSize();
5336 char* libname_str = new char[ size ];
5337 aDataset->ReadFromDisk( libname_str );
5338 if(MYDEBUG) SCRUTE( libname_str );
5339 libname = string( libname_str );
5340 delete [] libname_str;
5341 aDataset->CloseOnDisk();
5343 // --> get algorithm data
5344 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5345 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5346 aDataset->OpenOnDisk();
5347 size = aDataset->GetSize();
5348 char* hypdata_str = new char[ size ];
5349 aDataset->ReadFromDisk( hypdata_str );
5350 if(MYDEBUG) SCRUTE( hypdata_str );
5351 hypdata = string( hypdata_str );
5352 delete [] hypdata_str;
5353 aDataset->CloseOnDisk();
5356 // close algorithm HDF group
5357 aGroup->CloseOnDisk();
5359 // --> restore algorithm from data
5360 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5361 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5362 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5363 SMESH::SMESH_Hypothesis_var myHyp;
5365 try { // protect persistence mechanism against exceptions
5366 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5368 catch( SALOME::SALOME_Exception& ex )
5370 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5373 INFOS( "Exception during hypothesis creation" );
5376 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5378 //myImpl->LoadFrom( hypdata.c_str() );
5379 hypDataList.push_back( make_pair( myImpl, hypdata ));
5380 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5381 int newId = myStudyContext->findId( iorString.in() );
5382 myStudyContext->mapOldToNew( id, newId );
5385 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5389 // close algorithms root HDF group
5390 aTopGroup->CloseOnDisk();
5394 // --> the rest groups should be meshes
5395 for ( int i = 0; i < aNbGroups; i++ ) {
5396 // identify next group
5397 char meshName[ HDF_NAME_MAX_LEN+1 ];
5398 aFile->InternalObjectIndentify( i, meshName );
5400 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5402 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5406 // open mesh HDF group
5407 aTopGroup = new HDFgroup( meshName, aFile );
5408 aTopGroup->OpenOnDisk();
5410 // get number of child HDF objects
5411 int aNbObjects = aTopGroup->nInternalObjects();
5412 if ( aNbObjects > 0 ) {
5414 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5415 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5416 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5417 if ( !myNewMeshImpl )
5419 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5421 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5422 int newId = myStudyContext->findId( iorString.in() );
5423 myStudyContext->mapOldToNew( id, newId );
5426 // try to read and set auto color flag
5427 char aMeshAutoColorName[ 30 ];
5428 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5429 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5431 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5432 aDataset->OpenOnDisk();
5433 size = aDataset->GetSize();
5434 int* anAutoColor = new int[ size ];
5435 aDataset->ReadFromDisk( anAutoColor );
5436 aDataset->CloseOnDisk();
5437 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5438 delete [] anAutoColor;
5441 // try to read and set reference to shape
5442 GEOM::GEOM_Object_var aShapeObject;
5443 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5444 // load mesh "Ref on shape" - it's an entry to SObject
5445 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5446 aDataset->OpenOnDisk();
5447 size = aDataset->GetSize();
5448 char* refFromFile = new char[ size ];
5449 aDataset->ReadFromDisk( refFromFile );
5450 aDataset->CloseOnDisk();
5451 if ( strlen( refFromFile ) > 0 ) {
5452 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5453 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5454 if ( !CORBA::is_nil( shapeObject ) ) {
5455 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5456 if ( !aShapeObject->_is_nil() )
5457 myNewMeshImpl->SetShape( aShapeObject );
5460 delete [] refFromFile;
5463 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5464 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5466 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5467 aDataset->OpenOnDisk();
5468 size = aDataset->GetSize();
5469 int* meshPersistentId = new int[ size ];
5470 aDataset->ReadFromDisk( meshPersistentId );
5471 aDataset->CloseOnDisk();
5472 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5473 delete [] meshPersistentId;
5476 // Restore SMESH_Mesh_i::_mainShapeTick
5477 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5479 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5480 aDataset->OpenOnDisk();
5481 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5482 aDataset->ReadFromDisk( shapeTick );
5483 aDataset->CloseOnDisk();
5486 // Restore file info
5487 if ( aTopGroup->ExistInternalObject( "file info" ))
5489 aDataset = new HDFdataset( "file info", aTopGroup );
5490 aDataset->OpenOnDisk();
5491 size = aDataset->GetSize();
5492 std::string info( size, ' ');
5493 aDataset->ReadFromDisk( (char*) info.data() );
5494 aDataset->CloseOnDisk();
5495 myNewMeshImpl->FileInfoFromString( info );
5501 // As all object that can be referred by hypothesis are created,
5502 // we can restore hypothesis data
5504 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5505 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5507 SMESH_Hypothesis_i* hyp = hyp_data->first;
5508 string & data = hyp_data->second;
5509 hyp->LoadFrom( data.c_str() );
5512 // Restore the rest mesh data
5514 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5515 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5517 aTopGroup = meshi_group->second;
5518 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5519 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5520 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5522 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5523 bool hasData = false;
5526 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5527 int newId = myStudyContext->findId( iorString.in() );
5528 int meshOldId = myStudyContext->getOldId( newId );
5530 // try to find mesh data dataset
5531 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5532 // load mesh "has data" flag
5533 aDataset = new HDFdataset( "Has data", aTopGroup );
5534 aDataset->OpenOnDisk();
5535 size = aDataset->GetSize();
5536 char* strHasData = new char[ size ];
5537 aDataset->ReadFromDisk( strHasData );
5538 aDataset->CloseOnDisk();
5539 if ( strcmp( strHasData, "1") == 0 ) {
5542 delete [] strHasData;
5545 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5546 // nodes and elements are not yet put into sub-meshes)
5547 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5548 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5549 aGroup->OpenOnDisk();
5550 // get number of applied algorithms
5551 int aNbSubObjects = aGroup->nInternalObjects();
5552 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5553 for ( int j = 0; j < aNbSubObjects; j++ ) {
5554 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5555 aGroup->InternalObjectIndentify( j, name_dataset );
5556 // check if it is an algorithm
5557 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5558 aDataset = new HDFdataset( name_dataset, aGroup );
5559 aDataset->OpenOnDisk();
5560 size = aDataset->GetSize();
5561 char* refFromFile = new char[ size ];
5562 aDataset->ReadFromDisk( refFromFile );
5563 aDataset->CloseOnDisk();
5564 // san - it is impossible to recover applied algorithms using their entries within Load() method
5565 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5566 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5567 int id = atoi( refFromFile );
5568 delete [] refFromFile;
5569 string anIOR = myStudyContext->getIORbyOldId( id );
5570 if ( !anIOR.empty() ) {
5571 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5572 if ( !CORBA::is_nil( hypObject ) ) {
5573 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5574 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5575 || !myNewMeshImpl->HasShapeToMesh()) )
5576 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5581 aGroup->CloseOnDisk();
5584 // try to get applied hypotheses
5585 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5586 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5587 aGroup->OpenOnDisk();
5588 // get number of applied hypotheses
5589 int aNbSubObjects = aGroup->nInternalObjects();
5590 for ( int j = 0; j < aNbSubObjects; j++ ) {
5591 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5592 aGroup->InternalObjectIndentify( j, name_dataset );
5593 // check if it is a hypothesis
5594 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5595 aDataset = new HDFdataset( name_dataset, aGroup );
5596 aDataset->OpenOnDisk();
5597 size = aDataset->GetSize();
5598 char* refFromFile = new char[ size ];
5599 aDataset->ReadFromDisk( refFromFile );
5600 aDataset->CloseOnDisk();
5601 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5602 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5603 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5604 int id = atoi( refFromFile );
5605 delete [] refFromFile;
5606 string anIOR = myStudyContext->getIORbyOldId( id );
5607 if ( !anIOR.empty() ) {
5608 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5609 if ( !CORBA::is_nil( hypObject ) ) {
5610 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5611 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5612 || !myNewMeshImpl->HasShapeToMesh()) )
5613 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5618 aGroup->CloseOnDisk();
5621 // --> try to find SUB-MESHES containers for each type of submesh
5622 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5623 const char* name_meshgroup = 0;
5624 if ( j == GetSubMeshOnVertexTag() )
5625 name_meshgroup = "SubMeshes On Vertex";
5626 else if ( j == GetSubMeshOnEdgeTag() )
5627 name_meshgroup = "SubMeshes On Edge";
5628 else if ( j == GetSubMeshOnWireTag() )
5629 name_meshgroup = "SubMeshes On Wire";
5630 else if ( j == GetSubMeshOnFaceTag() )
5631 name_meshgroup = "SubMeshes On Face";
5632 else if ( j == GetSubMeshOnShellTag() )
5633 name_meshgroup = "SubMeshes On Shell";
5634 else if ( j == GetSubMeshOnSolidTag() )
5635 name_meshgroup = "SubMeshes On Solid";
5636 else if ( j == GetSubMeshOnCompoundTag() )
5637 name_meshgroup = "SubMeshes On Compound";
5639 // try to get submeshes container HDF group
5640 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5641 // open submeshes containers HDF group
5642 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5643 aGroup->OpenOnDisk();
5645 // get number of submeshes
5646 int aNbSubMeshes = aGroup->nInternalObjects();
5647 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5649 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5650 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5651 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5652 // --> get submesh id
5653 int subid = atoi( name_submeshgroup + 7 );
5656 // open submesh HDF group
5657 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5658 aSubGroup->OpenOnDisk();
5660 // try to read and set reference to subshape
5661 GEOM::GEOM_Object_var aSubShapeObject;
5662 SMESH::SMESH_subMesh_var aSubMesh;
5664 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5665 // load submesh "Ref on shape" - it's an entry to SObject
5666 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5667 aDataset->OpenOnDisk();
5668 size = aDataset->GetSize();
5669 char* refFromFile = new char[ size ];
5670 aDataset->ReadFromDisk( refFromFile );
5671 aDataset->CloseOnDisk();
5672 if ( strlen( refFromFile ) > 0 ) {
5673 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5674 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5675 if ( !CORBA::is_nil( subShapeObject ) ) {
5676 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5677 if ( !aSubShapeObject->_is_nil() )
5678 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5679 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5680 if ( aSubMesh->_is_nil() )
5682 string iorSubString = GetORB()->object_to_string( aSubMesh );
5683 int newSubId = myStudyContext->findId( iorSubString );
5684 myStudyContext->mapOldToNew( subid, newSubId );
5687 delete [] refFromFile;
5690 if ( aSubMesh->_is_nil() )
5693 // try to get applied algorithms
5694 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5695 // open "applied algorithms" HDF group
5696 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5697 aSubSubGroup->OpenOnDisk();
5698 // get number of applied algorithms
5699 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5700 for ( int l = 0; l < aNbSubObjects; l++ ) {
5701 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5702 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5703 // check if it is an algorithm
5704 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5705 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5706 aDataset->OpenOnDisk();
5707 size = aDataset->GetSize();
5708 char* refFromFile = new char[ size ];
5709 aDataset->ReadFromDisk( refFromFile );
5710 aDataset->CloseOnDisk();
5712 int id = atoi( refFromFile );
5713 string anIOR = myStudyContext->getIORbyOldId( id );
5714 if ( !anIOR.empty() ) {
5715 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5716 if ( !CORBA::is_nil( hypObject ) ) {
5717 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5718 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5719 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5722 delete [] refFromFile;
5725 // close "applied algorithms" HDF group
5726 aSubSubGroup->CloseOnDisk();
5729 // try to get applied hypotheses
5730 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5731 // open "applied hypotheses" HDF group
5732 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5733 aSubSubGroup->OpenOnDisk();
5734 // get number of applied hypotheses
5735 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5736 for ( int l = 0; l < aNbSubObjects; l++ ) {
5737 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5738 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5739 // check if it is a hypothesis
5740 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5741 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5742 aDataset->OpenOnDisk();
5743 size = aDataset->GetSize();
5744 char* refFromFile = new char[ size ];
5745 aDataset->ReadFromDisk( refFromFile );
5746 aDataset->CloseOnDisk();
5748 int id = atoi( refFromFile );
5749 string anIOR = myStudyContext->getIORbyOldId( id );
5750 if ( !anIOR.empty() ) {
5751 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5752 if ( !CORBA::is_nil( hypObject ) ) {
5753 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5754 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5755 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5758 delete [] refFromFile;
5761 // close "APPLIED HYPOTHESES" hdf group
5762 aSubSubGroup->CloseOnDisk();
5765 // close SUB-MESH hdf group
5766 aSubGroup->CloseOnDisk();
5769 // close SUB-MESHES containers hdf group
5770 aGroup->CloseOnDisk();
5774 // try to get GROUPS
5775 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5776 char name_group[ 30 ];
5777 if ( ii == GetNodeGroupsTag() )
5778 strcpy( name_group, "Groups of Nodes" );
5779 else if ( ii == GetEdgeGroupsTag() )
5780 strcpy( name_group, "Groups of Edges" );
5781 else if ( ii == GetFaceGroupsTag() )
5782 strcpy( name_group, "Groups of Faces" );
5783 else if ( ii == GetVolumeGroupsTag() )
5784 strcpy( name_group, "Groups of Volumes" );
5785 else if ( ii == Get0DElementsGroupsTag() )
5786 strcpy( name_group, "Groups of 0D Elements" );
5787 else if ( ii == GetBallElementsGroupsTag() )
5788 strcpy( name_group, "Groups of Balls" );
5790 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5791 aGroup = new HDFgroup( name_group, aTopGroup );
5792 aGroup->OpenOnDisk();
5793 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5794 // within aGroup->ExistInternalObject( name )
5795 std::vector< std::string > subNames;
5796 TColStd_MapOfAsciiString mapOfNames;
5797 aGroup->GetAllObjects( subNames );
5798 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5799 mapOfNames.Add( subNames[ iN ].c_str() );
5801 for ( size_t j = 0; j < subNames.size(); j++ ) {
5802 const std::string& name_dataset = subNames[ j ];
5803 // check if it is a group
5804 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5807 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5810 int groupID = -1; // group local ID (also persistent)
5812 groupID = atoi( endptr + 1 );
5813 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5814 aDataset->OpenOnDisk();
5816 // Retrieve actual group name
5817 size = aDataset->GetSize();
5818 char* nameFromFile = new char[ size ];
5819 aDataset->ReadFromDisk( nameFromFile );
5820 aDataset->CloseOnDisk();
5822 // Try to find a shape reference
5823 TopoDS_Shape aShape;
5824 char aRefName[ 30 ];
5825 sprintf( aRefName, "Ref on shape %d", subid);
5826 if ( mapOfNames.Contains( aRefName ))
5828 // load mesh "Ref on shape" - it's an entry to SObject
5829 aDataset = new HDFdataset( aRefName, aGroup );
5830 aDataset->OpenOnDisk();
5831 size = aDataset->GetSize();
5832 char* refFromFile = new char[ size ];
5833 aDataset->ReadFromDisk( refFromFile );
5834 aDataset->CloseOnDisk();
5835 if ( strlen( refFromFile ) > 0 ) {
5836 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5837 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5838 if ( !CORBA::is_nil( shapeObject ) ) {
5839 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5840 if ( !aShapeObject->_is_nil() )
5841 aShape = GeomObjectToShape( aShapeObject );
5844 delete [] refFromFile;
5846 // Try to read a filter of SMESH_GroupOnFilter
5847 SMESH::Filter_var filter;
5848 SMESH_PredicatePtr predicate;
5849 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5850 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5852 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5853 aDataset->OpenOnDisk();
5854 size = aDataset->GetSize();
5855 char* persistStr = new char[ size ];
5856 aDataset->ReadFromDisk( persistStr );
5857 aDataset->CloseOnDisk();
5858 if ( strlen( persistStr ) > 0 ) {
5859 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5860 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5861 filters.push_back( filter );
5863 delete [] persistStr;
5866 // Create group servant
5867 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5868 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5869 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5870 delete [] nameFromFile;
5871 // Obtain a SMESHDS_Group object
5872 if ( aNewGroup->_is_nil() )
5875 string iorSubString = GetORB()->object_to_string( aNewGroup );
5876 int newSubId = myStudyContext->findId( iorSubString );
5877 myStudyContext->mapOldToNew( subid, newSubId );
5879 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5883 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5884 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5886 aFilterGroup->SetFilter( filter );
5887 filter->UnRegister();
5889 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5890 if ( !aGroupBaseDS )
5893 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5896 // Read color of the group
5897 char aGroupColorName[ 30 ];
5898 sprintf( aGroupColorName, "ColorGroup %d", subid);
5899 if ( mapOfNames.Contains( aGroupColorName ))
5901 aDataset = new HDFdataset( aGroupColorName, aGroup );
5902 aDataset->OpenOnDisk();
5903 size = aDataset->GetSize();
5904 double* anRGB = new double[ size ];
5905 aDataset->ReadFromDisk( anRGB );
5906 aDataset->CloseOnDisk();
5907 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5908 aGroupBaseDS->SetColor( aColor );
5913 aGroup->CloseOnDisk();
5917 // instead of reading mesh data, we read only brief information of all
5918 // objects: mesh, groups, sub-meshes (issue 0021208)
5921 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5922 meshfile.ToCString(), filename.ToCString(),
5926 // read Sub-Mesh ORDER if any
5927 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5928 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5929 aDataset->OpenOnDisk();
5930 size = aDataset->GetSize();
5931 int* smIDs = new int[ size ];
5932 aDataset->ReadFromDisk( smIDs );
5933 aDataset->CloseOnDisk();
5934 TListOfListOfInt anOrderIds;
5935 anOrderIds.push_back( TListOfInt() );
5936 for ( int i = 0; i < size; i++ )
5937 if ( smIDs[ i ] < 0 ) // is separator
5938 anOrderIds.push_back( TListOfInt() );
5940 anOrderIds.back().push_back(smIDs[ i ]);
5942 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5947 // update hyps needing full mesh data restored (issue 20918)
5948 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5950 SMESH_Hypothesis_i* hyp = hyp_data->first;
5951 hyp->UpdateAsMeshesRestored();
5954 // notify algos on completed restoration to set sub-mesh event listeners
5955 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5957 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5958 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5960 TopoDS_Shape myLocShape;
5961 if(myLocMesh.HasShapeToMesh())
5962 myLocShape = myLocMesh.GetShapeToMesh();
5964 myLocShape = SMESH_Mesh::PseudoShape();
5966 myLocMesh.GetSubMesh(myLocShape)->
5967 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5970 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5971 list< SMESH::Filter_var >::iterator f = filters.begin();
5972 for ( ; f != filters.end(); ++f )
5973 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5974 fi->FindBaseObjects();
5979 aTopGroup->CloseOnDisk();
5982 aFile->CloseOnDisk();
5985 // Remove temporary files created from the stream
5988 SMESH_File meshFile( meshfile.ToCString() );
5989 if ( !meshFile ) // no meshfile exists
5991 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5995 Engines::Container_var container = GetContainerRef();
5996 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5998 container_i->registerTemporaryFile( filename.ToCString() );
5999 container_i->registerTemporaryFile( meshfile.ToCString() );
6000 container_i->registerTemporaryFile( tmpDir.ToCString() );
6004 pd << ""; // prevent optimizing pd out
6006 // creation of tree nodes for all data objects in the study
6007 // to support tree representation customization and drag-n-drop:
6008 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6009 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6010 useCaseBuilder->SetRootCurrent();
6011 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6012 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6013 for (it->InitEx(true); it->More(); it->Next()) {
6014 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6021 //=============================================================================
6023 * SMESH_Gen_i::LoadASCII
6025 * Load SMESH module's data in ASCII format
6027 //=============================================================================
6029 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6030 const SALOMEDS::TMPFile& theStream,
6032 bool isMultiFile ) {
6033 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6034 return Load( theComponent, theStream, theURL, isMultiFile );
6036 //before call main ::Load method it's need for decipher text format to
6037 //binary ( "|xx" => x' )
6038 int size = theStream.length();
6039 if ( int((size / 3 )*3) != size ) //error size of buffer
6042 int real_size = int(size / 3);
6044 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6047 unsigned int c = -1;
6048 for ( int i = 0; i < real_size; i++ )
6050 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6051 sscanf( tmp, "%x", &c );
6052 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6055 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6057 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6060 //=============================================================================
6062 * SMESH_Gen_i::Close
6064 * Clears study-connected data when it is closed
6066 //=============================================================================
6068 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6070 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6072 // Clear study contexts data
6073 myStudyContext->Clear();
6075 // remove the tmp files meshes are loaded from
6076 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6078 // Clean trace of API methods calls
6084 //=============================================================================
6086 * SMESH_Gen_i::ComponentDataType
6088 * Get component data type
6090 //=============================================================================
6092 char* SMESH_Gen_i::ComponentDataType()
6094 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6095 return CORBA::string_dup( "SMESH" );
6099 //=============================================================================
6101 * SMESH_Gen_i::IORToLocalPersistentID
6103 * Transform data from transient form to persistent
6105 //=============================================================================
6107 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6108 const char* IORString,
6109 CORBA::Boolean /*isMultiFile*/,
6110 CORBA::Boolean /*isASCII*/ )
6112 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6114 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6115 int anId = myStudyContext->findId( IORString );
6117 if(MYDEBUG) MESSAGE( "VSR " << anId )
6119 sprintf( strId, "%d", anId );
6120 return CORBA::string_dup( strId );
6123 return CORBA::string_dup( "" );
6126 //=============================================================================
6128 * SMESH_Gen_i::LocalPersistentIDToIOR
6130 * Transform data from persistent form to transient
6132 //=============================================================================
6134 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6135 const char* aLocalPersistentID,
6136 CORBA::Boolean /*isMultiFile*/,
6137 CORBA::Boolean /*isASCII*/ )
6139 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6141 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6142 int anId = atoi( aLocalPersistentID );
6143 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6145 return CORBA::string_dup( "" );
6148 //=======================================================================
6149 //function : RegisterObject
6151 //=======================================================================
6153 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6155 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6156 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6157 return myStudyContext->addObject( string( iorString.in() ) );
6162 //================================================================================
6164 * \brief Return id of registered object
6165 * \param theObject - the Object
6166 * \retval int - Object id
6168 //================================================================================
6170 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6172 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6173 string iorString = GetORB()->object_to_string( theObject );
6174 return myStudyContext->findId( iorString );
6179 //=============================================================================
6181 * SMESH_Gen_i::SetName
6183 * Set a new object name
6185 //=============================================================================
6186 void SMESH_Gen_i::SetName(const char* theIOR,
6187 const char* theName)
6189 if ( theIOR && strcmp( theIOR, "" ) ) {
6190 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6191 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6192 if ( !aSO->_is_nil() ) {
6193 SetName( aSO, theName );
6198 // Version information
6199 char* SMESH_Gen_i::getVersion()
6201 #if SMESH_DEVELOPMENT
6202 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6204 return CORBA::string_dup(SMESH_VERSION_STR);
6208 //=================================================================================
6209 // function : Move()
6210 // purpose : Moves objects to the specified position.
6211 // Is used in the drag-n-drop functionality.
6212 //=================================================================================
6213 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6214 SALOMEDS::SObject_ptr where,
6217 if ( CORBA::is_nil( where ) ) return;
6219 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6220 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6221 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6222 std::string dataType = father->ComponentDataType();
6223 if ( dataType != "SMESH" ) return; // not a SMESH component
6225 SALOMEDS::SObject_var objAfter;
6226 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6227 // insert at given row -> find insertion position
6228 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6230 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6231 if ( i == row && useCaseIt->More() ) {
6232 objAfter = useCaseIt->Value();
6236 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6237 SALOMEDS::SObject_var sobj = what[i];
6238 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6239 // insert the object to the use case tree
6240 if ( !CORBA::is_nil( objAfter ) )
6241 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6243 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6246 //================================================================================
6248 * \brief Returns true if algorithm can be used to mesh a given geometry
6249 * \param [in] theAlgoType - the algorithm type
6250 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6251 * \param [in] theGeomObject - the geometry to mesh
6252 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6253 * else, returns \c True if at least one shape is meshable
6254 * \return CORBA::Boolean - can or can't
6256 //================================================================================
6258 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6259 const char* theLibName,
6260 GEOM::GEOM_Object_ptr theGeomObject,
6261 CORBA::Boolean toCheckAll)
6265 std::string aPlatformLibName;
6266 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6267 GenericHypothesisCreator_i* aCreator =
6268 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6271 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6272 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6273 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6280 SMESH_CATCH( SMESH::doNothing );
6283 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6288 //=================================================================================
6289 // function : GetInsideSphere
6290 // purpose : Collect indices of elements, which are located inside the sphere
6291 //=================================================================================
6292 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6293 SMESH::ElementType theElemType,
6299 SMESH::long_array_var aResult = new SMESH::long_array();
6300 if ( meshPart->_is_nil() )
6301 return aResult._retn();
6303 // 1. Create geometrical object
6304 gp_Pnt aP( theX, theY, theZ );
6305 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6307 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6309 if ( lst.size() > 0 ) {
6310 aResult->length( lst.size() );
6311 for ( size_t i = 0; i < lst.size(); i++ ) {
6312 aResult[i] = lst[i];
6315 return aResult._retn();
6318 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6319 SMESH::ElementType theElemType,
6320 CORBA::Double theX1,
6321 CORBA::Double theY1,
6322 CORBA::Double theZ1,
6323 CORBA::Double theX2,
6324 CORBA::Double theY2,
6325 CORBA::Double theZ2) {
6326 SMESH::long_array_var aResult = new SMESH::long_array();
6327 if( meshPart->_is_nil() )
6328 return aResult._retn();
6330 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6332 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6334 if( lst.size() > 0 ) {
6335 aResult->length( lst.size() );
6336 for ( size_t i = 0; i < lst.size(); i++ ) {
6337 aResult[i] = lst[i];
6340 return aResult._retn();
6343 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6344 SMESH::ElementType theElemType,
6348 CORBA::Double theDX,
6349 CORBA::Double theDY,
6350 CORBA::Double theDZ,
6352 CORBA::Double theR ){
6353 SMESH::long_array_var aResult = new SMESH::long_array();
6354 if( meshPart->_is_nil() )
6355 return aResult._retn();
6357 gp_Pnt aP( theX, theY, theZ );
6358 gp_Vec aV( theDX, theDY, theDZ );
6359 gp_Ax2 anAxes (aP, aV);
6361 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6363 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6365 if( lst.size() > 0 ) {
6366 aResult->length( lst.size() );
6367 for ( size_t i = 0; i < lst.size(); i++ ) {
6368 aResult[i] = lst[i];
6371 return aResult._retn();
6374 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6375 SMESH::ElementType theElemType,
6376 GEOM::GEOM_Object_ptr theGeom,
6377 CORBA::Double theTolerance ) {
6378 SMESH::long_array_var aResult = new SMESH::long_array();
6379 if( meshPart->_is_nil() || theGeom->_is_nil() )
6380 return aResult._retn();
6382 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6384 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6386 if( lst.size() > 0 ) {
6387 aResult->length( lst.size() );
6388 for ( size_t i = 0; i < lst.size(); i++ ) {
6389 aResult[i] = lst[i];
6392 return aResult._retn();
6397 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6398 SMESH::ElementType theElemType,
6399 TopoDS_Shape& aShape,
6400 double* theTolerance) {
6402 std::vector<long> res;
6403 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6405 if ( mesh->_is_nil() )
6408 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6412 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6417 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6418 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6419 anElementsOnShape->SetAllNodes( true );
6420 anElementsOnShape->SetMesh( meshDS );
6421 anElementsOnShape->SetShape( aShape, aType );
6424 anElementsOnShape->SetTolerance(*theTolerance);
6426 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6427 if ( !msource->_is_nil() ) { // Mesh case
6428 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6430 while ( elemIt->more() ) {
6431 const SMDS_MeshElement* anElem = elemIt->next();
6432 long anId = anElem->GetID();
6433 if ( anElementsOnShape->IsSatisfy( anId ) )
6434 res.push_back( anId );
6438 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6439 if ( !gsource->_is_nil() ) {
6440 if(theElemType == SMESH::NODE) {
6441 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6442 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6443 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6444 long anId = node->GetID();
6445 if ( anElementsOnShape->IsSatisfy( anId ) )
6446 res.push_back( anId );
6449 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6450 SMESH::long_array_var elems = gsource->GetListOfID();
6451 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6452 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6453 long anId = elem->GetID();
6454 if ( anElementsOnShape->IsSatisfy( anId ) )
6455 res.push_back( anId );
6460 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6461 if ( !smsource->_is_nil() ) {
6462 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6463 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6464 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6466 long anId = elem->GetID();
6467 if ( anElementsOnShape->IsSatisfy( anId ) )
6468 res.push_back( anId );
6476 //=============================================================================
6478 * SMESHEngine_factory
6480 * C factory, accessible with dlsym, after dlopen
6482 //=============================================================================
6486 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6487 PortableServer::POA_ptr poa,
6488 PortableServer::ObjectId* contId,
6489 const char* instanceName,
6490 const char* interfaceName )
6492 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6493 if(MYDEBUG) SCRUTE(interfaceName);
6494 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6495 return aSMESHGen->getId() ;