1 // Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MeshAlgos.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_subMeshEventListener.hxx"
45 #include "utilities.h"
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B2d.hxx>
50 #include <Bnd_B3d.hxx>
52 #include <GCPnts_AbscissaPoint.hxx>
53 #include <Geom2d_Circle.hxx>
54 #include <Geom2d_Line.hxx>
55 #include <Geom2d_TrimmedCurve.hxx>
56 #include <GeomAdaptor_Curve.hxx>
57 #include <Geom_Circle.hxx>
58 #include <Geom_Curve.hxx>
59 #include <Geom_Line.hxx>
60 #include <Geom_TrimmedCurve.hxx>
61 #include <Precision.hxx>
62 #include <Standard_ErrorHandler.hxx>
63 #include <TColStd_Array1OfReal.hxx>
65 #include <TopExp_Explorer.hxx>
66 #include <TopTools_IndexedMapOfShape.hxx>
67 #include <TopTools_MapOfShape.hxx>
69 #include <TopoDS_Edge.hxx>
70 #include <TopoDS_Face.hxx>
71 #include <TopoDS_Vertex.hxx>
85 //================================================================================
90 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
93 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
94 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
96 struct _MeshOfSolid : public SMESH_ProxyMesh,
97 public SMESH_subMeshEventListenerData
101 _MeshOfSolid( SMESH_Mesh* mesh)
102 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
104 SMESH_ProxyMesh::setMesh( *mesh );
107 // returns submesh for a geom face
108 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
110 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
111 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
113 void setNode2Node(const SMDS_MeshNode* srcNode,
114 const SMDS_MeshNode* proxyNode,
115 const SMESH_ProxyMesh::SubMesh* subMesh)
117 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
120 //--------------------------------------------------------------------------------
122 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
123 * It is used to clear an inferior dim sub-meshes modified by viscous layers
125 class _ShrinkShapeListener : SMESH_subMeshEventListener
127 _ShrinkShapeListener()
128 : SMESH_subMeshEventListener(/*isDeletable=*/false,
129 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
131 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
132 virtual void ProcessEvent(const int event,
134 SMESH_subMesh* solidSM,
135 SMESH_subMeshEventListenerData* data,
136 const SMESH_Hypothesis* hyp)
138 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
140 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
144 //--------------------------------------------------------------------------------
146 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
147 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
148 * delete the data as soon as it has been used
150 class _ViscousListener : SMESH_subMeshEventListener
153 SMESH_subMeshEventListener(/*isDeletable=*/false,
154 "StdMeshers_ViscousLayers::_ViscousListener") {}
155 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
157 virtual void ProcessEvent(const int event,
159 SMESH_subMesh* subMesh,
160 SMESH_subMeshEventListenerData* data,
161 const SMESH_Hypothesis* hyp)
163 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
165 // delete SMESH_ProxyMesh containing temporary faces
166 subMesh->DeleteEventListener( this );
169 // Finds or creates proxy mesh of the solid
170 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
171 const TopoDS_Shape& solid,
174 if ( !mesh ) return 0;
175 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
176 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
177 if ( !data && toCreate )
179 data = new _MeshOfSolid(mesh);
180 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
181 sm->SetEventListener( Get(), data, sm );
185 // Removes proxy mesh of the solid
186 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
188 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
192 //================================================================================
194 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
195 * the main shape when sub-mesh of the main shape is cleared,
196 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
199 //================================================================================
201 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
203 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
204 SMESH_subMeshEventListenerData* data =
205 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
208 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
209 data->mySubMeshes.end())
210 data->mySubMeshes.push_back( sub );
214 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
215 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
218 //--------------------------------------------------------------------------------
220 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
221 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
222 * The class is used to check validity of face or volumes around a smoothed node;
223 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
227 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
228 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
229 : _nPrev(nPrev), _nNext(nNext) {}
230 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
232 const double M[3][3] =
233 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
234 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
235 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
236 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
237 + M[0][1]*M[1][2]*M[2][0]
238 + M[0][2]*M[1][0]*M[2][1]
239 - M[0][0]*M[1][2]*M[2][1]
240 - M[0][1]*M[1][0]*M[2][2]
241 - M[0][2]*M[1][1]*M[2][0]);
242 return determinant > 1e-100;
244 bool IsForward(const gp_XY& tgtUV,
245 const SMDS_MeshNode* smoothedNode,
246 const TopoDS_Face& face,
247 SMESH_MesherHelper& helper,
248 const double refSign) const
250 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
251 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
252 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
254 return d*refSign > 1e-100;
256 bool IsNeighbour(const _Simplex& other) const
258 return _nPrev == other._nNext || _nNext == other._nPrev;
261 //--------------------------------------------------------------------------------
263 * Structure used to take into account surface curvature while smoothing
268 double _k; // factor to correct node smoothed position
269 double _h2lenRatio; // avgNormProj / (2*avgDist)
271 static _Curvature* New( double avgNormProj, double avgDist )
274 if ( fabs( avgNormProj / avgDist ) > 1./200 )
277 c->_r = avgDist * avgDist / avgNormProj;
278 c->_k = avgDist * avgDist / c->_r / c->_r;
279 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
280 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
284 double lenDelta(double len) const { return _k * ( _r + len ); }
285 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
288 //--------------------------------------------------------------------------------
290 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
294 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
295 const SMDS_MeshNode* _nodes[2];
296 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
298 double _wgt[2]; // weights of _nodes
299 _LayerEdge* _edges[2];
301 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
304 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
306 std::swap( _nodes[0], _nodes[1] );
307 std::swap( _wgt[0], _wgt[1] );
310 //--------------------------------------------------------------------------------
312 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
313 * and a node of the most internal layer (_nodes.back())
317 vector< const SMDS_MeshNode*> _nodes;
319 gp_XYZ _normal; // to solid surface
320 vector<gp_XYZ> _pos; // points computed during inflation
321 double _len; // length achived with the last step
322 double _cosin; // of angle (_normal ^ surface)
323 double _lenFactor; // to compute _len taking _cosin into account
325 // face or edge w/o layer along or near which _LayerEdge is inflated
327 // simplices connected to the source node (_nodes[0]);
328 // used for smoothing and quality check of _LayerEdge's based on the FACE
329 vector<_Simplex> _simplices;
330 // data for smoothing of _LayerEdge's based on the EDGE
331 _2NearEdges* _2neibors;
333 _Curvature* _curvature;
334 // TODO:: detele _Curvature, _plnNorm
336 void SetNewLength( double len, SMESH_MesherHelper& helper );
337 bool SetNewLength2d( Handle(Geom_Surface)& surface,
338 const TopoDS_Face& F,
339 SMESH_MesherHelper& helper );
340 void SetDataByNeighbors( const SMDS_MeshNode* n1,
341 const SMDS_MeshNode* n2,
342 SMESH_MesherHelper& helper);
343 void InvalidateStep( int curStep );
344 bool Smooth(int& badNb);
345 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
346 const TopoDS_Face& F,
347 SMESH_MesherHelper& helper);
348 bool FindIntersection( SMESH_ElementSearcher& searcher,
350 const double& epsilon,
351 const SMDS_MeshElement** face = 0);
352 bool SegTriaInter( const gp_Ax1& lastSegment,
353 const SMDS_MeshNode* n0,
354 const SMDS_MeshNode* n1,
355 const SMDS_MeshNode* n2,
357 const double& epsilon) const;
358 gp_Ax1 LastSegment(double& segLen) const;
359 bool IsOnEdge() const { return _2neibors; }
360 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
361 void SetCosin( double cosin );
365 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
367 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
368 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
371 //--------------------------------------------------------------------------------
373 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
375 //--------------------------------------------------------------------------------
377 * \brief Data of a SOLID
382 const StdMeshers_ViscousLayers* _hyp;
383 _MeshOfSolid* _proxyMesh;
384 set<TGeomID> _reversedFaceIds;
386 double _stepSize, _stepSizeCoeff;
387 const SMDS_MeshNode* _stepSizeNodes[2];
390 // edges of _n2eMap. We keep same data in two containers because
391 // iteration over the map is 5 time longer than over the vector
392 vector< _LayerEdge* > _edges;
394 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
395 // layers and a FACE w/o layers
396 // value: the shape (FACE or EDGE) to shrink mesh on.
397 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
398 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
400 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
401 set< TGeomID > _noShrinkFaces;
403 // <EDGE to smooth on> to <it's curve>
404 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
406 // end indices in _edges of _LayerEdge on one shape to smooth
407 vector< int > _endEdgeToSmooth;
409 double _epsilon; // precision for SegTriaInter()
411 int _index; // for debug
413 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
414 const StdMeshers_ViscousLayers* h=0,
415 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
418 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
421 Handle(Geom_Surface)& surface,
422 const TopoDS_Face& F,
423 SMESH_MesherHelper& helper);
425 //--------------------------------------------------------------------------------
427 * \brief Data of node on a shrinked FACE
431 const SMDS_MeshNode* _node;
432 //vector<const SMDS_MeshNode*> _nodesAround;
433 vector<_Simplex> _simplices; // for quality check
435 bool Smooth(int& badNb,
436 Handle(Geom_Surface)& surface,
437 SMESH_MesherHelper& helper,
438 const double refSign,
442 //--------------------------------------------------------------------------------
444 * \brief Builder of viscous layers
446 class _ViscousBuilder
451 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
452 const TopoDS_Shape& shape);
454 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
455 void RestoreListeners();
457 // computes SMESH_ProxyMesh::SubMesh::_n2n;
458 bool MakeN2NMap( _MeshOfSolid* pm );
462 bool findSolidsWithLayers();
463 bool findFacesWithLayers();
464 bool makeLayer(_SolidData& data);
465 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
466 SMESH_MesherHelper& helper, _SolidData& data);
467 bool findNeiborsOnEdge(const _LayerEdge* edge,
468 const SMDS_MeshNode*& n1,
469 const SMDS_MeshNode*& n2,
471 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
472 const set<TGeomID>& ingnoreShapes,
473 const _SolidData* dataToCheckOri = 0,
474 const bool toSort = false);
475 bool sortEdges( _SolidData& data,
476 vector< vector<_LayerEdge*> >& edgesByGeom);
477 void limitStepSize( _SolidData& data,
478 const SMDS_MeshElement* face,
480 void limitStepSize( _SolidData& data, const double minSize);
481 bool inflate(_SolidData& data);
482 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
483 bool smoothAnalyticEdge( _SolidData& data,
486 Handle(Geom_Surface)& surface,
487 const TopoDS_Face& F,
488 SMESH_MesherHelper& helper);
489 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
490 bool refine(_SolidData& data);
492 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
493 SMESH_MesherHelper& helper,
494 const SMESHDS_SubMesh* faceSubMesh );
495 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
496 bool addBoundaryElements();
498 bool error( const string& text, int solidID=-1 );
499 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
502 void makeGroupOfLE();
505 SMESH_ComputeErrorPtr _error;
507 vector< _SolidData > _sdVec;
508 set<TGeomID> _ignoreShapeIds;
511 //--------------------------------------------------------------------------------
513 * \brief Shrinker of nodes on the EDGE
517 vector<double> _initU;
518 vector<double> _normPar;
519 vector<const SMDS_MeshNode*> _nodes;
520 const _LayerEdge* _edges[2];
523 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
524 void Compute(bool set3D, SMESH_MesherHelper& helper);
525 void RestoreParams();
526 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
528 //--------------------------------------------------------------------------------
530 * \brief Class of temporary mesh face.
531 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
532 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
534 struct TmpMeshFace : public SMDS_MeshElement
536 vector<const SMDS_MeshNode* > _nn;
537 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
538 SMDS_MeshElement(id), _nn(nodes) {}
539 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
540 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
541 virtual vtkIdType GetVtkType() const { return -1; }
542 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
543 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
544 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
545 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
547 //--------------------------------------------------------------------------------
549 * \brief Class of temporary mesh face storing _LayerEdge it's based on
551 struct TmpMeshFaceOnEdge : public TmpMeshFace
553 _LayerEdge *_le1, *_le2;
554 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
555 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
557 _nn[0]=_le1->_nodes[0];
558 _nn[1]=_le1->_nodes.back();
559 _nn[2]=_le2->_nodes.back();
560 _nn[3]=_le2->_nodes[0];
563 } // namespace VISCOUS_3D
565 //================================================================================
566 // StdMeshers_ViscousLayers hypothesis
568 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
569 :SMESH_Hypothesis(hypId, studyId, gen),
570 _isToIgnoreShapes(18), _nbLayers(1), _thickness(1), _stretchFactor(1)
572 _name = StdMeshers_ViscousLayers::GetHypType();
573 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
574 } // --------------------------------------------------------------------------------
575 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
577 if ( faceIds != _shapeIds )
578 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
579 if ( _isToIgnoreShapes != toIgnore )
580 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
581 } // --------------------------------------------------------------------------------
582 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
584 if ( thickness != _thickness )
585 _thickness = thickness, NotifySubMeshesHypothesisModification();
586 } // --------------------------------------------------------------------------------
587 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
589 if ( _nbLayers != nb )
590 _nbLayers = nb, NotifySubMeshesHypothesisModification();
591 } // --------------------------------------------------------------------------------
592 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
594 if ( _stretchFactor != factor )
595 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
596 } // --------------------------------------------------------------------------------
598 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
599 const TopoDS_Shape& theShape,
600 const bool toMakeN2NMap) const
602 using namespace VISCOUS_3D;
603 _ViscousBuilder bulder;
604 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
605 if ( err && !err->IsOK() )
606 return SMESH_ProxyMesh::Ptr();
608 vector<SMESH_ProxyMesh::Ptr> components;
609 TopExp_Explorer exp( theShape, TopAbs_SOLID );
610 for ( ; exp.More(); exp.Next() )
612 if ( _MeshOfSolid* pm =
613 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
615 if ( toMakeN2NMap && !pm->_n2nMapComputed )
616 if ( !bulder.MakeN2NMap( pm ))
617 return SMESH_ProxyMesh::Ptr();
618 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
619 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
621 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
623 switch ( components.size() )
627 case 1: return components[0];
629 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
631 return SMESH_ProxyMesh::Ptr();
632 } // --------------------------------------------------------------------------------
633 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
635 save << " " << _nbLayers
637 << " " << _stretchFactor
638 << " " << _shapeIds.size();
639 for ( unsigned i = 0; i < _shapeIds.size(); ++i )
640 save << " " << _shapeIds[i];
641 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
643 } // --------------------------------------------------------------------------------
644 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
646 int nbFaces, faceID, shapeToTreat;
647 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
648 while ( _shapeIds.size() < nbFaces && load >> faceID )
649 _shapeIds.push_back( faceID );
650 if ( load >> shapeToTreat )
651 _isToIgnoreShapes = !shapeToTreat;
653 _isToIgnoreShapes = true; // old behavior
655 } // --------------------------------------------------------------------------------
656 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
657 const TopoDS_Shape& theShape)
662 // END StdMeshers_ViscousLayers hypothesis
663 //================================================================================
667 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
671 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
672 gp_Pnt p = BRep_Tool::Pnt( fromV );
673 double distF = p.SquareDistance( c->Value( f ));
674 double distL = p.SquareDistance( c->Value( l ));
675 c->D1(( distF < distL ? f : l), p, dir );
676 if ( distL < distF ) dir.Reverse();
679 //--------------------------------------------------------------------------------
680 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
681 SMESH_MesherHelper& helper)
684 double f,l; gp_Pnt p;
685 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
686 double u = helper.GetNodeU( E, atNode );
690 //--------------------------------------------------------------------------------
691 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
692 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
694 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
695 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
696 gp_Pnt p; gp_Vec du, dv, norm;
697 surface->D1( uv.X(),uv.Y(), p, du,dv );
701 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
702 double u = helper.GetNodeU( fromE, node, 0, &ok );
704 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
705 if ( o == TopAbs_REVERSED )
708 gp_Vec dir = norm ^ du;
710 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
711 helper.IsClosedEdge( fromE ))
713 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
714 else c->D1( f, p, dv );
715 if ( o == TopAbs_REVERSED )
717 gp_Vec dir2 = norm ^ dv;
718 dir = dir.Normalized() + dir2.Normalized();
722 //--------------------------------------------------------------------------------
723 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
724 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
725 bool& ok, double* cosin=0)
727 double f,l; TopLoc_Location loc;
728 vector< TopoDS_Edge > edges; // sharing a vertex
729 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
732 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
733 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
734 edges.push_back( *e );
737 if ( !( ok = ( edges.size() > 0 ))) return dir;
738 // get average dir of edges going fromV
740 //if ( edges.size() > 1 )
741 for ( unsigned i = 0; i < edges.size(); ++i )
743 edgeDir = getEdgeDir( edges[i], fromV );
744 double size2 = edgeDir.SquareModulus();
745 if ( size2 > numeric_limits<double>::min() )
746 edgeDir /= sqrt( size2 );
751 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
752 if ( edges.size() == 1 )
754 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
755 dir = fromEdgeDir + getFaceDir( F, edges[1], node, helper, ok );
756 else if ( dir * fromEdgeDir < 0 )
760 //dir /= edges.size();
762 double angle = gp_Vec( edgeDir ).Angle( dir );
763 *cosin = cos( angle );
768 //================================================================================
770 * \brief Returns true if a FACE is bound by a concave EDGE
772 //================================================================================
774 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
778 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
779 for ( ; eExp.More(); eExp.Next() )
781 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
782 if ( BRep_Tool::Degenerated( E )) continue;
783 // check if 2D curve is concave
784 BRepAdaptor_Curve2d curve( E, F );
785 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
786 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
787 curve.Intervals( intervals, GeomAbs_C2 );
788 bool isConvex = true;
789 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
791 double u1 = intervals( i );
792 double u2 = intervals( i+1 );
793 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
794 double cross = drv2 ^ drv1;
795 if ( E.Orientation() == TopAbs_REVERSED )
797 isConvex = ( cross < 1e-9 );
799 // check if concavity is strong enough to care about it
800 //const double maxAngle = 5 * Standard_PI180;
803 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
805 // map< double, const SMDS_MeshNode* > u2nodes;
806 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
807 // /*ignoreMedium=*/true, u2nodes))
809 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
810 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
811 // double uPrev = u2n->first;
812 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
814 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
815 // gp_Vec2d segmentDir( uvPrev, uv );
816 // curve.D1( uPrev, p, drv1 );
818 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
823 // uPrev = u2n->first;
829 //--------------------------------------------------------------------------------
830 // DEBUG. Dump intermediate node positions into a python script
835 const char* fname = "/tmp/viscous.py";
836 cout << "execfile('"<<fname<<"')"<<endl;
837 py = new ofstream(fname);
838 *py << "from smesh import *" << endl
839 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
840 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
844 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
847 ~PyDump() { Finish(); }
849 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
850 #define dumpMove(n) { _dumpMove(n, __LINE__);}
851 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
852 void _dumpFunction(const string& fun, int ln)
853 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
854 void _dumpMove(const SMDS_MeshNode* n, int ln)
855 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
856 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
857 void _dumpCmd(const string& txt, int ln)
858 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
859 void dumpFunctionEnd()
860 { if (py) *py<< " return"<< endl; }
861 void dumpChangeNodes( const SMDS_MeshElement* f )
862 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
863 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
864 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
866 struct PyDump { void Finish() {} };
867 #define dumpFunction(f) f
870 #define dumpFunctionEnd()
871 #define dumpChangeNodes(f)
875 using namespace VISCOUS_3D;
877 //================================================================================
879 * \brief Constructor of _ViscousBuilder
881 //================================================================================
883 _ViscousBuilder::_ViscousBuilder()
885 _error = SMESH_ComputeError::New(COMPERR_OK);
889 //================================================================================
891 * \brief Stores error description and returns false
893 //================================================================================
895 bool _ViscousBuilder::error(const string& text, int solidId )
897 _error->myName = COMPERR_ALGO_FAILED;
898 _error->myComment = string("Viscous layers builder: ") + text;
901 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
902 if ( !sm && !_sdVec.empty() )
903 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
904 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
906 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
907 if ( smError && smError->myAlgo )
908 _error->myAlgo = smError->myAlgo;
912 makeGroupOfLE(); // debug
917 //================================================================================
919 * \brief At study restoration, restore event listeners used to clear an inferior
920 * dim sub-mesh modified by viscous layers
922 //================================================================================
924 void _ViscousBuilder::RestoreListeners()
929 //================================================================================
931 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
933 //================================================================================
935 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
937 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
938 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
939 for ( ; fExp.More(); fExp.Next() )
941 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
942 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
944 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
946 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
949 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
950 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
952 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
953 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
954 while( prxIt->more() )
956 const SMDS_MeshElement* fSrc = srcIt->next();
957 const SMDS_MeshElement* fPrx = prxIt->next();
958 if ( fSrc->NbNodes() != fPrx->NbNodes())
959 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
960 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
961 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
964 pm->_n2nMapComputed = true;
968 //================================================================================
970 * \brief Does its job
972 //================================================================================
974 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
975 const TopoDS_Shape& theShape)
977 // TODO: set priority of solids during Gen::Compute()
981 // check if proxy mesh already computed
982 TopExp_Explorer exp( theShape, TopAbs_SOLID );
984 return error("No SOLID's in theShape"), _error;
986 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
987 return SMESH_ComputeErrorPtr(); // everything already computed
991 // TODO: ignore already computed SOLIDs
992 if ( !findSolidsWithLayers())
995 if ( !findFacesWithLayers() )
998 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1000 if ( ! makeLayer(_sdVec[i]) )
1003 if ( _sdVec[i]._edges.size() == 0 )
1006 if ( ! inflate(_sdVec[i]) )
1009 if ( ! refine(_sdVec[i]) )
1015 addBoundaryElements();
1017 makeGroupOfLE(); // debug
1023 //================================================================================
1025 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1027 //================================================================================
1029 bool _ViscousBuilder::findSolidsWithLayers()
1032 TopTools_IndexedMapOfShape allSolids;
1033 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1034 _sdVec.reserve( allSolids.Extent());
1036 SMESH_Gen* gen = _mesh->GetGen();
1037 for ( int i = 1; i <= allSolids.Extent(); ++i )
1039 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1040 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1041 if ( !algo ) continue;
1042 // TODO: check if algo is hidden
1043 const list <const SMESHDS_Hypothesis *> & allHyps =
1044 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1045 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1046 const StdMeshers_ViscousLayers* viscHyp = 0;
1047 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1048 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1051 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1054 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1055 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1058 if ( _sdVec.empty() )
1060 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1065 //================================================================================
1069 //================================================================================
1071 bool _ViscousBuilder::findFacesWithLayers()
1073 // collect all faces to ignore defined by hyp
1074 vector<TopoDS_Shape> ignoreFaces;
1075 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1077 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1078 for ( unsigned i = 0; i < ids.size(); ++i )
1080 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1081 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1083 _ignoreShapeIds.insert( ids[i] );
1084 ignoreFaces.push_back( s );
1089 // ignore internal faces
1090 SMESH_MesherHelper helper( *_mesh );
1091 TopExp_Explorer exp;
1092 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1094 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1095 for ( ; exp.More(); exp.Next() )
1097 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1098 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1100 _ignoreShapeIds.insert( faceInd );
1101 ignoreFaces.push_back( exp.Current() );
1102 if ( helper.IsReversedSubMesh( TopoDS::Face( exp.Current() )))
1103 _sdVec[i]._reversedFaceIds.insert( faceInd );
1108 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1109 TopTools_IndexedMapOfShape shapes;
1110 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1113 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1114 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1116 const TopoDS_Shape& edge = shapes(iE);
1117 // find 2 faces sharing an edge
1119 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1120 while ( fIt->more())
1122 const TopoDS_Shape* f = fIt->next();
1123 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1124 FF[ int( !FF[0].IsNull()) ] = *f;
1126 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1127 // check presence of layers on them
1129 for ( int j = 0; j < 2; ++j )
1130 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1131 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1132 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1134 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1135 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1138 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1139 // the algo of the SOLID sharing the FACE does not support it
1140 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1141 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1143 TopTools_MapOfShape noShrinkVertices;
1144 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1145 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1147 const TopoDS_Shape& fWOL = e2f->second;
1148 TGeomID edgeID = e2f->first;
1149 bool notShrinkFace = false;
1150 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1151 while ( soIt->more())
1153 const TopoDS_Shape* solid = soIt->next();
1154 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1155 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1156 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1157 notShrinkFace = true;
1158 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1160 if ( _sdVec[j]._solid.IsSame( *solid ) )
1161 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1162 notShrinkFace = false;
1165 if ( notShrinkFace )
1167 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1168 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1169 noShrinkVertices.Add( vExp.Current() );
1172 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1173 // to the found not shrinked fWOL's
1174 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1175 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1177 TGeomID edgeID = e2f->first;
1178 TopoDS_Vertex VV[2];
1179 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1180 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1182 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1183 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1192 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1194 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1197 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1198 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1200 const TopoDS_Shape& vertex = shapes(iV);
1201 // find faces WOL sharing the vertex
1202 vector< TopoDS_Shape > facesWOL;
1203 int totalNbFaces = 0;
1204 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1205 while ( fIt->more())
1207 const TopoDS_Shape* f = fIt->next();
1208 const int fID = getMeshDS()->ShapeToIndex( *f );
1209 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1212 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1213 facesWOL.push_back( *f );
1216 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1217 continue; // no layers at this vertex or no WOL
1218 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1219 switch ( facesWOL.size() )
1223 helper.SetSubShape( facesWOL[0] );
1224 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1226 TopoDS_Shape seamEdge;
1227 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1228 while ( eIt->more() && seamEdge.IsNull() )
1230 const TopoDS_Shape* e = eIt->next();
1231 if ( helper.IsRealSeam( *e ) )
1234 if ( !seamEdge.IsNull() )
1236 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1240 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1245 // find an edge shared by 2 faces
1246 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1247 while ( eIt->more())
1249 const TopoDS_Shape* e = eIt->next();
1250 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1251 helper.IsSubShape( *e, facesWOL[1]))
1253 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1259 return error("Not yet supported case", _sdVec[i]._index);
1267 //================================================================================
1269 * \brief Create the inner surface of the viscous layer and prepare data for infation
1271 //================================================================================
1273 bool _ViscousBuilder::makeLayer(_SolidData& data)
1275 // get all sub-shapes to make layers on
1276 set<TGeomID> subIds, faceIds;
1277 subIds = data._noShrinkFaces;
1278 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1279 for ( ; exp.More(); exp.Next() )
1280 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1282 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1283 faceIds.insert( fSubM->GetId() );
1284 SMESH_subMeshIteratorPtr subIt =
1285 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1286 while ( subIt->more() )
1287 subIds.insert( subIt->next()->GetId() );
1290 // make a map to find new nodes on sub-shapes shared with other SOLID
1291 map< TGeomID, TNode2Edge* > s2neMap;
1292 map< TGeomID, TNode2Edge* >::iterator s2ne;
1293 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1294 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1296 TGeomID shapeInd = s2s->first;
1297 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1299 if ( _sdVec[i]._index == data._index ) continue;
1300 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1301 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1302 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1304 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1310 // Create temporary faces and _LayerEdge's
1312 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1314 data._stepSize = Precision::Infinite();
1315 data._stepSizeNodes[0] = 0;
1317 SMESH_MesherHelper helper( *_mesh );
1318 helper.SetSubShape( data._solid );
1319 helper.SetElementsOnShape(true);
1321 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1322 TNode2Edge::iterator n2e2;
1324 // collect _LayerEdge's of shapes they are based on
1325 const int nbShapes = getMeshDS()->MaxShapeIndex();
1326 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1328 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1330 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1331 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1333 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1334 SMESH_ProxyMesh::SubMesh* proxySub =
1335 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1337 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1338 while ( eIt->more() )
1340 const SMDS_MeshElement* face = eIt->next();
1341 newNodes.resize( face->NbCornerNodes() );
1342 double faceMaxCosin = -1;
1343 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1345 const SMDS_MeshNode* n = face->GetNode(i);
1346 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1347 if ( !(*n2e).second )
1350 _LayerEdge* edge = new _LayerEdge();
1352 edge->_nodes.push_back( n );
1353 const int shapeID = n->getshapeId();
1354 edgesByGeom[ shapeID ].push_back( edge );
1356 // set edge data or find already refined _LayerEdge and get data from it
1357 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1358 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1359 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1361 _LayerEdge* foundEdge = (*n2e2).second;
1362 edge->Copy( *foundEdge, helper );
1363 // location of the last node is modified but we can restore
1364 // it by node position on _sWOL stored by the node
1365 const_cast< SMDS_MeshNode* >
1366 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1370 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1371 if ( !setEdgeData( *edge, subIds, helper, data ))
1374 dumpMove(edge->_nodes.back());
1375 if ( edge->_cosin > 0.01 )
1377 if ( edge->_cosin > faceMaxCosin )
1378 faceMaxCosin = edge->_cosin;
1381 newNodes[ i ] = n2e->second->_nodes.back();
1383 // create a temporary face
1384 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1385 proxySub->AddElement( newFace );
1387 // compute inflation step size by min size of element on a convex surface
1388 if ( faceMaxCosin > 0.1 )
1389 limitStepSize( data, face, faceMaxCosin );
1390 } // loop on 2D elements on a FACE
1391 } // loop on FACEs of a SOLID
1393 data._epsilon = 1e-7;
1394 if ( data._stepSize < 1. )
1395 data._epsilon *= data._stepSize;
1397 // Put _LayerEdge's into the vector data._edges
1399 if ( !sortEdges( data, edgesByGeom ))
1402 // Set target nodes into _Simplex and _2NearEdges
1403 TNode2Edge::iterator n2e;
1404 for ( unsigned i = 0; i < data._edges.size(); ++i )
1406 if ( data._edges[i]->IsOnEdge())
1407 for ( int j = 0; j < 2; ++j )
1409 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1410 break; // _LayerEdge is shared by two _SolidData's
1411 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1412 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1413 return error("_LayerEdge not found by src node", data._index);
1414 n = (*n2e).second->_nodes.back();
1415 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1418 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1420 _Simplex& s = data._edges[i]->_simplices[j];
1421 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1422 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1430 //================================================================================
1432 * \brief Compute inflation step size by min size of element on a convex surface
1434 //================================================================================
1436 void _ViscousBuilder::limitStepSize( _SolidData& data,
1437 const SMDS_MeshElement* face,
1441 double minSize = 10 * data._stepSize;
1442 const int nbNodes = face->NbCornerNodes();
1443 for ( int i = 0; i < nbNodes; ++i )
1445 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1446 const SMDS_MeshNode* curN = face->GetNode( i );
1447 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1448 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1450 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1451 if ( dist < minSize )
1452 minSize = dist, iN = i;
1455 double newStep = 0.8 * minSize / cosin;
1456 if ( newStep < data._stepSize )
1458 data._stepSize = newStep;
1459 data._stepSizeCoeff = 0.8 / cosin;
1460 data._stepSizeNodes[0] = face->GetNode( iN );
1461 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1465 //================================================================================
1467 * \brief Compute inflation step size by min size of element on a convex surface
1469 //================================================================================
1471 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1473 if ( minSize < data._stepSize )
1475 data._stepSize = minSize;
1476 if ( data._stepSizeNodes[0] )
1479 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1480 data._stepSizeCoeff = data._stepSize / dist;
1485 //================================================================================
1487 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1489 //================================================================================
1491 bool _ViscousBuilder::sortEdges( _SolidData& data,
1492 vector< vector<_LayerEdge*> >& edgesByGeom)
1494 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1495 // boundry inclined at a sharp angle to the shape
1497 list< TGeomID > shapesToSmooth;
1499 SMESH_MesherHelper helper( *_mesh );
1502 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1504 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1505 if ( eS.empty() ) continue;
1506 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1507 bool needSmooth = false;
1508 switch ( S.ShapeType() )
1512 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1513 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1515 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1516 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1517 if ( eV.empty() ) continue;
1518 double cosin = eV[0]->_cosin;
1520 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1524 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1525 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1527 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1528 eV[0]->_nodes[0], helper, ok);
1529 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1530 double angle = dir1.Angle( dir2 );
1531 cosin = cos( angle );
1533 needSmooth = ( cosin > 0.1 );
1539 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1541 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1542 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1543 if ( eE.empty() ) continue;
1544 if ( eE[0]->_sWOL.IsNull() )
1546 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1547 needSmooth = ( eE[i]->_cosin > 0.1 );
1551 const TopoDS_Face& F1 = TopoDS::Face( S );
1552 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1553 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1554 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1556 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1557 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1558 double angle = dir1.Angle( dir2 );
1559 double cosin = cos( angle );
1560 needSmooth = ( cosin > 0.1 );
1572 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1573 else shapesToSmooth.push_back ( iS );
1576 } // loop on edgesByGeom
1578 data._edges.reserve( data._n2eMap.size() );
1579 data._endEdgeToSmooth.clear();
1581 // first we put _LayerEdge's on shapes to smooth
1582 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1583 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1585 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1586 if ( eVec.empty() ) continue;
1587 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1588 data._endEdgeToSmooth.push_back( data._edges.size() );
1592 // then the rest _LayerEdge's
1593 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1595 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1596 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1603 //================================================================================
1605 * \brief Set data of _LayerEdge needed for smoothing
1606 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1608 //================================================================================
1610 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1611 const set<TGeomID>& subIds,
1612 SMESH_MesherHelper& helper,
1615 SMESH_MeshEditor editor(_mesh);
1617 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1618 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1622 edge._curvature = 0;
1624 // --------------------------
1625 // Compute _normal and _cosin
1626 // --------------------------
1629 edge._normal.SetCoord(0,0,0);
1631 int totalNbFaces = 0;
1633 gp_Vec du, dv, geomNorm;
1636 TGeomID shapeInd = node->getshapeId();
1637 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1638 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1639 TopoDS_Shape vertEdge;
1641 if ( onShrinkShape ) // one of faces the node is on has no layers
1643 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1644 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1646 // inflate from VERTEX along EDGE
1647 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1649 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1651 // inflate from VERTEX along FACE
1652 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1653 node, helper, normOK, &edge._cosin);
1657 // inflate from EDGE along FACE
1658 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1659 node, helper, normOK);
1662 else // layers are on all faces of SOLID the node is on
1664 // find indices of geom faces the node lies on
1665 set<TGeomID> faceIds;
1666 if ( posType == SMDS_TOP_FACE )
1668 faceIds.insert( node->getshapeId() );
1672 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1673 while ( fIt->more() )
1674 faceIds.insert( editor.FindShape(fIt->next()));
1677 set<TGeomID>::iterator id = faceIds.begin();
1679 for ( ; id != faceIds.end(); ++id )
1681 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1682 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1685 //nbLayerFaces += subIds.count( *id );
1686 F = TopoDS::Face( s );
1688 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1689 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1690 surface->D1( uv.X(),uv.Y(), p, du,dv );
1692 double size2 = geomNorm.SquareMagnitude();
1693 if ( size2 > numeric_limits<double>::min() )
1694 geomNorm /= sqrt( size2 );
1697 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1699 edge._normal += geomNorm.XYZ();
1701 if ( totalNbFaces == 0 )
1702 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1704 edge._normal /= totalNbFaces;
1709 edge._cosin = 0; break;
1711 case SMDS_TOP_EDGE: {
1712 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1713 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1714 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1715 edge._cosin = cos( angle );
1716 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1719 case SMDS_TOP_VERTEX: {
1720 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1721 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1722 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
1723 edge._cosin = cos( angle );
1724 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1728 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1732 double normSize = edge._normal.SquareModulus();
1733 if ( normSize < numeric_limits<double>::min() )
1734 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1736 edge._normal /= sqrt( normSize );
1738 // TODO: if ( !normOK ) then get normal by mesh faces
1740 // Set the rest data
1741 // --------------------
1742 if ( onShrinkShape )
1744 edge._sWOL = (*s2s).second;
1746 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1747 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1748 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1750 // set initial position which is parameters on _sWOL in this case
1751 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1753 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1754 edge._pos.push_back( gp_XYZ( u, 0, 0));
1755 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1759 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1760 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1761 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1766 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1768 if ( posType == SMDS_TOP_FACE )
1770 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1771 double avgNormProj = 0, avgLen = 0;
1772 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1774 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1775 avgNormProj += edge._normal * vec;
1776 avgLen += vec.Modulus();
1778 avgNormProj /= edge._simplices.size();
1779 avgLen /= edge._simplices.size();
1780 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1784 // Set neighbour nodes for a _LayerEdge based on EDGE
1786 if ( posType == SMDS_TOP_EDGE /*||
1787 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1789 edge._2neibors = new _2NearEdges;
1790 // target node instead of source ones will be set later
1791 if ( ! findNeiborsOnEdge( &edge,
1792 edge._2neibors->_nodes[0],
1793 edge._2neibors->_nodes[1],
1796 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1797 edge._2neibors->_nodes[1],
1801 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1806 //================================================================================
1808 * \brief Find 2 neigbor nodes of a node on EDGE
1810 //================================================================================
1812 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1813 const SMDS_MeshNode*& n1,
1814 const SMDS_MeshNode*& n2,
1817 const SMDS_MeshNode* node = edge->_nodes[0];
1818 const int shapeInd = node->getshapeId();
1819 SMESHDS_SubMesh* edgeSM = 0;
1820 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1823 edgeSM = getMeshDS()->MeshElements( shapeInd );
1824 if ( !edgeSM || edgeSM->NbElements() == 0 )
1825 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1829 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1830 while ( eIt->more() && !n2 )
1832 const SMDS_MeshElement* e = eIt->next();
1833 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1834 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1837 if (!edgeSM->Contains(e)) continue;
1841 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1842 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1844 ( iN++ ? n2 : n1 ) = nNeibor;
1847 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1851 //================================================================================
1853 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1855 //================================================================================
1857 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1858 const SMDS_MeshNode* n2,
1859 SMESH_MesherHelper& helper)
1861 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1864 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1865 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1866 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1870 double sumLen = vec1.Modulus() + vec2.Modulus();
1871 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1872 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1873 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1874 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1875 if ( _curvature ) delete _curvature;
1876 _curvature = _Curvature::New( avgNormProj, avgLen );
1878 // if ( _curvature )
1879 // cout << _nodes[0]->GetID()
1880 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1881 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1882 // << _curvature->lenDelta(0) << endl;
1887 if ( _sWOL.IsNull() )
1889 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1890 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1891 gp_XYZ plnNorm = dirE ^ _normal;
1892 double proj0 = plnNorm * vec1;
1893 double proj1 = plnNorm * vec2;
1894 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1896 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1897 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1902 //================================================================================
1904 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1905 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1907 //================================================================================
1909 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1911 _nodes = other._nodes;
1912 _normal = other._normal;
1914 _lenFactor = other._lenFactor;
1915 _cosin = other._cosin;
1916 _sWOL = other._sWOL;
1917 _2neibors = other._2neibors;
1918 _curvature = 0; std::swap( _curvature, other._curvature );
1919 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1921 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1923 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1924 _pos.push_back( gp_XYZ( u, 0, 0));
1928 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1929 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1933 //================================================================================
1935 * \brief Set _cosin and _lenFactor
1937 //================================================================================
1939 void _LayerEdge::SetCosin( double cosin )
1942 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1945 //================================================================================
1947 * \brief Fills a vector<_Simplex >
1949 //================================================================================
1951 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1952 vector<_Simplex>& simplices,
1953 const set<TGeomID>& ingnoreShapes,
1954 const _SolidData* dataToCheckOri,
1957 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1958 while ( fIt->more() )
1960 const SMDS_MeshElement* f = fIt->next();
1961 const TGeomID shapeInd = f->getshapeId();
1962 if ( ingnoreShapes.count( shapeInd )) continue;
1963 const int nbNodes = f->NbCornerNodes();
1964 int srcInd = f->GetNodeIndex( node );
1965 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1966 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1967 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1968 std::swap( nPrev, nNext );
1969 simplices.push_back( _Simplex( nPrev, nNext ));
1974 vector<_Simplex> sortedSimplices( simplices.size() );
1975 sortedSimplices[0] = simplices[0];
1977 for ( size_t i = 1; i < simplices.size(); ++i )
1979 for ( size_t j = 1; j < simplices.size(); ++j )
1980 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1982 sortedSimplices[i] = simplices[j];
1987 if ( nbFound == simplices.size() - 1 )
1988 simplices.swap( sortedSimplices );
1992 //================================================================================
1994 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1996 //================================================================================
1998 void _ViscousBuilder::makeGroupOfLE()
2001 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
2003 if ( _sdVec[i]._edges.empty() ) continue;
2004 // string name = SMESH_Comment("_LayerEdge's_") << i;
2006 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2007 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2008 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2010 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2011 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2013 _LayerEdge* le = _sdVec[i]._edges[j];
2014 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
2015 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2016 << ", " << le->_nodes[iN]->GetID() <<"])");
2017 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2021 dumpFunction( SMESH_Comment("makeNormals") << i );
2022 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2024 _LayerEdge& edge = *_sdVec[i]._edges[j];
2025 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2026 nXYZ += edge._normal * _sdVec[i]._stepSize;
2027 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2028 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2032 // name = SMESH_Comment("tmp_faces ") << i;
2033 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2034 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2035 // SMESH_MeshEditor editor( _mesh );
2036 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2037 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2038 for ( ; fExp.More(); fExp.Next() )
2040 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2042 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2043 while ( fIt->more())
2045 const SMDS_MeshElement* e = fIt->next();
2046 SMESH_Comment cmd("mesh.AddFace([");
2047 for ( int j=0; j < e->NbCornerNodes(); ++j )
2048 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2050 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2051 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2060 //================================================================================
2062 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2064 //================================================================================
2066 bool _ViscousBuilder::inflate(_SolidData& data)
2068 SMESH_MesherHelper helper( *_mesh );
2070 // Limit inflation step size by geometry size found by itersecting
2071 // normals of _LayerEdge's with mesh faces
2072 double geomSize = Precision::Infinite(), intersecDist;
2073 auto_ptr<SMESH_ElementSearcher> searcher
2074 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2075 data._proxyMesh->GetFaces( data._solid )) );
2076 for ( unsigned i = 0; i < data._edges.size(); ++i )
2078 if ( data._edges[i]->IsOnEdge() ) continue;
2079 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2080 if ( geomSize > intersecDist && intersecDist > 0 )
2081 geomSize = intersecDist;
2083 if ( data._stepSize > 0.3 * geomSize )
2084 limitStepSize( data, 0.3 * geomSize );
2086 const double tgtThick = data._hyp->GetTotalThickness();
2087 if ( data._stepSize > tgtThick )
2088 limitStepSize( data, tgtThick );
2090 if ( data._stepSize < 1. )
2091 data._epsilon = data._stepSize * 1e-7;
2094 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2097 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2098 int nbSteps = 0, nbRepeats = 0;
2099 while ( 1.01 * avgThick < tgtThick )
2101 // new target length
2102 curThick += data._stepSize;
2103 if ( curThick > tgtThick )
2105 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2109 // Elongate _LayerEdge's
2110 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2111 for ( unsigned i = 0; i < data._edges.size(); ++i )
2113 data._edges[i]->SetNewLength( curThick, helper );
2118 if ( !updateNormals( data, helper ) )
2121 // Improve and check quality
2122 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2126 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2127 for ( unsigned i = 0; i < data._edges.size(); ++i )
2129 data._edges[i]->InvalidateStep( nbSteps+1 );
2133 break; // no more inflating possible
2137 // Evaluate achieved thickness
2139 for ( unsigned i = 0; i < data._edges.size(); ++i )
2140 avgThick += data._edges[i]->_len;
2141 avgThick /= data._edges.size();
2143 cout << "-- Thickness " << avgThick << " reached" << endl;
2146 if ( distToIntersection < avgThick*1.5 )
2149 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2150 << avgThick << " ) * 1.5" << endl;
2155 limitStepSize( data, 0.25 * distToIntersection );
2156 if ( data._stepSizeNodes[0] )
2157 data._stepSize = data._stepSizeCoeff *
2158 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2162 return error("failed at the very first inflation step", data._index);
2167 //================================================================================
2169 * \brief Improve quality of layer inner surface and check intersection
2171 //================================================================================
2173 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2175 double & distToIntersection)
2177 if ( data._endEdgeToSmooth.empty() )
2178 return true; // no shapes needing smoothing
2180 bool moved, improved;
2182 SMESH_MesherHelper helper(*_mesh);
2183 Handle(Geom_Surface) surface;
2187 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2190 iEnd = data._endEdgeToSmooth[ iS ];
2192 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2193 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2195 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2196 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2197 helper.SetSubShape( F );
2198 surface = BRep_Tool::Surface( F );
2203 F.Nullify(); surface.Nullify();
2205 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2207 if ( data._edges[ iBeg ]->IsOnEdge() )
2209 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2211 // try a simple solution on an analytic EDGE
2212 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2218 for ( int i = iBeg; i < iEnd; ++i )
2220 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2222 dumpCmd( SMESH_Comment("# end step ")<<step);
2224 while ( moved && step++ < 5 );
2225 //cout << " NB STEPS: " << step << endl;
2232 int step = 0, badNb = 0; moved = true;
2233 while (( ++step <= 5 && moved ) || improved )
2235 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2236 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2237 int oldBadNb = badNb;
2240 for ( int i = iBeg; i < iEnd; ++i )
2241 moved |= data._edges[i]->Smooth(badNb);
2242 improved = ( badNb < oldBadNb );
2249 for ( int i = iBeg; i < iEnd; ++i )
2251 _LayerEdge* edge = data._edges[i];
2252 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2253 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2254 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2256 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2257 << " "<< edge->_simplices[j]._nPrev->GetID()
2258 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2266 } // loop on shapes to smooth
2268 // Check if the last segments of _LayerEdge intersects 2D elements;
2269 // checked elements are either temporary faces or faces on surfaces w/o the layers
2271 auto_ptr<SMESH_ElementSearcher> searcher
2272 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2273 data._proxyMesh->GetFaces( data._solid )) );
2275 distToIntersection = Precision::Infinite();
2277 const SMDS_MeshElement* intFace = 0;
2279 const SMDS_MeshElement* closestFace = 0;
2282 for ( unsigned i = 0; i < data._edges.size(); ++i )
2284 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2286 if ( distToIntersection > dist )
2288 distToIntersection = dist;
2291 closestFace = intFace;
2298 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2299 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2300 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2301 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2302 << ") distance = " << distToIntersection<< endl;
2309 //================================================================================
2311 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2312 * _LayerEdge's to be in a consequent order
2314 //================================================================================
2316 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2319 Handle(Geom_Surface)& surface,
2320 const TopoDS_Face& F,
2321 SMESH_MesherHelper& helper)
2323 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2325 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2327 if ( i2curve == _edge2curve.end() )
2329 // sort _LayerEdge's by position on the EDGE
2331 map< double, _LayerEdge* > u2edge;
2332 for ( int i = iFrom; i < iTo; ++i )
2333 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2335 ASSERT( u2edge.size() == iTo - iFrom );
2336 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2337 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2338 _edges[i] = u2e->second;
2340 // set _2neibors according to the new order
2341 for ( int i = iFrom; i < iTo-1; ++i )
2342 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2343 _edges[i]->_2neibors->reverse();
2344 if ( u2edge.size() > 1 &&
2345 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2346 _edges[iTo-1]->_2neibors->reverse();
2349 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2351 TopLoc_Location loc; double f,l;
2353 Handle(Geom_Line) line;
2354 Handle(Geom_Circle) circle;
2355 bool isLine, isCirc;
2356 if ( F.IsNull() ) // 3D case
2358 // check if the EDGE is a line
2359 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2360 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2361 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2363 line = Handle(Geom_Line)::DownCast( curve );
2364 circle = Handle(Geom_Circle)::DownCast( curve );
2365 isLine = (!line.IsNull());
2366 isCirc = (!circle.IsNull());
2368 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2371 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2372 while ( nIt->more() )
2373 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2374 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2376 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2377 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2378 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2379 for ( int i = 0; i < 3 && !isLine; ++i )
2380 isLine = ( size.Coord( i+1 ) <= lineTol );
2382 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2389 // check if the EDGE is a line
2390 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2391 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2392 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2394 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2395 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2396 isLine = (!line2d.IsNull());
2397 isCirc = (!circle2d.IsNull());
2399 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2402 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2403 while ( nIt->more() )
2404 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2405 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2407 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2408 for ( int i = 0; i < 2 && !isLine; ++i )
2409 isLine = ( size.Coord( i+1 ) <= lineTol );
2411 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2417 line = new Geom_Line( gp::OX() ); // only type does matter
2421 gp_Pnt2d p = circle2d->Location();
2422 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2423 circle = new Geom_Circle( ax, 1.); // only center position does matter
2427 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2435 return i2curve->second;
2438 //================================================================================
2440 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2442 //================================================================================
2444 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2447 Handle(Geom_Surface)& surface,
2448 const TopoDS_Face& F,
2449 SMESH_MesherHelper& helper)
2451 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2452 helper.GetMeshDS());
2453 TopoDS_Edge E = TopoDS::Edge( S );
2455 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2456 if ( curve.IsNull() ) return false;
2458 // compute a relative length of segments
2459 vector< double > len( iTo-iFrom+1 );
2461 double curLen, prevLen = len[0] = 1.0;
2462 for ( int i = iFrom; i < iTo; ++i )
2464 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2465 len[i-iFrom+1] = len[i-iFrom] + curLen;
2470 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2472 if ( F.IsNull() ) // 3D
2474 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2475 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2476 for ( int i = iFrom; i < iTo; ++i )
2478 double r = len[i-iFrom] / len.back();
2479 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2480 data._edges[i]->_pos.back() = newPos;
2481 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2482 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2483 dumpMove( tgtNode );
2488 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2489 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2490 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2491 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2493 int iPeriodic = helper.GetPeriodicIndex();
2494 if ( iPeriodic == 1 || iPeriodic == 2 )
2496 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2497 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2498 std::swap( uv0, uv1 );
2501 const gp_XY rangeUV = uv1 - uv0;
2502 for ( int i = iFrom; i < iTo; ++i )
2504 double r = len[i-iFrom] / len.back();
2505 gp_XY newUV = uv0 + r * rangeUV;
2506 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2508 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2509 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2510 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2511 dumpMove( tgtNode );
2513 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2514 pos->SetUParameter( newUV.X() );
2515 pos->SetVParameter( newUV.Y() );
2521 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2523 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2524 gp_Pnt center3D = circle->Location();
2526 if ( F.IsNull() ) // 3D
2528 return false; // TODO ???
2532 const gp_XY center( center3D.X(), center3D.Y() );
2534 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2535 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2536 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2537 gp_Vec2d vec0( center, uv0 );
2538 gp_Vec2d vecM( center, uvM );
2539 gp_Vec2d vec1( center, uv1 );
2540 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2541 double uMidl = vec0.Angle( vecM );
2542 if ( uLast * uMidl < 0. )
2543 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2544 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2546 gp_Ax2d axis( center, vec0 );
2547 gp_Circ2d circ( axis, radius );
2548 for ( int i = iFrom; i < iTo; ++i )
2550 double newU = uLast * len[i-iFrom] / len.back();
2551 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2552 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2554 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2555 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2556 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2557 dumpMove( tgtNode );
2559 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2560 pos->SetUParameter( newUV.X() );
2561 pos->SetVParameter( newUV.Y() );
2570 //================================================================================
2572 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2573 * _LayerEdge's on neighbor EDGE's
2575 //================================================================================
2577 bool _ViscousBuilder::updateNormals( _SolidData& data,
2578 SMESH_MesherHelper& helper )
2580 // make temporary quadrangles got by extrusion of
2581 // mesh edges along _LayerEdge._normal's
2583 vector< const SMDS_MeshElement* > tmpFaces;
2585 set< SMESH_TLink > extrudedLinks; // contains target nodes
2586 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2588 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2589 for ( unsigned i = 0; i < data._edges.size(); ++i )
2591 _LayerEdge* edge = data._edges[i];
2592 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2593 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2594 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2596 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2597 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2598 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2599 if ( !link_isnew.second )
2601 extrudedLinks.erase( link_isnew.first );
2602 continue; // already extruded and will no more encounter
2604 // look for a _LayerEdge containg tgt2
2605 // _LayerEdge* neiborEdge = 0;
2606 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2607 // while ( !neiborEdge && ++di <= data._edges.size() )
2609 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2610 // neiborEdge = data._edges[i+di];
2611 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2612 // neiborEdge = data._edges[i-di];
2614 // if ( !neiborEdge )
2615 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2616 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2618 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2619 tmpFaces.push_back( f );
2621 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2622 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2623 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2628 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2629 // Perform two loops on _LayerEdge on EDGE's:
2630 // 1) to find and fix intersection
2631 // 2) to check that no new intersection appears as result of 1)
2633 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2635 auto_ptr<SMESH_ElementSearcher> searcher
2636 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
2638 // 1) Find intersections
2640 const SMDS_MeshElement* face;
2641 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2642 TLEdge2LEdgeSet edge2CloseEdge;
2644 const double eps = data._epsilon * data._epsilon;
2645 for ( unsigned i = 0; i < data._edges.size(); ++i )
2647 _LayerEdge* edge = data._edges[i];
2648 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2649 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2651 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2652 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2653 ee.insert( f->_le1 );
2654 ee.insert( f->_le2 );
2655 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2656 edge2CloseEdge[ f->_le1 ].insert( edge );
2657 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2658 edge2CloseEdge[ f->_le2 ].insert( edge );
2662 // Set _LayerEdge._normal
2664 if ( !edge2CloseEdge.empty() )
2666 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2668 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2669 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2671 _LayerEdge* edge1 = e2ee->first;
2672 _LayerEdge* edge2 = 0;
2673 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2675 // find EDGEs the edges reside
2677 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2678 if ( S.ShapeType() != TopAbs_EDGE )
2679 continue; // TODO: find EDGE by VERTEX
2680 E1 = TopoDS::Edge( S );
2681 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2682 while ( E2.IsNull() && eIt != ee.end())
2684 _LayerEdge* e2 = *eIt++;
2685 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2686 if ( S.ShapeType() == TopAbs_EDGE )
2687 E2 = TopoDS::Edge( S ), edge2 = e2;
2689 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2691 // find 3 FACEs sharing 2 EDGEs
2693 TopoDS_Face FF1[2], FF2[2];
2694 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2695 while ( fIt->more() && FF1[1].IsNull())
2697 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2698 if ( helper.IsSubShape( *F, data._solid))
2699 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2701 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2702 while ( fIt->more() && FF2[1].IsNull())
2704 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2705 if ( helper.IsSubShape( *F, data._solid))
2706 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2708 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2709 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2710 std::swap( FF1[0], FF1[1] );
2711 if ( FF2[0].IsSame( FF1[0]) )
2712 std::swap( FF2[0], FF2[1] );
2713 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2716 // // get a new normal for edge1
2718 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2719 if ( edge1->_cosin < 0 )
2720 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2721 if ( edge2->_cosin < 0 )
2722 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2723 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2724 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2725 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2726 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2727 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2728 // newNorm.Normalize();
2730 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2731 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2732 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2733 newNorm.Normalize();
2735 edge1->_normal = newNorm.XYZ();
2737 // update data of edge1 depending on _normal
2738 const SMDS_MeshNode *n1, *n2;
2739 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2740 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2741 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2743 edge1->SetDataByNeighbors( n1, n2, helper );
2745 if ( edge1->_cosin < 0 )
2748 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2749 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2750 edge1->SetCosin( cos( angle ));
2752 // limit data._stepSize
2753 if ( edge1->_cosin > 0.1 )
2755 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2756 while ( fIt->more() )
2757 limitStepSize( data, fIt->next(), edge1->_cosin );
2759 // set new XYZ of target node
2760 edge1->InvalidateStep( 1 );
2762 edge1->SetNewLength( data._stepSize, helper );
2765 // Update normals and other dependent data of not intersecting _LayerEdge's
2766 // neighboring the intersecting ones
2768 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2770 _LayerEdge* edge1 = e2ee->first;
2771 if ( !edge1->_2neibors )
2773 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2775 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2776 if ( edge2CloseEdge.count ( neighbor ))
2777 continue; // j-th neighbor is also intersected
2778 _LayerEdge* prevEdge = edge1;
2779 const int nbSteps = 6;
2780 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2782 if ( !neighbor->_2neibors )
2783 break; // neighbor is on VERTEX
2785 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2786 if ( nextEdge == prevEdge )
2787 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2788 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2789 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2790 double r = double(step-1)/nbSteps;
2791 if ( !nextEdge->_2neibors )
2794 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2795 newNorm.Normalize();
2797 neighbor->_normal = newNorm;
2798 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2799 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2801 neighbor->InvalidateStep( 1 );
2803 neighbor->SetNewLength( data._stepSize, helper );
2805 // goto the next neighbor
2806 prevEdge = neighbor;
2807 neighbor = nextEdge;
2813 // 2) Check absence of intersections
2816 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2822 //================================================================================
2824 * \brief Looks for intersection of it's last segment with faces
2825 * \param distance - returns shortest distance from the last node to intersection
2827 //================================================================================
2829 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2831 const double& epsilon,
2832 const SMDS_MeshElement** face)
2834 vector< const SMDS_MeshElement* > suspectFaces;
2836 gp_Ax1 lastSegment = LastSegment(segLen);
2837 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2839 bool segmentIntersected = false;
2840 distance = Precision::Infinite();
2841 int iFace = -1; // intersected face
2842 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2844 const SMDS_MeshElement* face = suspectFaces[j];
2845 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2846 face->GetNodeIndex( _nodes[0] ) >= 0 )
2847 continue; // face sharing _LayerEdge node
2848 const int nbNodes = face->NbCornerNodes();
2849 bool intFound = false;
2851 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2854 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2858 const SMDS_MeshNode* tria[3];
2861 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2864 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2870 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
2871 segmentIntersected = true;
2872 if ( distance > dist )
2873 distance = dist, iFace = j;
2876 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2877 // if ( distance && iFace > -1 )
2879 // // distance is used to limit size of inflation step which depends on
2880 // // whether the intersected face bears viscous layers or not
2881 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2885 if ( segmentIntersected )
2888 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2889 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2890 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2891 << ", intersection with face ("
2892 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2893 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2894 << ") distance = " << distance - segLen<< endl;
2900 return segmentIntersected;
2903 //================================================================================
2905 * \brief Returns size and direction of the last segment
2907 //================================================================================
2909 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2911 // find two non-coincident positions
2912 gp_XYZ orig = _pos.back();
2914 int iPrev = _pos.size() - 2;
2915 while ( iPrev >= 0 )
2917 dir = orig - _pos[iPrev];
2918 if ( dir.SquareModulus() > 1e-100 )
2928 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2929 segDir.SetDirection( _normal );
2934 gp_Pnt pPrev = _pos[ iPrev ];
2935 if ( !_sWOL.IsNull() )
2937 TopLoc_Location loc;
2938 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2941 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2942 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2946 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2947 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2949 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2951 segDir.SetLocation( pPrev );
2952 segDir.SetDirection( dir );
2953 segLen = dir.Modulus();
2959 //================================================================================
2961 * \brief Test intersection of the last segment with a given triangle
2962 * using Moller-Trumbore algorithm
2963 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2965 //================================================================================
2967 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2968 const SMDS_MeshNode* n0,
2969 const SMDS_MeshNode* n1,
2970 const SMDS_MeshNode* n2,
2972 const double& EPSILON) const
2974 //const double EPSILON = 1e-6;
2976 gp_XYZ orig = lastSegment.Location().XYZ();
2977 gp_XYZ dir = lastSegment.Direction().XYZ();
2979 SMESH_TNodeXYZ vert0( n0 );
2980 SMESH_TNodeXYZ vert1( n1 );
2981 SMESH_TNodeXYZ vert2( n2 );
2983 /* calculate distance from vert0 to ray origin */
2984 gp_XYZ tvec = orig - vert0;
2986 if ( tvec * dir > EPSILON )
2987 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2990 gp_XYZ edge1 = vert1 - vert0;
2991 gp_XYZ edge2 = vert2 - vert0;
2993 /* begin calculating determinant - also used to calculate U parameter */
2994 gp_XYZ pvec = dir ^ edge2;
2996 /* if determinant is near zero, ray lies in plane of triangle */
2997 double det = edge1 * pvec;
2999 if (det > -EPSILON && det < EPSILON)
3001 double inv_det = 1.0 / det;
3003 /* calculate U parameter and test bounds */
3004 double u = ( tvec * pvec ) * inv_det;
3005 if (u < 0.0 || u > 1.0)
3008 /* prepare to test V parameter */
3009 gp_XYZ qvec = tvec ^ edge1;
3011 /* calculate V parameter and test bounds */
3012 double v = (dir * qvec) * inv_det;
3013 if ( v < 0.0 || u + v > 1.0 )
3016 /* calculate t, ray intersects triangle */
3017 t = (edge2 * qvec) * inv_det;
3019 // if (det < EPSILON)
3022 // /* calculate distance from vert0 to ray origin */
3023 // gp_XYZ tvec = orig - vert0;
3025 // /* calculate U parameter and test bounds */
3026 // double u = tvec * pvec;
3027 // if (u < 0.0 || u > det)
3030 // /* prepare to test V parameter */
3031 // gp_XYZ qvec = tvec ^ edge1;
3033 // /* calculate V parameter and test bounds */
3034 // double v = dir * qvec;
3035 // if (v < 0.0 || u + v > det)
3038 // /* calculate t, scale parameters, ray intersects triangle */
3039 // double t = edge2 * qvec;
3040 // double inv_det = 1.0 / det;
3048 //================================================================================
3050 * \brief Perform smooth of _LayerEdge's based on EDGE's
3051 * \retval bool - true if node has been moved
3053 //================================================================================
3055 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3056 const TopoDS_Face& F,
3057 SMESH_MesherHelper& helper)
3059 ASSERT( IsOnEdge() );
3061 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3062 SMESH_TNodeXYZ oldPos( tgtNode );
3063 double dist01, distNewOld;
3065 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3066 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3067 dist01 = p0.Distance( _2neibors->_nodes[1] );
3069 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3070 double lenDelta = 0;
3073 //lenDelta = _curvature->lenDelta( _len );
3074 lenDelta = _curvature->lenDeltaByDist( dist01 );
3075 newPos.ChangeCoord() += _normal * lenDelta;
3078 distNewOld = newPos.Distance( oldPos );
3082 if ( _2neibors->_plnNorm )
3084 // put newPos on the plane defined by source node and _plnNorm
3085 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3086 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3087 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3089 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3090 _pos.back() = newPos.XYZ();
3094 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3095 gp_XY uv( Precision::Infinite(), 0 );
3096 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3097 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3099 newPos = surface->Value( uv.X(), uv.Y() );
3100 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3103 if ( _curvature && lenDelta < 0 )
3105 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3106 _len -= prevPos.Distance( oldPos );
3107 _len += prevPos.Distance( newPos );
3109 bool moved = distNewOld > dist01/50;
3111 dumpMove( tgtNode ); // debug
3116 //================================================================================
3118 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3119 * \retval bool - true if _tgtNode has been moved
3121 //================================================================================
3123 bool _LayerEdge::Smooth(int& badNb)
3125 if ( _simplices.size() < 2 )
3126 return false; // _LayerEdge inflated along EDGE or FACE
3128 // compute new position for the last _pos
3129 gp_XYZ newPos (0,0,0);
3130 for ( unsigned i = 0; i < _simplices.size(); ++i )
3131 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3132 newPos /= _simplices.size();
3135 newPos += _normal * _curvature->lenDelta( _len );
3137 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3138 // if ( _cosin < -0.1)
3140 // // Avoid decreasing length of edge on concave surface
3141 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3142 // gp_Vec newMove( prevPos, newPos );
3143 // newPos = _pos.back() + newMove.XYZ();
3145 // else if ( _cosin > 0.3 )
3147 // // Avoid increasing length of edge too much
3150 // count quality metrics (orientation) of tetras around _tgtNode
3152 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3153 for ( unsigned i = 0; i < _simplices.size(); ++i )
3154 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3157 for ( unsigned i = 0; i < _simplices.size(); ++i )
3158 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3160 if ( nbOkAfter < nbOkBefore )
3163 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3165 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3166 _len += prevPos.Distance(newPos);
3168 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3169 _pos.back() = newPos;
3171 badNb += _simplices.size() - nbOkAfter;
3178 //================================================================================
3180 * \brief Add a new segment to _LayerEdge during inflation
3182 //================================================================================
3184 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3186 if ( _len - len > -1e-6 )
3188 _pos.push_back( _pos.back() );
3192 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3193 SMESH_TNodeXYZ oldXYZ( n );
3194 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3195 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3197 _pos.push_back( nXYZ );
3199 if ( !_sWOL.IsNull() )
3202 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3204 double u = Precision::Infinite(); // to force projection w/o distance check
3205 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3206 _pos.back().SetCoord( u, 0, 0 );
3207 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3208 pos->SetUParameter( u );
3212 gp_XY uv( Precision::Infinite(), 0 );
3213 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3214 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3215 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3216 pos->SetUParameter( uv.X() );
3217 pos->SetVParameter( uv.Y() );
3219 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3221 dumpMove( n ); //debug
3224 //================================================================================
3226 * \brief Remove last inflation step
3228 //================================================================================
3230 void _LayerEdge::InvalidateStep( int curStep )
3232 if ( _pos.size() > curStep )
3234 _pos.resize( curStep );
3235 gp_Pnt nXYZ = _pos.back();
3236 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3237 if ( !_sWOL.IsNull() )
3239 TopLoc_Location loc;
3240 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3242 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3243 pos->SetUParameter( nXYZ.X() );
3245 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3246 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3250 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3251 pos->SetUParameter( nXYZ.X() );
3252 pos->SetVParameter( nXYZ.Y() );
3253 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3254 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3257 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3262 //================================================================================
3264 * \brief Create layers of prisms
3266 //================================================================================
3268 bool _ViscousBuilder::refine(_SolidData& data)
3270 SMESH_MesherHelper helper( *_mesh );
3271 helper.SetSubShape( data._solid );
3272 helper.SetElementsOnShape(false);
3274 Handle(Geom_Curve) curve;
3275 Handle(Geom_Surface) surface;
3276 TopoDS_Edge geomEdge;
3277 TopoDS_Face geomFace;
3278 TopLoc_Location loc;
3279 double f,l, u/*, distXYZ[4]*/;
3283 for ( unsigned i = 0; i < data._edges.size(); ++i )
3285 _LayerEdge& edge = *data._edges[i];
3287 // get accumulated length of segments
3288 vector< double > segLen( edge._pos.size() );
3290 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3291 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3293 // allocate memory for new nodes if it is not yet refined
3294 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3295 if ( edge._nodes.size() == 2 )
3297 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3299 edge._nodes.back() = tgtNode;
3301 if ( !edge._sWOL.IsNull() )
3303 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3304 // restore position of the last node
3308 geomEdge = TopoDS::Edge( edge._sWOL );
3309 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3310 // double u = helper.GetNodeU( tgtNode );
3311 // p = curve->Value( u );
3315 geomFace = TopoDS::Face( edge._sWOL );
3316 surface = BRep_Tool::Surface( geomFace, loc );
3317 // gp_XY uv = helper.GetNodeUV( tgtNode );
3318 // p = surface->Value( uv.X(), uv.Y() );
3320 // p.Transform( loc );
3321 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3323 // calculate height of the first layer
3325 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3326 const double f = data._hyp->GetStretchFactor();
3327 const int N = data._hyp->GetNumberLayers();
3328 const double fPowN = pow( f, N );
3329 if ( fPowN - 1 <= numeric_limits<double>::min() )
3332 h0 = T * ( f - 1 )/( fPowN - 1 );
3334 const double zeroLen = std::numeric_limits<double>::min();
3336 // create intermediate nodes
3337 double hSum = 0, hi = h0/f;
3339 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3341 // compute an intermediate position
3344 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3346 int iPrevSeg = iSeg-1;
3347 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3349 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3350 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3352 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3353 if ( !edge._sWOL.IsNull() )
3355 // compute XYZ by parameters <pos>
3359 pos = curve->Value( u ).Transformed(loc);
3363 uv.SetCoord( pos.X(), pos.Y() );
3364 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3367 // create or update the node
3370 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3371 if ( !edge._sWOL.IsNull() )
3374 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3376 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3380 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3385 if ( !edge._sWOL.IsNull() )
3387 // make average pos from new and current parameters
3390 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3391 pos = curve->Value( u ).Transformed(loc);
3395 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3396 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3399 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3404 if ( !getMeshDS()->IsEmbeddedMode() )
3405 // Log node movement
3406 for ( unsigned i = 0; i < data._edges.size(); ++i )
3408 _LayerEdge& edge = *data._edges[i];
3409 SMESH_TNodeXYZ p ( edge._nodes.back() );
3410 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3413 // TODO: make quadratic prisms and polyhedrons(?)
3415 helper.SetElementsOnShape(true);
3417 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3418 for ( ; exp.More(); exp.Next() )
3420 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3422 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3423 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3424 vector< vector<const SMDS_MeshNode*>* > nnVec;
3425 while ( fIt->more() )
3427 const SMDS_MeshElement* face = fIt->next();
3428 int nbNodes = face->NbCornerNodes();
3429 nnVec.resize( nbNodes );
3430 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3431 for ( int iN = 0; iN < nbNodes; ++iN )
3433 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3434 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3437 int nbZ = nnVec[0]->size();
3441 for ( int iZ = 1; iZ < nbZ; ++iZ )
3442 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3443 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3446 for ( int iZ = 1; iZ < nbZ; ++iZ )
3447 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3448 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3449 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3450 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3453 return error("Not supported type of element", data._index);
3460 //================================================================================
3462 * \brief Shrink 2D mesh on faces to let space for inflated layers
3464 //================================================================================
3466 bool _ViscousBuilder::shrink()
3468 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3469 // inflated along FACE or EDGE)
3470 map< TGeomID, _SolidData* > f2sdMap;
3471 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3473 _SolidData& data = _sdVec[i];
3474 TopTools_MapOfShape FFMap;
3475 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3476 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3477 if ( s2s->second.ShapeType() == TopAbs_FACE )
3479 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3481 if ( FFMap.Add( (*s2s).second ))
3482 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3483 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3484 // by StdMeshers_QuadToTriaAdaptor
3485 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3487 SMESH_ProxyMesh::SubMesh* proxySub =
3488 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3489 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3490 while ( fIt->more() )
3491 proxySub->AddElement( fIt->next() );
3492 // as a result 3D algo will use elements from proxySub and not from smDS
3497 SMESH_MesherHelper helper( *_mesh );
3498 helper.ToFixNodeParameters( true );
3501 map< TGeomID, _Shrinker1D > e2shrMap;
3503 // loop on FACES to srink mesh on
3504 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3505 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3507 _SolidData& data = *f2sd->second;
3508 TNode2Edge& n2eMap = data._n2eMap;
3509 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3511 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3513 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3514 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3516 helper.SetSubShape(F);
3518 // ===========================
3519 // Prepare data for shrinking
3520 // ===========================
3522 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3523 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3524 vector < const SMDS_MeshNode* > smoothNodes;
3526 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3527 while ( nIt->more() )
3529 const SMDS_MeshNode* n = nIt->next();
3530 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3531 smoothNodes.push_back( n );
3534 // Find out face orientation
3536 const set<TGeomID> ignoreShapes;
3538 if ( !smoothNodes.empty() )
3540 vector<_Simplex> simplices;
3541 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3542 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3543 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3544 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3545 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3549 // Find _LayerEdge's inflated along F
3550 vector< _LayerEdge* > lEdges;
3552 SMESH_subMeshIteratorPtr subIt =
3553 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3554 while ( subIt->more() )
3556 SMESH_subMesh* sub = subIt->next();
3557 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3558 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3560 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3561 while ( nIt->more() )
3563 _LayerEdge* edge = n2eMap[ nIt->next() ];
3564 lEdges.push_back( edge );
3565 prepareEdgeToShrink( *edge, F, helper, smDS );
3570 // Replace source nodes by target nodes in mesh faces to shrink
3571 const SMDS_MeshNode* nodes[20];
3572 for ( unsigned i = 0; i < lEdges.size(); ++i )
3574 _LayerEdge& edge = *lEdges[i];
3575 const SMDS_MeshNode* srcNode = edge._nodes[0];
3576 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3577 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3578 while ( fIt->more() )
3580 const SMDS_MeshElement* f = fIt->next();
3581 if ( !smDS->Contains( f ))
3583 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3584 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3586 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3587 nodes[iN] = ( n == srcNode ? tgtNode : n );
3589 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3593 // find out if a FACE is concave
3594 const bool isConcaveFace = isConcave( F, helper );
3596 // Create _SmoothNode's on face F
3597 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3599 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3600 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3602 const SMDS_MeshNode* n = smoothNodes[i];
3603 nodesToSmooth[ i ]._node = n;
3604 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3605 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3606 // fix up incorrect uv of nodes on the FACE
3607 helper.GetNodeUV( F, n, 0, &isOkUV);
3612 //if ( nodesToSmooth.empty() ) continue;
3614 // Find EDGE's to shrink
3615 set< _Shrinker1D* > eShri1D;
3617 for ( unsigned i = 0; i < lEdges.size(); ++i )
3619 _LayerEdge* edge = lEdges[i];
3620 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3622 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3623 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3624 eShri1D.insert( & srinker );
3625 srinker.AddEdge( edge, helper );
3626 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3627 // restore params of nodes on EGDE if the EDGE has been already
3628 // srinked while srinking another FACE
3629 srinker.RestoreParams();
3634 // ==================
3635 // Perform shrinking
3636 // ==================
3638 bool shrinked = true;
3639 int badNb, shriStep=0, smooStep=0;
3642 // Move boundary nodes (actually just set new UV)
3643 // -----------------------------------------------
3644 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3646 for ( unsigned i = 0; i < lEdges.size(); ++i )
3648 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3652 // Move nodes on EDGE's
3653 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3654 for ( ; shr != eShri1D.end(); ++shr )
3655 (*shr)->Compute( /*set3D=*/false, helper );
3658 // -----------------
3659 int nbNoImpSteps = 0;
3662 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3664 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3666 int oldBadNb = badNb;
3669 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3671 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3672 /*isCentroidal=*/isConcaveFace,
3673 /*set3D=*/isConcaveFace);
3675 if ( badNb < oldBadNb )
3683 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3685 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3686 // First, find out a needed quality of smoothing (high for quadrangles only)
3689 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3690 if ( hasTria != hasQuad ) {
3691 highQuality = hasQuad;
3694 set<int> nbNodesSet;
3695 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3696 while ( fIt->more() && nbNodesSet.size() < 2 )
3697 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3698 highQuality = ( *nbNodesSet.begin() == 4 );
3701 if ( !highQuality && isConcaveFace )
3702 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3703 for ( int st = highQuality ? 10 : 3; st; --st )
3705 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3706 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3707 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3708 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3711 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3712 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3714 if ( !getMeshDS()->IsEmbeddedMode() )
3715 // Log node movement
3716 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3718 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3719 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3722 } // loop on FACES to srink mesh on
3725 // Replace source nodes by target nodes in shrinked mesh edges
3727 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3728 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3729 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3734 //================================================================================
3736 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3738 //================================================================================
3740 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3741 const TopoDS_Face& F,
3742 SMESH_MesherHelper& helper,
3743 const SMESHDS_SubMesh* faceSubMesh)
3745 const SMDS_MeshNode* srcNode = edge._nodes[0];
3746 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3750 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3752 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3753 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3754 gp_Vec2d uvDir( srcUV, tgtUV );
3755 double uvLen = uvDir.Magnitude();
3757 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3759 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3760 vector<const SMDS_MeshElement*> faces;
3761 multimap< double, const SMDS_MeshNode* > proj2node;
3762 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3763 while ( fIt->more() )
3765 const SMDS_MeshElement* f = fIt->next();
3766 if ( faceSubMesh->Contains( f ))
3767 faces.push_back( f );
3769 for ( unsigned i = 0; i < faces.size(); ++i )
3771 const int nbNodes = faces[i]->NbCornerNodes();
3772 for ( int j = 0; j < nbNodes; ++j )
3774 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3775 if ( n == srcNode ) continue;
3776 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3777 ( faces.size() > 1 || nbNodes > 3 ))
3779 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3780 gp_Vec2d uvDirN( srcUV, uv );
3781 double proj = uvDirN * uvDir;
3782 proj2node.insert( make_pair( proj, n ));
3786 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3787 const double minProj = p2n->first;
3788 const double projThreshold = 1.1 * uvLen;
3789 if ( minProj > projThreshold )
3791 // tgtNode is located so that it does not make faces with wrong orientation
3794 edge._pos.resize(1);
3795 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3797 // store most risky nodes in _simplices
3798 p2nEnd = proj2node.lower_bound( projThreshold );
3799 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3800 edge._simplices.resize( nbSimpl );
3801 for ( int i = 0; i < nbSimpl; ++i )
3803 edge._simplices[i]._nPrev = p2n->second;
3804 if ( ++p2n != p2nEnd )
3805 edge._simplices[i]._nNext = p2n->second;
3807 // set UV of source node to target node
3808 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3809 pos->SetUParameter( srcUV.X() );
3810 pos->SetVParameter( srcUV.Y() );
3812 else // _sWOL is TopAbs_EDGE
3814 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3815 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3816 if ( !edgeSM || edgeSM->NbElements() == 0 )
3817 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3819 const SMDS_MeshNode* n2 = 0;
3820 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3821 while ( eIt->more() && !n2 )
3823 const SMDS_MeshElement* e = eIt->next();
3824 if ( !edgeSM->Contains(e)) continue;
3825 n2 = e->GetNode( 0 );
3826 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3829 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3831 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3832 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3833 double u2 = helper.GetNodeU( E, n2, srcNode );
3835 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3837 // tgtNode is located so that it does not make faces with wrong orientation
3840 edge._pos.resize(1);
3841 edge._pos[0].SetCoord( U_TGT, uTgt );
3842 edge._pos[0].SetCoord( U_SRC, uSrc );
3843 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3845 edge._simplices.resize( 1 );
3846 edge._simplices[0]._nPrev = n2;
3848 // set UV of source node to target node
3849 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3850 pos->SetUParameter( uSrc );
3854 //================================================================================
3856 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3858 //================================================================================
3860 // Compute UV to follow during shrinking
3862 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3863 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3865 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3866 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3867 // gp_Vec2d uvDir( srcUV, tgtUV );
3868 // double uvLen = uvDir.Magnitude();
3871 // // Select shrinking step such that not to make faces with wrong orientation.
3872 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3873 // const double minStepSize = uvLen / 20;
3874 // double stepSize = uvLen;
3875 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3876 // while ( fIt->more() )
3878 // const SMDS_MeshElement* f = fIt->next();
3879 // if ( !faceSubMesh->Contains( f )) continue;
3880 // const int nbNodes = f->NbCornerNodes();
3881 // for ( int i = 0; i < nbNodes; ++i )
3883 // const SMDS_MeshNode* n = f->GetNode(i);
3884 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3886 // gp_XY uv = helper.GetNodeUV( F, n );
3887 // gp_Vec2d uvDirN( srcUV, uv );
3888 // double proj = uvDirN * uvDir;
3889 // if ( proj < stepSize && proj > minStepSize )
3895 // const int nbSteps = ceil( uvLen / stepSize );
3896 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3897 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3898 // edge._pos.resize( nbSteps );
3899 // edge._pos[0] = tgtUV0;
3900 // for ( int i = 1; i < nbSteps; ++i )
3902 // double r = i / double( nbSteps );
3903 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3908 //================================================================================
3910 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3912 //================================================================================
3914 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3916 SMESH::Controls::AspectRatio qualifier;
3917 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3918 const double maxAspectRatio = 4.;
3920 // find bad triangles
3922 vector< const SMDS_MeshElement* > badTrias;
3923 vector< double > badAspects;
3924 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3925 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3926 while ( fIt->more() )
3928 const SMDS_MeshElement * f = fIt->next();
3929 if ( f->NbCornerNodes() != 3 ) continue;
3930 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3931 double aspect = qualifier.GetValue( points );
3932 if ( aspect > maxAspectRatio )
3934 badTrias.push_back( f );
3935 badAspects.push_back( aspect );
3938 if ( badTrias.empty() )
3941 // find couples of faces to swap diagonal
3943 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3944 vector< T2Trias > triaCouples;
3946 TIDSortedElemSet involvedFaces, emptySet;
3947 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3950 double aspRatio [3];
3953 involvedFaces.insert( badTrias[iTia] );
3954 for ( int iP = 0; iP < 3; ++iP )
3955 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3957 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3958 int bestCouple = -1;
3959 for ( int iSide = 0; iSide < 3; ++iSide )
3961 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3962 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3963 trias [iSide].first = badTrias[iTia];
3964 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3966 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3969 // aspect ratio of an adjacent tria
3970 for ( int iP = 0; iP < 3; ++iP )
3971 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3972 double aspectInit = qualifier.GetValue( points2 );
3974 // arrange nodes as after diag-swaping
3975 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3976 i3 = helper.WrapIndex( i1-1, 3 );
3978 i3 = helper.WrapIndex( i1+1, 3 );
3980 points1( 1+ iSide ) = points2( 1+ i3 );
3981 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3983 // aspect ratio after diag-swaping
3984 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3985 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3988 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3992 if ( bestCouple >= 0 )
3994 triaCouples.push_back( trias[bestCouple] );
3995 involvedFaces.insert ( trias[bestCouple].second );
3999 involvedFaces.erase( badTrias[iTia] );
4002 if ( triaCouples.empty() )
4007 SMESH_MeshEditor editor( helper.GetMesh() );
4008 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4009 for ( size_t i = 0; i < triaCouples.size(); ++i )
4011 dumpChangeNodes( triaCouples[i].first );
4012 dumpChangeNodes( triaCouples[i].second );
4013 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4017 // just for debug dump resulting triangles
4018 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
4019 for ( size_t i = 0; i < triaCouples.size(); ++i )
4021 dumpChangeNodes( triaCouples[i].first );
4022 dumpChangeNodes( triaCouples[i].second );
4026 //================================================================================
4028 * \brief Move target node to it's final position on the FACE during shrinking
4030 //================================================================================
4032 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4033 const TopoDS_Face& F,
4034 SMESH_MesherHelper& helper )
4037 return false; // already at the target position
4039 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4041 if ( _sWOL.ShapeType() == TopAbs_FACE )
4043 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4044 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4045 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4046 const double uvLen = tgtUV.Distance( curUV );
4048 // Select shrinking step such that not to make faces with wrong orientation.
4049 const double kSafe = 0.8;
4050 const double minStepSize = uvLen / 10;
4051 double stepSize = uvLen;
4052 for ( unsigned i = 0; i < _simplices.size(); ++i )
4054 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4055 for ( int j = 0; j < 2; ++j )
4056 if ( const SMDS_MeshNode* n = nn[j] )
4058 gp_XY uv = helper.GetNodeUV( F, n );
4059 gp_Vec2d uvDirN( curUV, uv );
4060 double proj = uvDirN * uvDir * kSafe;
4061 if ( proj < stepSize && proj > minStepSize )
4067 if ( stepSize == uvLen )
4074 newUV = curUV + uvDir.XY() * stepSize;
4077 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4078 pos->SetUParameter( newUV.X() );
4079 pos->SetVParameter( newUV.Y() );
4082 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4083 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4084 dumpMove( tgtNode );
4087 else // _sWOL is TopAbs_EDGE
4089 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4090 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4092 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4093 const double uSrc = _pos[0].Coord( U_SRC );
4094 const double lenTgt = _pos[0].Coord( LEN_TGT );
4096 double newU = _pos[0].Coord( U_TGT );
4097 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4103 newU = 0.1 * uSrc + 0.9 * u2;
4105 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4106 pos->SetUParameter( newU );
4108 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4109 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4110 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4111 dumpMove( tgtNode );
4117 //================================================================================
4119 * \brief Perform smooth on the FACE
4120 * \retval bool - true if the node has been moved
4122 //================================================================================
4124 bool _SmoothNode::Smooth(int& badNb,
4125 Handle(Geom_Surface)& surface,
4126 SMESH_MesherHelper& helper,
4127 const double refSign,
4131 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4133 // get uv of surrounding nodes
4134 vector<gp_XY> uv( _simplices.size() );
4135 for ( size_t i = 0; i < _simplices.size(); ++i )
4136 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4138 // compute new UV for the node
4140 if ( isCentroidal && _simplices.size() > 3 )
4142 // average centers of diagonals wieghted with their reciprocal lengths
4143 if ( _simplices.size() == 4 )
4145 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4146 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4147 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4151 double sumWeight = 0;
4152 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4153 for ( int i = 0; i < nb; ++i )
4156 int iTo = i + _simplices.size() - 1;
4157 for ( int j = iFrom; j < iTo; ++j )
4159 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4160 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4162 newPos += w * ( uv[i]+uv[i2] );
4165 newPos /= 2 * sumWeight;
4171 isCentroidal = false;
4172 for ( size_t i = 0; i < _simplices.size(); ++i )
4174 newPos /= _simplices.size();
4177 // count quality metrics (orientation) of triangles around the node
4179 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4180 for ( unsigned i = 0; i < _simplices.size(); ++i )
4181 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4184 for ( unsigned i = 0; i < _simplices.size(); ++i )
4185 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4187 if ( nbOkAfter < nbOkBefore )
4189 // if ( isCentroidal )
4190 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4191 badNb += _simplices.size() - nbOkBefore;
4195 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4196 pos->SetUParameter( newPos.X() );
4197 pos->SetVParameter( newPos.Y() );
4204 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4205 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4209 badNb += _simplices.size() - nbOkAfter;
4210 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4213 //================================================================================
4215 * \brief Delete _SolidData
4217 //================================================================================
4219 _SolidData::~_SolidData()
4221 for ( unsigned i = 0; i < _edges.size(); ++i )
4223 if ( _edges[i] && _edges[i]->_2neibors )
4224 delete _edges[i]->_2neibors;
4229 //================================================================================
4231 * \brief Add a _LayerEdge inflated along the EDGE
4233 //================================================================================
4235 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4238 if ( _nodes.empty() )
4240 _edges[0] = _edges[1] = 0;
4244 if ( e == _edges[0] || e == _edges[1] )
4246 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4247 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4248 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4249 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4252 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4254 BRep_Tool::Range( E, f,l );
4255 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4256 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4260 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4261 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4263 if ( _nodes.empty() )
4265 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4266 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4268 TopLoc_Location loc;
4269 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4270 GeomAdaptor_Curve aCurve(C, f,l);
4271 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4273 int nbExpectNodes = eSubMesh->NbNodes();
4274 _initU .reserve( nbExpectNodes );
4275 _normPar.reserve( nbExpectNodes );
4276 _nodes .reserve( nbExpectNodes );
4277 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4278 while ( nIt->more() )
4280 const SMDS_MeshNode* node = nIt->next();
4281 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4282 node == tgtNode0 || node == tgtNode1 )
4283 continue; // refinement nodes
4284 _nodes.push_back( node );
4285 _initU.push_back( helper.GetNodeU( E, node ));
4286 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4287 _normPar.push_back( len / totLen );
4292 // remove target node of the _LayerEdge from _nodes
4294 for ( unsigned i = 0; i < _nodes.size(); ++i )
4295 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4296 _nodes[i] = 0, nbFound++;
4297 if ( nbFound == _nodes.size() )
4302 //================================================================================
4304 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4306 //================================================================================
4308 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4310 if ( _done || _nodes.empty())
4312 const _LayerEdge* e = _edges[0];
4313 if ( !e ) e = _edges[1];
4316 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4317 ( !_edges[1] || _edges[1]->_pos.empty() ));
4319 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4321 if ( set3D || _done )
4323 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4324 GeomAdaptor_Curve aCurve(C, f,l);
4327 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4329 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4330 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4332 for ( unsigned i = 0; i < _nodes.size(); ++i )
4334 if ( !_nodes[i] ) continue;
4335 double len = totLen * _normPar[i];
4336 GCPnts_AbscissaPoint discret( aCurve, len, f );
4337 if ( !discret.IsDone() )
4338 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4339 double u = discret.Parameter();
4340 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4341 pos->SetUParameter( u );
4342 gp_Pnt p = C->Value( u );
4343 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4348 BRep_Tool::Range( E, f,l );
4350 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4352 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4354 for ( unsigned i = 0; i < _nodes.size(); ++i )
4356 if ( !_nodes[i] ) continue;
4357 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4358 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4359 pos->SetUParameter( u );
4364 //================================================================================
4366 * \brief Restore initial parameters of nodes on EDGE
4368 //================================================================================
4370 void _Shrinker1D::RestoreParams()
4373 for ( unsigned i = 0; i < _nodes.size(); ++i )
4375 if ( !_nodes[i] ) continue;
4376 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4377 pos->SetUParameter( _initU[i] );
4382 //================================================================================
4384 * \brief Replace source nodes by target nodes in shrinked mesh edges
4386 //================================================================================
4388 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4390 const SMDS_MeshNode* nodes[3];
4391 for ( int i = 0; i < 2; ++i )
4393 if ( !_edges[i] ) continue;
4395 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4396 if ( !eSubMesh ) return;
4397 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4398 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4399 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4400 while ( eIt->more() )
4402 const SMDS_MeshElement* e = eIt->next();
4403 if ( !eSubMesh->Contains( e ))
4405 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4406 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4408 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4409 nodes[iN] = ( n == srcNode ? tgtNode : n );
4411 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4416 //================================================================================
4418 * \brief Creates 2D and 1D elements on boundaries of new prisms
4420 //================================================================================
4422 bool _ViscousBuilder::addBoundaryElements()
4424 SMESH_MesherHelper helper( *_mesh );
4426 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4428 _SolidData& data = _sdVec[i];
4429 TopTools_IndexedMapOfShape geomEdges;
4430 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4431 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4433 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4435 // Get _LayerEdge's based on E
4437 map< double, const SMDS_MeshNode* > u2nodes;
4438 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4441 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4442 TNode2Edge & n2eMap = data._n2eMap;
4443 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4445 //check if 2D elements are needed on E
4446 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4447 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4448 ledges.push_back( n2e->second );
4450 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4451 continue; // no layers on E
4452 ledges.push_back( n2eMap[ u2n->second ]);
4454 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4455 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4456 int nbSharedPyram = 0;
4457 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4458 while ( vIt->more() )
4460 const SMDS_MeshElement* v = vIt->next();
4461 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4463 if ( nbSharedPyram > 1 )
4464 continue; // not free border of the pyramid
4466 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4467 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4468 continue; // faces already created
4470 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4471 ledges.push_back( n2eMap[ u2n->second ]);
4473 // Find out orientation and type of face to create
4475 bool reverse = false, isOnFace;
4477 map< TGeomID, TopoDS_Shape >::iterator e2f =
4478 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4480 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4482 F = e2f->second.Oriented( TopAbs_FORWARD );
4483 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4484 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4485 reverse = !reverse, F.Reverse();
4486 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
4491 // find FACE with layers sharing E
4492 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4493 while ( fIt->more() && F.IsNull() )
4495 const TopoDS_Shape* pF = fIt->next();
4496 if ( helper.IsSubShape( *pF, data._solid) &&
4497 !_ignoreShapeIds.count( e2f->first ))
4501 // Find the sub-mesh to add new faces
4502 SMESHDS_SubMesh* sm = 0;
4504 sm = getMeshDS()->MeshElements( F );
4506 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4508 return error("error in addBoundaryElements()", data._index);
4511 const int dj1 = reverse ? 0 : 1;
4512 const int dj2 = reverse ? 1 : 0;
4513 for ( unsigned j = 1; j < ledges.size(); ++j )
4515 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4516 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4518 for ( size_t z = 1; z < nn1.size(); ++z )
4519 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4521 for ( size_t z = 1; z < nn1.size(); ++z )
4522 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4526 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4528 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4529 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4531 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4532 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4534 helper.SetSubShape( edge->_sWOL );
4535 helper.SetElementsOnShape( true );
4536 for ( size_t z = 1; z < nn.size(); ++z )
4537 helper.AddEdge( nn[z-1], nn[z] );