1 // Copyright (C) 2007-2014 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, or (at your option) any later version.
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_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
90 //================================================================================
95 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
98 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
99 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
101 struct _MeshOfSolid : public SMESH_ProxyMesh,
102 public SMESH_subMeshEventListenerData
104 bool _n2nMapComputed;
106 _MeshOfSolid( SMESH_Mesh* mesh)
107 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
109 SMESH_ProxyMesh::setMesh( *mesh );
112 // returns submesh for a geom face
113 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
115 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
116 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
118 void setNode2Node(const SMDS_MeshNode* srcNode,
119 const SMDS_MeshNode* proxyNode,
120 const SMESH_ProxyMesh::SubMesh* subMesh)
122 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
125 //--------------------------------------------------------------------------------
127 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
128 * It is used to clear an inferior dim sub-meshes modified by viscous layers
130 class _ShrinkShapeListener : SMESH_subMeshEventListener
132 _ShrinkShapeListener()
133 : SMESH_subMeshEventListener(/*isDeletable=*/false,
134 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
136 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
137 virtual void ProcessEvent(const int event,
139 SMESH_subMesh* solidSM,
140 SMESH_subMeshEventListenerData* data,
141 const SMESH_Hypothesis* hyp)
143 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
145 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
149 //--------------------------------------------------------------------------------
151 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
152 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
153 * delete the data as soon as it has been used
155 class _ViscousListener : SMESH_subMeshEventListener
158 SMESH_subMeshEventListener(/*isDeletable=*/false,
159 "StdMeshers_ViscousLayers::_ViscousListener") {}
160 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
162 virtual void ProcessEvent(const int event,
164 SMESH_subMesh* subMesh,
165 SMESH_subMeshEventListenerData* data,
166 const SMESH_Hypothesis* hyp)
168 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
170 // delete SMESH_ProxyMesh containing temporary faces
171 subMesh->DeleteEventListener( this );
174 // Finds or creates proxy mesh of the solid
175 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
176 const TopoDS_Shape& solid,
179 if ( !mesh ) return 0;
180 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
181 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
182 if ( !data && toCreate )
184 data = new _MeshOfSolid(mesh);
185 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
186 sm->SetEventListener( Get(), data, sm );
190 // Removes proxy mesh of the solid
191 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
193 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
197 //================================================================================
199 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
200 * the main shape when sub-mesh of the main shape is cleared,
201 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
204 //================================================================================
206 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
208 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
209 SMESH_subMeshEventListenerData* data =
210 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
213 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
214 data->mySubMeshes.end())
215 data->mySubMeshes.push_back( sub );
219 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
220 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
223 //--------------------------------------------------------------------------------
225 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
226 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
227 * The class is used to check validity of face or volumes around a smoothed node;
228 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
232 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
233 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
234 _Simplex(const SMDS_MeshNode* nPrev=0,
235 const SMDS_MeshNode* nNext=0,
236 const SMDS_MeshNode* nOpp=0)
237 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
238 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
240 const double M[3][3] =
241 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
242 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
243 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
244 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
245 + M[0][1]*M[1][2]*M[2][0]
246 + M[0][2]*M[1][0]*M[2][1]
247 - M[0][0]*M[1][2]*M[2][1]
248 - M[0][1]*M[1][0]*M[2][2]
249 - M[0][2]*M[1][1]*M[2][0]);
250 return determinant > 1e-100;
252 bool IsForward(const gp_XY& tgtUV,
253 const SMDS_MeshNode* smoothedNode,
254 const TopoDS_Face& face,
255 SMESH_MesherHelper& helper,
256 const double refSign) const
258 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
259 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
260 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
262 return d*refSign > 1e-100;
264 bool IsNeighbour(const _Simplex& other) const
266 return _nPrev == other._nNext || _nNext == other._nPrev;
269 //--------------------------------------------------------------------------------
271 * Structure used to take into account surface curvature while smoothing
276 double _k; // factor to correct node smoothed position
277 double _h2lenRatio; // avgNormProj / (2*avgDist)
279 static _Curvature* New( double avgNormProj, double avgDist )
282 if ( fabs( avgNormProj / avgDist ) > 1./200 )
285 c->_r = avgDist * avgDist / avgNormProj;
286 c->_k = avgDist * avgDist / c->_r / c->_r;
287 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
288 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
292 double lenDelta(double len) const { return _k * ( _r + len ); }
293 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
296 //--------------------------------------------------------------------------------
298 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
302 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
303 const SMDS_MeshNode* _nodes[2];
304 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
306 double _wgt[2]; // weights of _nodes
307 _LayerEdge* _edges[2];
309 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
312 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
314 std::swap( _nodes[0], _nodes[1] );
315 std::swap( _wgt[0], _wgt[1] );
318 //--------------------------------------------------------------------------------
320 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
321 * and a node of the most internal layer (_nodes.back())
325 vector< const SMDS_MeshNode*> _nodes;
327 gp_XYZ _normal; // to solid surface
328 vector<gp_XYZ> _pos; // points computed during inflation
329 double _len; // length achived with the last step
330 double _cosin; // of angle (_normal ^ surface)
331 double _lenFactor; // to compute _len taking _cosin into account
333 // face or edge w/o layer along or near which _LayerEdge is inflated
335 // simplices connected to the source node (_nodes[0]);
336 // used for smoothing and quality check of _LayerEdge's based on the FACE
337 vector<_Simplex> _simplices;
338 // data for smoothing of _LayerEdge's based on the EDGE
339 _2NearEdges* _2neibors;
341 _Curvature* _curvature;
342 // TODO:: detele _Curvature, _plnNorm
344 void SetNewLength( double len, SMESH_MesherHelper& helper );
345 bool SetNewLength2d( Handle(Geom_Surface)& surface,
346 const TopoDS_Face& F,
347 SMESH_MesherHelper& helper );
348 void SetDataByNeighbors( const SMDS_MeshNode* n1,
349 const SMDS_MeshNode* n2,
350 SMESH_MesherHelper& helper);
351 void InvalidateStep( int curStep );
352 bool Smooth(int& badNb);
353 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
354 const TopoDS_Face& F,
355 SMESH_MesherHelper& helper);
356 bool FindIntersection( SMESH_ElementSearcher& searcher,
358 const double& epsilon,
359 const SMDS_MeshElement** face = 0);
360 bool SegTriaInter( const gp_Ax1& lastSegment,
361 const SMDS_MeshNode* n0,
362 const SMDS_MeshNode* n1,
363 const SMDS_MeshNode* n2,
365 const double& epsilon) const;
366 gp_Ax1 LastSegment(double& segLen) const;
367 bool IsOnEdge() const { return _2neibors; }
368 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
369 void SetCosin( double cosin );
373 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
375 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
376 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
379 //--------------------------------------------------------------------------------
381 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
383 //--------------------------------------------------------------------------------
385 * \brief Data of a SOLID
390 const StdMeshers_ViscousLayers* _hyp;
391 TopoDS_Shape _hypShape;
392 _MeshOfSolid* _proxyMesh;
393 set<TGeomID> _reversedFaceIds;
394 set<TGeomID> _ignoreFaceIds;
396 double _stepSize, _stepSizeCoeff;
397 const SMDS_MeshNode* _stepSizeNodes[2];
400 // edges of _n2eMap. We keep same data in two containers because
401 // iteration over the map is 5 time longer than over the vector
402 vector< _LayerEdge* > _edges;
403 // edges on EDGE's with null _sWOL, whose _simplices are used to stop inflation
404 vector< _LayerEdge* > _simplexTestEdges;
406 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
407 // layers and a FACE w/o layers
408 // value: the shape (FACE or EDGE) to shrink mesh on.
409 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
410 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
412 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
413 set< TGeomID > _noShrinkFaces;
415 // <EDGE to smooth on> to <it's curve>
416 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
418 // end indices in _edges of _LayerEdge on one shape to smooth
419 vector< int > _endEdgeToSmooth;
421 double _epsilon; // precision for SegTriaInter()
423 int _index; // for debug
425 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
426 const StdMeshers_ViscousLayers* h=0,
427 const TopoDS_Shape& hs=TopoDS_Shape(),
429 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
432 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
435 Handle(Geom_Surface)& surface,
436 const TopoDS_Face& F,
437 SMESH_MesherHelper& helper);
439 //--------------------------------------------------------------------------------
441 * \brief Data of node on a shrinked FACE
445 const SMDS_MeshNode* _node;
446 //vector<const SMDS_MeshNode*> _nodesAround;
447 vector<_Simplex> _simplices; // for quality check
449 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
451 bool Smooth(int& badNb,
452 Handle(Geom_Surface)& surface,
453 SMESH_MesherHelper& helper,
454 const double refSign,
458 gp_XY computeAngularPos(vector<gp_XY>& uv,
459 const gp_XY& uvToFix,
460 const double refSign );
462 //--------------------------------------------------------------------------------
464 * \brief Builder of viscous layers
466 class _ViscousBuilder
471 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
472 const TopoDS_Shape& shape);
474 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
475 void RestoreListeners();
477 // computes SMESH_ProxyMesh::SubMesh::_n2n;
478 bool MakeN2NMap( _MeshOfSolid* pm );
482 bool findSolidsWithLayers();
483 bool findFacesWithLayers();
484 bool makeLayer(_SolidData& data);
485 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
486 SMESH_MesherHelper& helper, _SolidData& data);
487 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
488 std::pair< TGeomID, gp_XYZ > fId2Normal[],
490 bool findNeiborsOnEdge(const _LayerEdge* edge,
491 const SMDS_MeshNode*& n1,
492 const SMDS_MeshNode*& n2,
494 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
495 const set<TGeomID>& ingnoreShapes,
496 const _SolidData* dataToCheckOri = 0,
497 const bool toSort = false);
498 void findSimplexTestEdges( _SolidData& data,
499 vector< vector<_LayerEdge*> >& edgesByGeom);
500 bool sortEdges( _SolidData& data,
501 vector< vector<_LayerEdge*> >& edgesByGeom);
502 void limitStepSize( _SolidData& data,
503 const SMDS_MeshElement* face,
505 void limitStepSize( _SolidData& data, const double minSize);
506 bool inflate(_SolidData& data);
507 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
508 bool smoothAnalyticEdge( _SolidData& data,
511 Handle(Geom_Surface)& surface,
512 const TopoDS_Face& F,
513 SMESH_MesherHelper& helper);
514 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
515 bool refine(_SolidData& data);
517 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
518 SMESH_MesherHelper& helper,
519 const SMESHDS_SubMesh* faceSubMesh );
520 void fixBadFaces(const TopoDS_Face& F,
521 SMESH_MesherHelper& helper,
524 set<const SMDS_MeshNode*> * involvedNodes=NULL);
525 bool addBoundaryElements();
527 bool error( const string& text, int solidID=-1 );
528 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
531 void makeGroupOfLE();
534 SMESH_ComputeErrorPtr _error;
536 vector< _SolidData > _sdVec;
539 //--------------------------------------------------------------------------------
541 * \brief Shrinker of nodes on the EDGE
545 vector<double> _initU;
546 vector<double> _normPar;
547 vector<const SMDS_MeshNode*> _nodes;
548 const _LayerEdge* _edges[2];
551 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
552 void Compute(bool set3D, SMESH_MesherHelper& helper);
553 void RestoreParams();
554 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
556 //--------------------------------------------------------------------------------
558 * \brief Class of temporary mesh face.
559 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
560 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
562 struct TmpMeshFace : public SMDS_MeshElement
564 vector<const SMDS_MeshNode* > _nn;
565 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
566 SMDS_MeshElement(id), _nn(nodes) {}
567 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
568 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
569 virtual vtkIdType GetVtkType() const { return -1; }
570 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
571 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
572 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
573 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
575 //--------------------------------------------------------------------------------
577 * \brief Class of temporary mesh face storing _LayerEdge it's based on
579 struct TmpMeshFaceOnEdge : public TmpMeshFace
581 _LayerEdge *_le1, *_le2;
582 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
583 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
585 _nn[0]=_le1->_nodes[0];
586 _nn[1]=_le1->_nodes.back();
587 _nn[2]=_le2->_nodes.back();
588 _nn[3]=_le2->_nodes[0];
591 //--------------------------------------------------------------------------------
593 * \brief Retriever of node coordinates either directly of from a surface by node UV.
594 * \warning Location of a surface is ignored
596 struct NodeCoordHelper
598 SMESH_MesherHelper& _helper;
599 const TopoDS_Face& _face;
600 Handle(Geom_Surface) _surface;
601 gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
603 NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
604 : _helper( helper ), _face( F )
609 _surface = BRep_Tool::Surface( _face, loc );
611 if ( _surface.IsNull() )
612 _fun = & NodeCoordHelper::direct;
614 _fun = & NodeCoordHelper::byUV;
616 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
619 gp_XYZ direct(const SMDS_MeshNode* n) const
621 return SMESH_TNodeXYZ( n );
623 gp_XYZ byUV (const SMDS_MeshNode* n) const
625 gp_XY uv = _helper.GetNodeUV( _face, n );
626 return _surface->Value( uv.X(), uv.Y() ).XYZ();
629 } // namespace VISCOUS_3D
631 //================================================================================
632 // StdMeshers_ViscousLayers hypothesis
634 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
635 :SMESH_Hypothesis(hypId, studyId, gen),
636 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
638 _name = StdMeshers_ViscousLayers::GetHypType();
639 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
640 } // --------------------------------------------------------------------------------
641 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
643 if ( faceIds != _shapeIds )
644 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
645 if ( _isToIgnoreShapes != toIgnore )
646 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
647 } // --------------------------------------------------------------------------------
648 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
650 if ( thickness != _thickness )
651 _thickness = thickness, NotifySubMeshesHypothesisModification();
652 } // --------------------------------------------------------------------------------
653 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
655 if ( _nbLayers != nb )
656 _nbLayers = nb, NotifySubMeshesHypothesisModification();
657 } // --------------------------------------------------------------------------------
658 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
660 if ( _stretchFactor != factor )
661 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
662 } // --------------------------------------------------------------------------------
664 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
665 const TopoDS_Shape& theShape,
666 const bool toMakeN2NMap) const
668 using namespace VISCOUS_3D;
669 _ViscousBuilder bulder;
670 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
671 if ( err && !err->IsOK() )
672 return SMESH_ProxyMesh::Ptr();
674 vector<SMESH_ProxyMesh::Ptr> components;
675 TopExp_Explorer exp( theShape, TopAbs_SOLID );
676 for ( ; exp.More(); exp.Next() )
678 if ( _MeshOfSolid* pm =
679 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
681 if ( toMakeN2NMap && !pm->_n2nMapComputed )
682 if ( !bulder.MakeN2NMap( pm ))
683 return SMESH_ProxyMesh::Ptr();
684 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
685 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
687 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
689 switch ( components.size() )
693 case 1: return components[0];
695 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
697 return SMESH_ProxyMesh::Ptr();
698 } // --------------------------------------------------------------------------------
699 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
701 save << " " << _nbLayers
703 << " " << _stretchFactor
704 << " " << _shapeIds.size();
705 for ( size_t i = 0; i < _shapeIds.size(); ++i )
706 save << " " << _shapeIds[i];
707 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
709 } // --------------------------------------------------------------------------------
710 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
712 int nbFaces, faceID, shapeToTreat;
713 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
714 while ( _shapeIds.size() < nbFaces && load >> faceID )
715 _shapeIds.push_back( faceID );
716 if ( load >> shapeToTreat )
717 _isToIgnoreShapes = !shapeToTreat;
719 _isToIgnoreShapes = true; // old behavior
721 } // --------------------------------------------------------------------------------
722 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
723 const TopoDS_Shape& theShape)
728 // END StdMeshers_ViscousLayers hypothesis
729 //================================================================================
733 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
737 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
738 gp_Pnt p = BRep_Tool::Pnt( fromV );
739 double distF = p.SquareDistance( c->Value( f ));
740 double distL = p.SquareDistance( c->Value( l ));
741 c->D1(( distF < distL ? f : l), p, dir );
742 if ( distL < distF ) dir.Reverse();
745 //--------------------------------------------------------------------------------
746 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
747 SMESH_MesherHelper& helper)
750 double f,l; gp_Pnt p;
751 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
752 double u = helper.GetNodeU( E, atNode );
756 //--------------------------------------------------------------------------------
757 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
758 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
760 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
761 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
762 gp_Pnt p; gp_Vec du, dv, norm;
763 surface->D1( uv.X(),uv.Y(), p, du,dv );
767 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
768 double u = helper.GetNodeU( fromE, node, 0, &ok );
770 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
771 if ( o == TopAbs_REVERSED )
774 gp_Vec dir = norm ^ du;
776 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
777 helper.IsClosedEdge( fromE ))
779 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
780 else c->D1( f, p, dv );
781 if ( o == TopAbs_REVERSED )
783 gp_Vec dir2 = norm ^ dv;
784 dir = dir.Normalized() + dir2.Normalized();
788 //--------------------------------------------------------------------------------
789 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
790 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
791 bool& ok, double* cosin=0)
793 double f,l; TopLoc_Location loc;
794 vector< TopoDS_Edge > edges; // sharing a vertex
795 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
798 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
799 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
800 edges.push_back( *e );
803 if ( !( ok = ( edges.size() > 0 ))) return dir;
804 // get average dir of edges going fromV
806 //if ( edges.size() > 1 )
807 for ( size_t i = 0; i < edges.size(); ++i )
809 edgeDir = getEdgeDir( edges[i], fromV );
810 double size2 = edgeDir.SquareModulus();
811 if ( size2 > numeric_limits<double>::min() )
812 edgeDir /= sqrt( size2 );
817 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
819 if ( edges.size() == 1 )
821 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
822 dir = fromEdgeDir.Normalized() + getFaceDir( F, edges[1], node, helper, ok ).Normalized();
823 else if ( dir * fromEdgeDir < 0 )
826 catch ( Standard_Failure )
832 //dir /= edges.size();
834 double angle = gp_Vec( edgeDir ).Angle( dir );
835 *cosin = cos( angle );
840 //================================================================================
842 * \brief Returns true if a FACE is bound by a concave EDGE
844 //================================================================================
846 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
848 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
852 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
853 for ( ; eExp.More(); eExp.Next() )
855 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
856 if ( SMESH_Algo::isDegenerated( E )) continue;
857 // check if 2D curve is concave
858 BRepAdaptor_Curve2d curve( E, F );
859 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
860 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
861 curve.Intervals( intervals, GeomAbs_C2 );
862 bool isConvex = true;
863 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
865 double u1 = intervals( i );
866 double u2 = intervals( i+1 );
867 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
868 double cross = drv2 ^ drv1;
869 if ( E.Orientation() == TopAbs_REVERSED )
871 isConvex = ( cross > 0.1 ); //-1e-9 );
873 // check if concavity is strong enough to care about it
874 //const double maxAngle = 5 * Standard_PI180;
877 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
879 // map< double, const SMDS_MeshNode* > u2nodes;
880 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
881 // /*ignoreMedium=*/true, u2nodes))
883 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
884 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
885 // double uPrev = u2n->first;
886 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
888 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
889 // gp_Vec2d segmentDir( uvPrev, uv );
890 // curve.D1( uPrev, p, drv1 );
892 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
897 // uPrev = u2n->first;
901 // check angles at VERTEXes
903 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
904 for ( size_t iW = 0; iW < wires.size(); ++iW )
906 const int nbEdges = wires[iW]->NbEdges();
907 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
909 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
911 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
912 int iE2 = ( iE1 + 1 ) % nbEdges;
913 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
914 iE2 = ( iE2 + 1 ) % nbEdges;
915 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
916 wires[iW]->Edge( iE2 ), F );
917 if ( angle < -5. * M_PI / 180. )
923 //--------------------------------------------------------------------------------
924 // DEBUG. Dump intermediate node positions into a python script
929 const char* fname = "/tmp/viscous.py";
930 cout << "execfile('"<<fname<<"')"<<endl;
931 py = new ofstream(fname);
932 *py << "import SMESH" << endl
933 << "from salome.smesh import smeshBuilder" << endl
934 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
935 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
936 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
940 *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
943 ~PyDump() { Finish(); }
945 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
946 #define dumpMove(n) { _dumpMove(n, __LINE__);}
947 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
948 void _dumpFunction(const string& fun, int ln)
949 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
950 void _dumpMove(const SMDS_MeshNode* n, int ln)
951 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
952 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
953 void _dumpCmd(const string& txt, int ln)
954 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
955 void dumpFunctionEnd()
956 { if (py) *py<< " return"<< endl; }
957 void dumpChangeNodes( const SMDS_MeshElement* f )
958 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
959 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
960 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
962 struct PyDump { void Finish() {} };
963 #define dumpFunction(f) f
966 #define dumpFunctionEnd()
967 #define dumpChangeNodes(f)
971 using namespace VISCOUS_3D;
973 //================================================================================
975 * \brief Constructor of _ViscousBuilder
977 //================================================================================
979 _ViscousBuilder::_ViscousBuilder()
981 _error = SMESH_ComputeError::New(COMPERR_OK);
985 //================================================================================
987 * \brief Stores error description and returns false
989 //================================================================================
991 bool _ViscousBuilder::error(const string& text, int solidId )
993 _error->myName = COMPERR_ALGO_FAILED;
994 _error->myComment = string("Viscous layers builder: ") + text;
997 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
998 if ( !sm && !_sdVec.empty() )
999 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1000 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1002 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1003 if ( smError && smError->myAlgo )
1004 _error->myAlgo = smError->myAlgo;
1008 makeGroupOfLE(); // debug
1013 //================================================================================
1015 * \brief At study restoration, restore event listeners used to clear an inferior
1016 * dim sub-mesh modified by viscous layers
1018 //================================================================================
1020 void _ViscousBuilder::RestoreListeners()
1025 //================================================================================
1027 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1029 //================================================================================
1031 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1033 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1034 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1035 for ( ; fExp.More(); fExp.Next() )
1037 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1038 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1040 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1042 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1045 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1046 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1048 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1049 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1050 while( prxIt->more() )
1052 const SMDS_MeshElement* fSrc = srcIt->next();
1053 const SMDS_MeshElement* fPrx = prxIt->next();
1054 if ( fSrc->NbNodes() != fPrx->NbNodes())
1055 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1056 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1057 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1060 pm->_n2nMapComputed = true;
1064 //================================================================================
1066 * \brief Does its job
1068 //================================================================================
1070 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1071 const TopoDS_Shape& theShape)
1073 // TODO: set priority of solids during Gen::Compute()
1077 // check if proxy mesh already computed
1078 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1080 return error("No SOLID's in theShape"), _error;
1082 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1083 return SMESH_ComputeErrorPtr(); // everything already computed
1087 // TODO: ignore already computed SOLIDs
1088 if ( !findSolidsWithLayers())
1091 if ( !findFacesWithLayers() )
1094 for ( size_t i = 0; i < _sdVec.size(); ++i )
1096 if ( ! makeLayer(_sdVec[i]) )
1099 if ( _sdVec[i]._edges.size() == 0 )
1102 if ( ! inflate(_sdVec[i]) )
1105 if ( ! refine(_sdVec[i]) )
1111 addBoundaryElements();
1113 makeGroupOfLE(); // debug
1119 //================================================================================
1121 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1123 //================================================================================
1125 bool _ViscousBuilder::findSolidsWithLayers()
1128 TopTools_IndexedMapOfShape allSolids;
1129 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1130 _sdVec.reserve( allSolids.Extent());
1132 SMESH_Gen* gen = _mesh->GetGen();
1133 SMESH_HypoFilter filter;
1134 for ( int i = 1; i <= allSolids.Extent(); ++i )
1136 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1137 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1138 if ( !algo ) continue;
1139 // TODO: check if algo is hidden
1140 const list <const SMESHDS_Hypothesis *> & allHyps =
1141 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1142 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1143 const StdMeshers_ViscousLayers* viscHyp = 0;
1144 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1145 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1148 TopoDS_Shape hypShape;
1149 filter.Init( filter.Is( viscHyp ));
1150 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1152 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1155 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1156 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1159 if ( _sdVec.empty() )
1161 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1166 //================================================================================
1170 //================================================================================
1172 bool _ViscousBuilder::findFacesWithLayers()
1174 SMESH_MesherHelper helper( *_mesh );
1175 TopExp_Explorer exp;
1176 TopTools_IndexedMapOfShape solids;
1178 // collect all faces to ignore defined by hyp
1179 for ( size_t i = 0; i < _sdVec.size(); ++i )
1181 solids.Add( _sdVec[i]._solid );
1183 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1184 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1186 for ( size_t ii = 0; ii < ids.size(); ++ii )
1188 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1189 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1190 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1193 else // FACEs with layers are given
1195 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1196 for ( ; exp.More(); exp.Next() )
1198 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1199 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1200 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1204 // ignore internal FACEs if inlets and outlets are specified
1206 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1207 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1208 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1209 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1211 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1212 for ( ; exp.More(); exp.Next() )
1214 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1215 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1218 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1219 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1221 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1223 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1226 if ( helper.IsReversedSubMesh( face ))
1228 _sdVec[i]._reversedFaceIds.insert( faceInd );
1234 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1235 TopTools_IndexedMapOfShape shapes;
1236 for ( size_t i = 0; i < _sdVec.size(); ++i )
1239 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1240 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1242 const TopoDS_Shape& edge = shapes(iE);
1243 // find 2 faces sharing an edge
1245 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1246 while ( fIt->more())
1248 const TopoDS_Shape* f = fIt->next();
1249 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1250 FF[ int( !FF[0].IsNull()) ] = *f;
1252 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1253 // check presence of layers on them
1255 for ( int j = 0; j < 2; ++j )
1256 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1257 if ( ignore[0] == ignore[1] )
1258 continue; // nothing interesting
1259 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1260 // check presence of layers on fWOL within an adjacent SOLID
1261 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1262 while ( const TopoDS_Shape* solid = sIt->next() )
1263 if ( !solid->IsSame( _sdVec[i]._solid ))
1265 int iSolid = solids.FindIndex( *solid );
1266 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1267 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1269 _sdVec[i]._noShrinkFaces.insert( iFace );
1274 if ( !fWOL.IsNull())
1276 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1277 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1281 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1282 // the algo of the SOLID sharing the FACE does not support it
1283 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1284 for ( size_t i = 0; i < _sdVec.size(); ++i )
1286 TopTools_MapOfShape noShrinkVertices;
1287 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1288 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1290 const TopoDS_Shape& fWOL = e2f->second;
1291 TGeomID edgeID = e2f->first;
1292 bool notShrinkFace = false;
1293 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1294 while ( soIt->more())
1296 const TopoDS_Shape* solid = soIt->next();
1297 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1298 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1299 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1300 notShrinkFace = true;
1301 for ( size_t j = 0; j < _sdVec.size(); ++j )
1303 if ( _sdVec[j]._solid.IsSame( *solid ) )
1304 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1305 notShrinkFace = false;
1308 if ( notShrinkFace )
1310 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1311 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1312 noShrinkVertices.Add( vExp.Current() );
1315 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1316 // to the found not shrinked fWOL's
1317 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1318 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1320 TGeomID edgeID = e2f->first;
1321 TopoDS_Vertex VV[2];
1322 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1323 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1325 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1326 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1335 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1337 for ( size_t i = 0; i < _sdVec.size(); ++i )
1340 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1341 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1343 const TopoDS_Shape& vertex = shapes(iV);
1344 // find faces WOL sharing the vertex
1345 vector< TopoDS_Shape > facesWOL;
1346 int totalNbFaces = 0;
1347 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1348 while ( fIt->more())
1350 const TopoDS_Shape* f = fIt->next();
1351 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1354 const int fID = getMeshDS()->ShapeToIndex( *f );
1355 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1356 !_sdVec[i]._noShrinkFaces.count( fID ))
1357 facesWOL.push_back( *f );
1360 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1361 continue; // no layers at this vertex or no WOL
1362 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1363 switch ( facesWOL.size() )
1367 helper.SetSubShape( facesWOL[0] );
1368 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1370 TopoDS_Shape seamEdge;
1371 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1372 while ( eIt->more() && seamEdge.IsNull() )
1374 const TopoDS_Shape* e = eIt->next();
1375 if ( helper.IsRealSeam( *e ) )
1378 if ( !seamEdge.IsNull() )
1380 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1384 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1389 // find an edge shared by 2 faces
1390 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1391 while ( eIt->more())
1393 const TopoDS_Shape* e = eIt->next();
1394 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1395 helper.IsSubShape( *e, facesWOL[1]))
1397 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1403 return error("Not yet supported case", _sdVec[i]._index);
1408 // add FACEs of other SOLIDs to _ignoreFaceIds
1409 for ( size_t i = 0; i < _sdVec.size(); ++i )
1412 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1414 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1416 if ( !shapes.Contains( exp.Current() ))
1417 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1424 //================================================================================
1426 * \brief Create the inner surface of the viscous layer and prepare data for infation
1428 //================================================================================
1430 bool _ViscousBuilder::makeLayer(_SolidData& data)
1432 // get all sub-shapes to make layers on
1433 set<TGeomID> subIds, faceIds;
1434 subIds = data._noShrinkFaces;
1435 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1436 for ( ; exp.More(); exp.Next() )
1438 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1439 if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1440 faceIds.insert( fSubM->GetId() );
1441 SMESH_subMeshIteratorPtr subIt =
1442 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1443 while ( subIt->more() )
1444 subIds.insert( subIt->next()->GetId() );
1447 // make a map to find new nodes on sub-shapes shared with other SOLID
1448 map< TGeomID, TNode2Edge* > s2neMap;
1449 map< TGeomID, TNode2Edge* >::iterator s2ne;
1450 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1451 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1453 TGeomID shapeInd = s2s->first;
1454 for ( size_t i = 0; i < _sdVec.size(); ++i )
1456 if ( _sdVec[i]._index == data._index ) continue;
1457 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1458 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1459 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1461 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1467 // Create temporary faces and _LayerEdge's
1469 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1471 data._stepSize = Precision::Infinite();
1472 data._stepSizeNodes[0] = 0;
1474 SMESH_MesherHelper helper( *_mesh );
1475 helper.SetSubShape( data._solid );
1476 helper.SetElementsOnShape(true);
1478 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1479 TNode2Edge::iterator n2e2;
1481 // collect _LayerEdge's of shapes they are based on
1482 const int nbShapes = getMeshDS()->MaxShapeIndex();
1483 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1485 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1487 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1488 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1490 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1491 SMESH_ProxyMesh::SubMesh* proxySub =
1492 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1494 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1495 while ( eIt->more() )
1497 const SMDS_MeshElement* face = eIt->next();
1498 newNodes.resize( face->NbCornerNodes() );
1499 double faceMaxCosin = -1;
1500 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1502 const SMDS_MeshNode* n = face->GetNode(i);
1503 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1504 if ( !(*n2e).second )
1507 _LayerEdge* edge = new _LayerEdge();
1509 edge->_nodes.push_back( n );
1510 const int shapeID = n->getshapeId();
1511 edgesByGeom[ shapeID ].push_back( edge );
1513 // set edge data or find already refined _LayerEdge and get data from it
1514 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1515 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1516 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1518 _LayerEdge* foundEdge = (*n2e2).second;
1519 edge->Copy( *foundEdge, helper );
1520 // location of the last node is modified but we can restore
1521 // it by node position on _sWOL stored by the node
1522 const_cast< SMDS_MeshNode* >
1523 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1527 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1528 if ( !setEdgeData( *edge, subIds, helper, data ))
1531 dumpMove(edge->_nodes.back());
1532 if ( edge->_cosin > 0.01 )
1534 if ( edge->_cosin > faceMaxCosin )
1535 faceMaxCosin = edge->_cosin;
1538 newNodes[ i ] = n2e->second->_nodes.back();
1540 // create a temporary face
1541 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1542 proxySub->AddElement( newFace );
1544 // compute inflation step size by min size of element on a convex surface
1545 if ( faceMaxCosin > 0.1 )
1546 limitStepSize( data, face, faceMaxCosin );
1547 } // loop on 2D elements on a FACE
1548 } // loop on FACEs of a SOLID
1550 data._epsilon = 1e-7;
1551 if ( data._stepSize < 1. )
1552 data._epsilon *= data._stepSize;
1554 // fill data._simplexTestEdges
1555 findSimplexTestEdges( data, edgesByGeom );
1557 // Put _LayerEdge's into the vector data._edges
1558 if ( !sortEdges( data, edgesByGeom ))
1561 // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1562 TNode2Edge::iterator n2e;
1563 for ( size_t i = 0; i < data._edges.size(); ++i )
1565 if ( data._edges[i]->IsOnEdge())
1566 for ( int j = 0; j < 2; ++j )
1568 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1569 break; // _LayerEdge is shared by two _SolidData's
1570 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1571 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1572 return error("_LayerEdge not found by src node", data._index);
1573 n = (*n2e).second->_nodes.back();
1574 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1577 for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1579 _Simplex& s = data._edges[i]->_simplices[j];
1580 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1581 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1589 //================================================================================
1591 * \brief Compute inflation step size by min size of element on a convex surface
1593 //================================================================================
1595 void _ViscousBuilder::limitStepSize( _SolidData& data,
1596 const SMDS_MeshElement* face,
1600 double minSize = 10 * data._stepSize;
1601 const int nbNodes = face->NbCornerNodes();
1602 for ( int i = 0; i < nbNodes; ++i )
1604 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1605 const SMDS_MeshNode* curN = face->GetNode( i );
1606 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1607 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1609 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1610 if ( dist < minSize )
1611 minSize = dist, iN = i;
1614 double newStep = 0.8 * minSize / cosin;
1615 if ( newStep < data._stepSize )
1617 data._stepSize = newStep;
1618 data._stepSizeCoeff = 0.8 / cosin;
1619 data._stepSizeNodes[0] = face->GetNode( iN );
1620 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1624 //================================================================================
1626 * \brief Compute inflation step size by min size of element on a convex surface
1628 //================================================================================
1630 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1632 if ( minSize < data._stepSize )
1634 data._stepSize = minSize;
1635 if ( data._stepSizeNodes[0] )
1638 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1639 data._stepSizeCoeff = data._stepSize / dist;
1644 //================================================================================
1646 * Fill data._simplexTestEdges. These _LayerEdge's are used to stop inflation
1647 * in the case where there are no _LayerEdge's on a curved convex FACE,
1648 * as e.g. on a fillet surface with no internal nodes - issue 22580,
1649 * so that collision of viscous internal faces is not detected by check of
1650 * intersection of _LayerEdge's with the viscous internal faces.
1652 //================================================================================
1654 void _ViscousBuilder::findSimplexTestEdges( _SolidData& data,
1655 vector< vector<_LayerEdge*> >& edgesByGeom)
1657 data._simplexTestEdges.clear();
1659 SMESH_MesherHelper helper( *_mesh );
1661 vector< vector<_LayerEdge*> * > ledgesOnEdges;
1662 set< const SMDS_MeshNode* > usedNodes;
1664 const double minCurvature = 1. / data._hyp->GetTotalThickness();
1666 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1668 // look for a FACE with layers and w/o _LayerEdge's
1669 const vector<_LayerEdge*>& eS = edgesByGeom[iS];
1670 if ( !eS.empty() ) continue;
1671 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1672 if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
1673 if ( data._ignoreFaceIds.count( iS )) continue;
1675 const TopoDS_Face& F = TopoDS::Face( S );
1677 // look for _LayerEdge's on EDGEs with null _sWOL
1678 ledgesOnEdges.clear();
1679 TopExp_Explorer eExp( F, TopAbs_EDGE );
1680 for ( ; eExp.More(); eExp.Next() )
1682 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1683 vector<_LayerEdge*>& eE = edgesByGeom[iE];
1684 if ( !eE.empty() && eE[0]->_sWOL.IsNull() )
1685 ledgesOnEdges.push_back( & eE );
1687 if ( ledgesOnEdges.empty() ) continue;
1689 // check FACE convexity
1690 const _LayerEdge* le = ledgesOnEdges[0]->back();
1691 gp_XY uv = helper.GetNodeUV( F, le->_nodes[0] );
1692 BRepAdaptor_Surface surf( F );
1693 BRepLProp_SLProps surfProp( surf, uv.X(), uv.Y(), 2, 1e-6 );
1694 if ( !surfProp.IsCurvatureDefined() )
1696 double surfCurvature = Max( Abs( surfProp.MaxCurvature() ),
1697 Abs( surfProp.MinCurvature() ));
1698 if ( surfCurvature < minCurvature )
1700 gp_Dir minDir, maxDir;
1701 surfProp.CurvatureDirections( maxDir, minDir );
1702 if ( F.Orientation() == TopAbs_REVERSED ) {
1703 maxDir.Reverse(); minDir.Reverse();
1705 const gp_XYZ& inDir = le->_normal;
1706 if ( inDir * maxDir.XYZ() < 0 &&
1707 inDir * minDir.XYZ() < 0 )
1710 limitStepSize( data, 0.9 / surfCurvature );
1712 // add _simplices to the _LayerEdge's
1713 for ( size_t iE = 0; iE < ledgesOnEdges.size(); ++iE )
1715 const vector<_LayerEdge*>& ledges = *ledgesOnEdges[iE];
1716 for ( size_t iLE = 0; iLE < ledges.size(); ++iLE )
1718 _LayerEdge* ledge = ledges[iLE];
1719 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1720 if ( !usedNodes.insert( srcNode ).second ) continue;
1722 getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1723 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1725 usedNodes.insert( ledge->_simplices[i]._nPrev );
1726 usedNodes.insert( ledge->_simplices[i]._nNext );
1728 data._simplexTestEdges.push_back( ledge );
1734 //================================================================================
1736 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1738 //================================================================================
1740 bool _ViscousBuilder::sortEdges( _SolidData& data,
1741 vector< vector<_LayerEdge*> >& edgesByGeom)
1743 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1744 // boundry inclined at a sharp angle to the shape
1746 list< TGeomID > shapesToSmooth;
1748 SMESH_MesherHelper helper( *_mesh );
1751 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1753 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1754 if ( eS.empty() ) continue;
1755 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1756 bool needSmooth = false;
1757 switch ( S.ShapeType() )
1761 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1762 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1764 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1765 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1766 if ( eV.empty() ) continue;
1767 double cosin = eV[0]->_cosin;
1769 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1773 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1774 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1776 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1777 eV[0]->_nodes[0], helper, ok);
1778 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1779 double angle = dir1.Angle( dir2 );
1780 cosin = cos( angle );
1782 needSmooth = ( cosin > 0.1 );
1788 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1790 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1791 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1792 if ( eE.empty() ) continue;
1793 if ( eE[0]->_sWOL.IsNull() )
1795 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1796 needSmooth = ( eE[i]->_cosin > 0.1 );
1800 const TopoDS_Face& F1 = TopoDS::Face( S );
1801 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1802 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1803 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1805 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1806 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1807 double angle = dir1.Angle( dir2 );
1808 double cosin = cos( angle );
1809 needSmooth = ( cosin > 0.1 );
1821 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1822 else shapesToSmooth.push_back ( iS );
1825 } // loop on edgesByGeom
1827 data._edges.reserve( data._n2eMap.size() );
1828 data._endEdgeToSmooth.clear();
1830 // first we put _LayerEdge's on shapes to smooth
1831 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1832 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1834 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1835 if ( eVec.empty() ) continue;
1836 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1837 data._endEdgeToSmooth.push_back( data._edges.size() );
1841 // then the rest _LayerEdge's
1842 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1844 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1845 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1852 //================================================================================
1854 * \brief Set data of _LayerEdge needed for smoothing
1855 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1857 //================================================================================
1859 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1860 const set<TGeomID>& subIds,
1861 SMESH_MesherHelper& helper,
1864 SMESH_MeshEditor editor(_mesh);
1866 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1867 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1871 edge._curvature = 0;
1873 // --------------------------
1874 // Compute _normal and _cosin
1875 // --------------------------
1878 edge._normal.SetCoord(0,0,0);
1880 int totalNbFaces = 0;
1882 gp_Vec du, dv, geomNorm;
1885 TGeomID shapeInd = node->getshapeId();
1886 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1887 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1888 TopoDS_Shape vertEdge;
1890 if ( onShrinkShape ) // one of faces the node is on has no layers
1892 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1893 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1895 // inflate from VERTEX along EDGE
1896 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1898 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1900 // inflate from VERTEX along FACE
1901 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1902 node, helper, normOK, &edge._cosin);
1906 // inflate from EDGE along FACE
1907 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1908 node, helper, normOK);
1911 else // layers are on all faces of SOLID the node is on
1913 // find indices of geom faces the node lies on
1914 set<TGeomID> faceIds;
1915 if ( posType == SMDS_TOP_FACE )
1917 faceIds.insert( node->getshapeId() );
1921 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1922 while ( fIt->more() )
1923 faceIds.insert( editor.FindShape(fIt->next()));
1926 set<TGeomID>::iterator id = faceIds.begin();
1928 std::pair< TGeomID, gp_XYZ > id2Norm[20];
1929 for ( ; id != faceIds.end(); ++id )
1931 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1932 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1934 F = TopoDS::Face( s );
1936 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1937 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1940 if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1945 else // hard singularity
1947 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1948 while ( fIt->more() )
1950 const SMDS_MeshElement* f = fIt->next();
1951 if ( editor.FindShape( f ) == *id )
1953 SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1954 if ( helper.IsReversedSubMesh( F ))
1959 double size2 = geomNorm.SquareMagnitude();
1960 if ( size2 > numeric_limits<double>::min() )
1961 geomNorm /= sqrt( size2 );
1966 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1968 id2Norm[ totalNbFaces ].first = *id;
1969 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
1971 edge._normal += geomNorm.XYZ();
1973 if ( totalNbFaces == 0 )
1974 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1976 if ( totalNbFaces < 3 )
1978 //edge._normal /= totalNbFaces;
1982 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
1988 edge._cosin = 0; break;
1990 case SMDS_TOP_EDGE: {
1991 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1992 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1993 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1994 edge._cosin = cos( angle );
1995 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1998 case SMDS_TOP_VERTEX: {
1999 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2000 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
2001 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
2002 edge._cosin = cos( angle );
2003 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2007 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2011 double normSize = edge._normal.SquareModulus();
2012 if ( normSize < numeric_limits<double>::min() )
2013 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2015 edge._normal /= sqrt( normSize );
2017 // TODO: if ( !normOK ) then get normal by mesh faces
2019 // Set the rest data
2020 // --------------------
2021 if ( onShrinkShape )
2023 edge._sWOL = (*s2s).second;
2025 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2026 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2027 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2029 // set initial position which is parameters on _sWOL in this case
2030 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2032 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2033 edge._pos.push_back( gp_XYZ( u, 0, 0));
2034 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2038 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2039 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2040 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2045 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2047 if ( posType == SMDS_TOP_FACE )
2049 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2050 double avgNormProj = 0, avgLen = 0;
2051 for ( size_t i = 0; i < edge._simplices.size(); ++i )
2053 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2054 avgNormProj += edge._normal * vec;
2055 avgLen += vec.Modulus();
2057 avgNormProj /= edge._simplices.size();
2058 avgLen /= edge._simplices.size();
2059 edge._curvature = _Curvature::New( avgNormProj, avgLen );
2063 // Set neighbour nodes for a _LayerEdge based on EDGE
2065 if ( posType == SMDS_TOP_EDGE /*||
2066 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2068 edge._2neibors = new _2NearEdges;
2069 // target node instead of source ones will be set later
2070 if ( ! findNeiborsOnEdge( &edge,
2071 edge._2neibors->_nodes[0],
2072 edge._2neibors->_nodes[1],
2075 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2076 edge._2neibors->_nodes[1],
2080 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2085 //================================================================================
2087 * \brief Return normal at a node weighted with angles taken by FACEs
2088 * \param [in] n - the node
2089 * \param [in] fId2Normal - FACE ids and normals
2090 * \param [in] nbFaces - nb of FACEs meeting at the node
2091 * \return gp_XYZ - computed normal
2093 //================================================================================
2095 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
2096 std::pair< TGeomID, gp_XYZ > fId2Normal[],
2099 gp_XYZ resNorm(0,0,0);
2100 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2101 if ( V.ShapeType() != TopAbs_VERTEX )
2103 for ( int i = 0; i < nbFaces; ++i )
2104 resNorm += fId2Normal[i].second / nbFaces ;
2109 for ( int i = 0; i < nbFaces; ++i )
2111 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2113 // look for two EDGEs shared by F and other FACEs within fId2Normal
2116 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2117 while ( const TopoDS_Shape* E = eIt->next() )
2119 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2121 bool isSharedEdge = false;
2122 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2124 if ( i == j ) continue;
2125 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2126 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2128 if ( !isSharedEdge )
2130 ee[ nbE ] = TopoDS::Edge( *E );
2131 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2136 // get an angle between the two EDGEs
2138 if ( nbE < 1 ) continue;
2145 TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2146 TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2147 if ( !v10.IsSame( v01 ))
2148 std::swap( ee[0], ee[1] );
2150 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2153 // compute a weighted normal
2154 double sumAngle = 0;
2155 for ( int i = 0; i < nbFaces; ++i )
2157 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
2158 sumAngle += angles[i];
2160 for ( int i = 0; i < nbFaces; ++i )
2161 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2166 //================================================================================
2168 * \brief Find 2 neigbor nodes of a node on EDGE
2170 //================================================================================
2172 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
2173 const SMDS_MeshNode*& n1,
2174 const SMDS_MeshNode*& n2,
2177 const SMDS_MeshNode* node = edge->_nodes[0];
2178 const int shapeInd = node->getshapeId();
2179 SMESHDS_SubMesh* edgeSM = 0;
2180 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2183 edgeSM = getMeshDS()->MeshElements( shapeInd );
2184 if ( !edgeSM || edgeSM->NbElements() == 0 )
2185 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2189 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2190 while ( eIt->more() && !n2 )
2192 const SMDS_MeshElement* e = eIt->next();
2193 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
2194 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2197 if (!edgeSM->Contains(e)) continue;
2201 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2202 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2204 ( iN++ ? n2 : n1 ) = nNeibor;
2207 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2211 //================================================================================
2213 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2215 //================================================================================
2217 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2218 const SMDS_MeshNode* n2,
2219 SMESH_MesherHelper& helper)
2221 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2224 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2225 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2226 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2230 double sumLen = vec1.Modulus() + vec2.Modulus();
2231 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2232 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2233 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2234 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2235 if ( _curvature ) delete _curvature;
2236 _curvature = _Curvature::New( avgNormProj, avgLen );
2238 // if ( _curvature )
2239 // cout << _nodes[0]->GetID()
2240 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2241 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2242 // << _curvature->lenDelta(0) << endl;
2247 if ( _sWOL.IsNull() )
2249 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2250 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2251 gp_XYZ plnNorm = dirE ^ _normal;
2252 double proj0 = plnNorm * vec1;
2253 double proj1 = plnNorm * vec2;
2254 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2256 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2257 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2262 //================================================================================
2264 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2265 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2267 //================================================================================
2269 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2271 _nodes = other._nodes;
2272 _normal = other._normal;
2274 _lenFactor = other._lenFactor;
2275 _cosin = other._cosin;
2276 _sWOL = other._sWOL;
2277 _2neibors = other._2neibors;
2278 _curvature = 0; std::swap( _curvature, other._curvature );
2279 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2281 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2283 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2284 _pos.push_back( gp_XYZ( u, 0, 0));
2288 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2289 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2293 //================================================================================
2295 * \brief Set _cosin and _lenFactor
2297 //================================================================================
2299 void _LayerEdge::SetCosin( double cosin )
2302 _lenFactor = ( Abs( _cosin ) > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
2305 //================================================================================
2307 * \brief Fills a vector<_Simplex >
2309 //================================================================================
2311 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2312 vector<_Simplex>& simplices,
2313 const set<TGeomID>& ingnoreShapes,
2314 const _SolidData* dataToCheckOri,
2318 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2319 while ( fIt->more() )
2321 const SMDS_MeshElement* f = fIt->next();
2322 const TGeomID shapeInd = f->getshapeId();
2323 if ( ingnoreShapes.count( shapeInd )) continue;
2324 const int nbNodes = f->NbCornerNodes();
2325 const int srcInd = f->GetNodeIndex( node );
2326 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2327 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2328 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2329 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2330 std::swap( nPrev, nNext );
2331 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2336 vector<_Simplex> sortedSimplices( simplices.size() );
2337 sortedSimplices[0] = simplices[0];
2339 for ( size_t i = 1; i < simplices.size(); ++i )
2341 for ( size_t j = 1; j < simplices.size(); ++j )
2342 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2344 sortedSimplices[i] = simplices[j];
2349 if ( nbFound == simplices.size() - 1 )
2350 simplices.swap( sortedSimplices );
2354 //================================================================================
2356 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2358 //================================================================================
2360 void _ViscousBuilder::makeGroupOfLE()
2363 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2365 if ( _sdVec[i]._edges.empty() ) continue;
2366 // string name = SMESH_Comment("_LayerEdge's_") << i;
2368 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2369 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2370 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2372 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2373 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2375 _LayerEdge* le = _sdVec[i]._edges[j];
2376 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2377 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2378 << ", " << le->_nodes[iN]->GetID() <<"])");
2379 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2383 dumpFunction( SMESH_Comment("makeNormals") << i );
2384 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2386 _LayerEdge& edge = *_sdVec[i]._edges[j];
2387 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2388 nXYZ += edge._normal * _sdVec[i]._stepSize;
2389 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2390 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2394 // name = SMESH_Comment("tmp_faces ") << i;
2395 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2396 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2397 // SMESH_MeshEditor editor( _mesh );
2398 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2399 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2400 for ( ; fExp.More(); fExp.Next() )
2402 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2404 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2405 while ( fIt->more())
2407 const SMDS_MeshElement* e = fIt->next();
2408 SMESH_Comment cmd("mesh.AddFace([");
2409 for ( int j=0; j < e->NbCornerNodes(); ++j )
2410 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2412 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2413 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2422 //================================================================================
2424 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2426 //================================================================================
2428 bool _ViscousBuilder::inflate(_SolidData& data)
2430 SMESH_MesherHelper helper( *_mesh );
2432 // Limit inflation step size by geometry size found by itersecting
2433 // normals of _LayerEdge's with mesh faces
2434 double geomSize = Precision::Infinite(), intersecDist;
2435 auto_ptr<SMESH_ElementSearcher> searcher
2436 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2437 data._proxyMesh->GetFaces( data._solid )) );
2438 for ( size_t i = 0; i < data._edges.size(); ++i )
2440 if ( data._edges[i]->IsOnEdge() ) continue;
2441 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2442 if ( geomSize > intersecDist && intersecDist > 0 )
2443 geomSize = intersecDist;
2445 if ( data._stepSize > 0.3 * geomSize )
2446 limitStepSize( data, 0.3 * geomSize );
2448 const double tgtThick = data._hyp->GetTotalThickness();
2449 if ( data._stepSize > tgtThick )
2450 limitStepSize( data, tgtThick );
2452 if ( data._stepSize < 1. )
2453 data._epsilon = data._stepSize * 1e-7;
2456 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2459 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2460 int nbSteps = 0, nbRepeats = 0;
2461 while ( 1.01 * avgThick < tgtThick )
2463 // new target length
2464 curThick += data._stepSize;
2465 if ( curThick > tgtThick )
2467 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2471 // Elongate _LayerEdge's
2472 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2473 for ( size_t i = 0; i < data._edges.size(); ++i )
2475 data._edges[i]->SetNewLength( curThick, helper );
2480 if ( !updateNormals( data, helper ) )
2483 // Improve and check quality
2484 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2488 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2489 for ( size_t i = 0; i < data._edges.size(); ++i )
2491 data._edges[i]->InvalidateStep( nbSteps+1 );
2495 break; // no more inflating possible
2499 // Evaluate achieved thickness
2501 for ( size_t i = 0; i < data._edges.size(); ++i )
2502 avgThick += data._edges[i]->_len;
2503 avgThick /= data._edges.size();
2505 cout << "-- Thickness " << avgThick << " reached" << endl;
2508 if ( distToIntersection < avgThick*1.5 )
2511 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2512 << avgThick << " ) * 1.5" << endl;
2517 limitStepSize( data, 0.25 * distToIntersection );
2518 if ( data._stepSizeNodes[0] )
2519 data._stepSize = data._stepSizeCoeff *
2520 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2524 return error("failed at the very first inflation step", data._index);
2529 //================================================================================
2531 * \brief Improve quality of layer inner surface and check intersection
2533 //================================================================================
2535 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2537 double & distToIntersection)
2539 if ( data._endEdgeToSmooth.empty() )
2540 return true; // no shapes needing smoothing
2542 bool moved, improved;
2544 SMESH_MesherHelper helper(*_mesh);
2545 Handle(Geom_Surface) surface;
2549 for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2552 iEnd = data._endEdgeToSmooth[ iS ];
2554 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2555 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2557 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2558 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2559 helper.SetSubShape( F );
2560 surface = BRep_Tool::Surface( F );
2565 F.Nullify(); surface.Nullify();
2567 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2569 if ( data._edges[ iBeg ]->IsOnEdge() )
2571 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2573 // try a simple solution on an analytic EDGE
2574 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2580 for ( int i = iBeg; i < iEnd; ++i )
2582 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2584 dumpCmd( SMESH_Comment("# end step ")<<step);
2586 while ( moved && step++ < 5 );
2587 //cout << " NB STEPS: " << step << endl;
2594 int step = 0, stepLimit = 5, badNb = 0; moved = true;
2595 while (( ++step <= stepLimit && moved ) || improved )
2597 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2598 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2599 int oldBadNb = badNb;
2602 for ( int i = iBeg; i < iEnd; ++i )
2603 moved |= data._edges[i]->Smooth(badNb);
2604 improved = ( badNb < oldBadNb );
2606 // issue 22576. no bad faces but still there are intersections to fix
2607 if ( improved && badNb == 0 )
2608 stepLimit = step + 3;
2615 for ( int i = iBeg; i < iEnd; ++i )
2617 _LayerEdge* edge = data._edges[i];
2618 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2619 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2620 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2622 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2623 << " "<< edge->_simplices[j]._nPrev->GetID()
2624 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2632 } // loop on shapes to smooth
2634 // Check orientation of simplices of _simplexTestEdges
2635 for ( size_t i = 0; i < data._simplexTestEdges.size(); ++i )
2637 const _LayerEdge* edge = data._simplexTestEdges[i];
2638 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2639 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2640 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2643 cout << "Bad simplex of _simplexTestEdges ("
2644 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2645 << " "<< edge->_simplices[j]._nPrev->GetID()
2646 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2652 // Check if the last segments of _LayerEdge intersects 2D elements;
2653 // checked elements are either temporary faces or faces on surfaces w/o the layers
2655 auto_ptr<SMESH_ElementSearcher> searcher
2656 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2657 data._proxyMesh->GetFaces( data._solid )) );
2659 distToIntersection = Precision::Infinite();
2661 const SMDS_MeshElement* intFace = 0;
2663 const SMDS_MeshElement* closestFace = 0;
2666 for ( size_t i = 0; i < data._edges.size(); ++i )
2668 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2670 if ( distToIntersection > dist )
2672 distToIntersection = dist;
2675 closestFace = intFace;
2682 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2683 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2684 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2685 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2686 << ") distance = " << distToIntersection<< endl;
2693 //================================================================================
2695 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2696 * _LayerEdge's to be in a consequent order
2698 //================================================================================
2700 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2703 Handle(Geom_Surface)& surface,
2704 const TopoDS_Face& F,
2705 SMESH_MesherHelper& helper)
2707 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2709 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2711 if ( i2curve == _edge2curve.end() )
2713 // sort _LayerEdge's by position on the EDGE
2715 map< double, _LayerEdge* > u2edge;
2716 for ( int i = iFrom; i < iTo; ++i )
2717 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2719 ASSERT( u2edge.size() == iTo - iFrom );
2720 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2721 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2722 _edges[i] = u2e->second;
2724 // set _2neibors according to the new order
2725 for ( int i = iFrom; i < iTo-1; ++i )
2726 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2727 _edges[i]->_2neibors->reverse();
2728 if ( u2edge.size() > 1 &&
2729 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2730 _edges[iTo-1]->_2neibors->reverse();
2733 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2735 TopLoc_Location loc; double f,l;
2737 Handle(Geom_Line) line;
2738 Handle(Geom_Circle) circle;
2739 bool isLine, isCirc;
2740 if ( F.IsNull() ) // 3D case
2742 // check if the EDGE is a line
2743 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2744 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2745 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2747 line = Handle(Geom_Line)::DownCast( curve );
2748 circle = Handle(Geom_Circle)::DownCast( curve );
2749 isLine = (!line.IsNull());
2750 isCirc = (!circle.IsNull());
2752 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2755 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2756 while ( nIt->more() )
2757 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2758 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2760 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2761 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2762 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2763 for ( int i = 0; i < 3 && !isLine; ++i )
2764 isLine = ( size.Coord( i+1 ) <= lineTol );
2766 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2773 // check if the EDGE is a line
2774 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2775 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2776 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2778 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2779 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2780 isLine = (!line2d.IsNull());
2781 isCirc = (!circle2d.IsNull());
2783 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2786 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2787 while ( nIt->more() )
2788 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2789 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2791 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2792 for ( int i = 0; i < 2 && !isLine; ++i )
2793 isLine = ( size.Coord( i+1 ) <= lineTol );
2795 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2801 line = new Geom_Line( gp::OX() ); // only type does matter
2805 gp_Pnt2d p = circle2d->Location();
2806 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2807 circle = new Geom_Circle( ax, 1.); // only center position does matter
2811 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2819 return i2curve->second;
2822 //================================================================================
2824 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2826 //================================================================================
2828 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2831 Handle(Geom_Surface)& surface,
2832 const TopoDS_Face& F,
2833 SMESH_MesherHelper& helper)
2835 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2836 helper.GetMeshDS());
2837 TopoDS_Edge E = TopoDS::Edge( S );
2839 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2840 if ( curve.IsNull() ) return false;
2842 // compute a relative length of segments
2843 vector< double > len( iTo-iFrom+1 );
2845 double curLen, prevLen = len[0] = 1.0;
2846 for ( int i = iFrom; i < iTo; ++i )
2848 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2849 len[i-iFrom+1] = len[i-iFrom] + curLen;
2854 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2856 if ( F.IsNull() ) // 3D
2858 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2859 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2860 for ( int i = iFrom; i < iTo; ++i )
2862 double r = len[i-iFrom] / len.back();
2863 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2864 data._edges[i]->_pos.back() = newPos;
2865 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2866 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2867 dumpMove( tgtNode );
2872 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2873 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2874 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2875 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2877 int iPeriodic = helper.GetPeriodicIndex();
2878 if ( iPeriodic == 1 || iPeriodic == 2 )
2880 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2881 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2882 std::swap( uv0, uv1 );
2885 const gp_XY rangeUV = uv1 - uv0;
2886 for ( int i = iFrom; i < iTo; ++i )
2888 double r = len[i-iFrom] / len.back();
2889 gp_XY newUV = uv0 + r * rangeUV;
2890 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2892 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2893 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2894 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2895 dumpMove( tgtNode );
2897 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2898 pos->SetUParameter( newUV.X() );
2899 pos->SetVParameter( newUV.Y() );
2905 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2907 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2908 gp_Pnt center3D = circle->Location();
2910 if ( F.IsNull() ) // 3D
2912 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2913 data._edges[iTo-1]->_2neibors->_nodes[1] )
2914 return true; // closed EDGE - nothing to do
2916 return false; // TODO ???
2920 const gp_XY center( center3D.X(), center3D.Y() );
2922 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2923 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2924 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2925 gp_Vec2d vec0( center, uv0 );
2926 gp_Vec2d vecM( center, uvM );
2927 gp_Vec2d vec1( center, uv1 );
2928 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2929 double uMidl = vec0.Angle( vecM );
2930 if ( uLast * uMidl < 0. )
2931 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2932 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2934 gp_Ax2d axis( center, vec0 );
2935 gp_Circ2d circ( axis, radius );
2936 for ( int i = iFrom; i < iTo; ++i )
2938 double newU = uLast * len[i-iFrom] / len.back();
2939 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2940 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2942 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2943 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2944 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2945 dumpMove( tgtNode );
2947 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2948 pos->SetUParameter( newUV.X() );
2949 pos->SetVParameter( newUV.Y() );
2958 //================================================================================
2960 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2961 * _LayerEdge's on neighbor EDGE's
2963 //================================================================================
2965 bool _ViscousBuilder::updateNormals( _SolidData& data,
2966 SMESH_MesherHelper& helper )
2968 // make temporary quadrangles got by extrusion of
2969 // mesh edges along _LayerEdge._normal's
2971 vector< const SMDS_MeshElement* > tmpFaces;
2973 set< SMESH_TLink > extrudedLinks; // contains target nodes
2974 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2976 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2977 for ( size_t i = 0; i < data._edges.size(); ++i )
2979 _LayerEdge* edge = data._edges[i];
2980 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2981 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2982 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2984 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2985 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2986 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2987 if ( !link_isnew.second )
2989 extrudedLinks.erase( link_isnew.first );
2990 continue; // already extruded and will no more encounter
2992 // look for a _LayerEdge containg tgt2
2993 // _LayerEdge* neiborEdge = 0;
2994 // size_t di = 0; // check _edges[i+di] and _edges[i-di]
2995 // while ( !neiborEdge && ++di <= data._edges.size() )
2997 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2998 // neiborEdge = data._edges[i+di];
2999 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
3000 // neiborEdge = data._edges[i-di];
3002 // if ( !neiborEdge )
3003 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
3004 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3006 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3007 tmpFaces.push_back( f );
3009 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3010 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3011 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3016 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3017 // Perform two loops on _LayerEdge on EDGE's:
3018 // 1) to find and fix intersection
3019 // 2) to check that no new intersection appears as result of 1)
3021 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3023 auto_ptr<SMESH_ElementSearcher> searcher
3024 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3026 // 1) Find intersections
3028 const SMDS_MeshElement* face;
3029 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3030 TLEdge2LEdgeSet edge2CloseEdge;
3032 const double eps = data._epsilon * data._epsilon;
3033 for ( size_t i = 0; i < data._edges.size(); ++i )
3035 _LayerEdge* edge = data._edges[i];
3036 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3037 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3039 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
3040 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3041 ee.insert( f->_le1 );
3042 ee.insert( f->_le2 );
3043 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
3044 edge2CloseEdge[ f->_le1 ].insert( edge );
3045 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
3046 edge2CloseEdge[ f->_le2 ].insert( edge );
3050 // Set _LayerEdge._normal
3052 if ( !edge2CloseEdge.empty() )
3054 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3056 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3057 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3059 _LayerEdge* edge1 = e2ee->first;
3060 _LayerEdge* edge2 = 0;
3061 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
3063 // find EDGEs the edges reside
3065 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3066 if ( S.ShapeType() != TopAbs_EDGE )
3067 continue; // TODO: find EDGE by VERTEX
3068 E1 = TopoDS::Edge( S );
3069 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3070 while ( E2.IsNull() && eIt != ee.end())
3072 _LayerEdge* e2 = *eIt++;
3073 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3074 if ( S.ShapeType() == TopAbs_EDGE )
3075 E2 = TopoDS::Edge( S ), edge2 = e2;
3077 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3079 // find 3 FACEs sharing 2 EDGEs
3081 TopoDS_Face FF1[2], FF2[2];
3082 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3083 while ( fIt->more() && FF1[1].IsNull())
3085 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3086 if ( helper.IsSubShape( *F, data._solid))
3087 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3089 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3090 while ( fIt->more() && FF2[1].IsNull())
3092 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3093 if ( helper.IsSubShape( *F, data._solid))
3094 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3096 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3097 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3098 std::swap( FF1[0], FF1[1] );
3099 if ( FF2[0].IsSame( FF1[0]) )
3100 std::swap( FF2[0], FF2[1] );
3101 if ( FF1[0].IsNull() || FF2[0].IsNull() )
3104 // get a new normal for edge1
3106 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3107 if ( edge1->_cosin < 0 )
3108 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3109 if ( edge2->_cosin < 0 )
3110 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3111 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3112 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3113 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3114 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3115 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3116 // newNorm.Normalize();
3118 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3119 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3120 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3121 newNorm.Normalize();
3123 edge1->_normal = newNorm.XYZ();
3125 // update data of edge1 depending on _normal
3126 const SMDS_MeshNode *n1, *n2;
3127 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3128 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3129 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
3131 edge1->SetDataByNeighbors( n1, n2, helper );
3133 if ( edge1->_cosin < 0 )
3136 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3137 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3138 edge1->SetCosin( cos( angle ));
3140 // limit data._stepSize
3141 if ( edge1->_cosin > 0.1 )
3143 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3144 while ( fIt->more() )
3145 limitStepSize( data, fIt->next(), edge1->_cosin );
3147 // set new XYZ of target node
3148 edge1->InvalidateStep( 1 );
3150 edge1->SetNewLength( data._stepSize, helper );
3153 // Update normals and other dependent data of not intersecting _LayerEdge's
3154 // neighboring the intersecting ones
3156 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3158 _LayerEdge* edge1 = e2ee->first;
3159 if ( !edge1->_2neibors )
3161 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3163 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3164 if ( edge2CloseEdge.count ( neighbor ))
3165 continue; // j-th neighbor is also intersected
3166 _LayerEdge* prevEdge = edge1;
3167 const int nbSteps = 6;
3168 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3170 if ( !neighbor->_2neibors )
3171 break; // neighbor is on VERTEX
3173 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3174 if ( nextEdge == prevEdge )
3175 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3176 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
3177 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
3178 double r = double(step-1)/nbSteps;
3179 if ( !nextEdge->_2neibors )
3182 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3183 newNorm.Normalize();
3185 neighbor->_normal = newNorm;
3186 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3187 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3189 neighbor->InvalidateStep( 1 );
3191 neighbor->SetNewLength( data._stepSize, helper );
3193 // goto the next neighbor
3194 prevEdge = neighbor;
3195 neighbor = nextEdge;
3201 // 2) Check absence of intersections
3204 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3210 //================================================================================
3212 * \brief Looks for intersection of it's last segment with faces
3213 * \param distance - returns shortest distance from the last node to intersection
3215 //================================================================================
3217 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
3219 const double& epsilon,
3220 const SMDS_MeshElement** face)
3222 vector< const SMDS_MeshElement* > suspectFaces;
3224 gp_Ax1 lastSegment = LastSegment(segLen);
3225 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
3227 bool segmentIntersected = false;
3228 distance = Precision::Infinite();
3229 int iFace = -1; // intersected face
3230 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3232 const SMDS_MeshElement* face = suspectFaces[j];
3233 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3234 face->GetNodeIndex( _nodes[0] ) >= 0 )
3235 continue; // face sharing _LayerEdge node
3236 const int nbNodes = face->NbCornerNodes();
3237 bool intFound = false;
3239 SMDS_MeshElement::iterator nIt = face->begin_nodes();
3242 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3246 const SMDS_MeshNode* tria[3];
3249 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3252 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3258 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3259 segmentIntersected = true;
3260 if ( distance > dist )
3261 distance = dist, iFace = j;
3264 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3265 // if ( distance && iFace > -1 )
3267 // // distance is used to limit size of inflation step which depends on
3268 // // whether the intersected face bears viscous layers or not
3269 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3273 if ( segmentIntersected )
3276 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3277 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3278 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3279 << ", intersection with face ("
3280 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3281 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3282 << ") distance = " << distance - segLen<< endl;
3288 return segmentIntersected;
3291 //================================================================================
3293 * \brief Returns size and direction of the last segment
3295 //================================================================================
3297 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3299 // find two non-coincident positions
3300 gp_XYZ orig = _pos.back();
3302 int iPrev = _pos.size() - 2;
3303 while ( iPrev >= 0 )
3305 dir = orig - _pos[iPrev];
3306 if ( dir.SquareModulus() > 1e-100 )
3316 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3317 segDir.SetDirection( _normal );
3322 gp_Pnt pPrev = _pos[ iPrev ];
3323 if ( !_sWOL.IsNull() )
3325 TopLoc_Location loc;
3326 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3329 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3330 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3334 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3335 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3337 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3339 segDir.SetLocation( pPrev );
3340 segDir.SetDirection( dir );
3341 segLen = dir.Modulus();
3347 //================================================================================
3349 * \brief Test intersection of the last segment with a given triangle
3350 * using Moller-Trumbore algorithm
3351 * Intersection is detected if distance to intersection is less than _LayerEdge._len
3353 //================================================================================
3355 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
3356 const SMDS_MeshNode* n0,
3357 const SMDS_MeshNode* n1,
3358 const SMDS_MeshNode* n2,
3360 const double& EPSILON) const
3362 //const double EPSILON = 1e-6;
3364 gp_XYZ orig = lastSegment.Location().XYZ();
3365 gp_XYZ dir = lastSegment.Direction().XYZ();
3367 SMESH_TNodeXYZ vert0( n0 );
3368 SMESH_TNodeXYZ vert1( n1 );
3369 SMESH_TNodeXYZ vert2( n2 );
3371 /* calculate distance from vert0 to ray origin */
3372 gp_XYZ tvec = orig - vert0;
3374 if ( tvec * dir > EPSILON )
3375 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3378 gp_XYZ edge1 = vert1 - vert0;
3379 gp_XYZ edge2 = vert2 - vert0;
3381 /* begin calculating determinant - also used to calculate U parameter */
3382 gp_XYZ pvec = dir ^ edge2;
3384 /* if determinant is near zero, ray lies in plane of triangle */
3385 double det = edge1 * pvec;
3387 if (det > -EPSILON && det < EPSILON)
3389 double inv_det = 1.0 / det;
3391 /* calculate U parameter and test bounds */
3392 double u = ( tvec * pvec ) * inv_det;
3393 if (u < 0.0 || u > 1.0)
3396 /* prepare to test V parameter */
3397 gp_XYZ qvec = tvec ^ edge1;
3399 /* calculate V parameter and test bounds */
3400 double v = (dir * qvec) * inv_det;
3401 if ( v < 0.0 || u + v > 1.0 )
3404 /* calculate t, ray intersects triangle */
3405 t = (edge2 * qvec) * inv_det;
3407 // if (det < EPSILON)
3410 // /* calculate distance from vert0 to ray origin */
3411 // gp_XYZ tvec = orig - vert0;
3413 // /* calculate U parameter and test bounds */
3414 // double u = tvec * pvec;
3415 // if (u < 0.0 || u > det)
3418 // /* prepare to test V parameter */
3419 // gp_XYZ qvec = tvec ^ edge1;
3421 // /* calculate V parameter and test bounds */
3422 // double v = dir * qvec;
3423 // if (v < 0.0 || u + v > det)
3426 // /* calculate t, scale parameters, ray intersects triangle */
3427 // double t = edge2 * qvec;
3428 // double inv_det = 1.0 / det;
3436 //================================================================================
3438 * \brief Perform smooth of _LayerEdge's based on EDGE's
3439 * \retval bool - true if node has been moved
3441 //================================================================================
3443 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3444 const TopoDS_Face& F,
3445 SMESH_MesherHelper& helper)
3447 ASSERT( IsOnEdge() );
3449 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3450 SMESH_TNodeXYZ oldPos( tgtNode );
3451 double dist01, distNewOld;
3453 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3454 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3455 dist01 = p0.Distance( _2neibors->_nodes[1] );
3457 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3458 double lenDelta = 0;
3461 //lenDelta = _curvature->lenDelta( _len );
3462 lenDelta = _curvature->lenDeltaByDist( dist01 );
3463 newPos.ChangeCoord() += _normal * lenDelta;
3466 distNewOld = newPos.Distance( oldPos );
3470 if ( _2neibors->_plnNorm )
3472 // put newPos on the plane defined by source node and _plnNorm
3473 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3474 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3475 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3477 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3478 _pos.back() = newPos.XYZ();
3482 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3483 gp_XY uv( Precision::Infinite(), 0 );
3484 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3485 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3487 newPos = surface->Value( uv.X(), uv.Y() );
3488 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3491 if ( _curvature && lenDelta < 0 )
3493 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3494 _len -= prevPos.Distance( oldPos );
3495 _len += prevPos.Distance( newPos );
3497 bool moved = distNewOld > dist01/50;
3499 dumpMove( tgtNode ); // debug
3504 //================================================================================
3506 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3507 * \retval bool - true if _tgtNode has been moved
3509 //================================================================================
3511 bool _LayerEdge::Smooth(int& badNb)
3513 if ( _simplices.size() < 2 )
3514 return false; // _LayerEdge inflated along EDGE or FACE
3516 // compute new position for the last _pos
3517 gp_XYZ newPos (0,0,0);
3518 for ( size_t i = 0; i < _simplices.size(); ++i )
3519 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3520 newPos /= _simplices.size();
3523 newPos += _normal * _curvature->lenDelta( _len );
3525 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3526 // if ( _cosin < -0.1)
3528 // // Avoid decreasing length of edge on concave surface
3529 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3530 // gp_Vec newMove( prevPos, newPos );
3531 // newPos = _pos.back() + newMove.XYZ();
3533 // else if ( _cosin > 0.3 )
3535 // // Avoid increasing length of edge too much
3538 // count quality metrics (orientation) of tetras around _tgtNode
3540 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3541 for ( size_t i = 0; i < _simplices.size(); ++i )
3542 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3545 for ( size_t i = 0; i < _simplices.size(); ++i )
3546 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3548 if ( nbOkAfter < nbOkBefore )
3551 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3553 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3554 _len += prevPos.Distance(newPos);
3556 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3557 _pos.back() = newPos;
3559 badNb += _simplices.size() - nbOkAfter;
3566 //================================================================================
3568 * \brief Add a new segment to _LayerEdge during inflation
3570 //================================================================================
3572 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3574 if ( _len - len > -1e-6 )
3576 _pos.push_back( _pos.back() );
3580 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3581 SMESH_TNodeXYZ oldXYZ( n );
3582 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3583 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3585 _pos.push_back( nXYZ );
3587 if ( !_sWOL.IsNull() )
3590 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3592 double u = Precision::Infinite(); // to force projection w/o distance check
3593 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3594 _pos.back().SetCoord( u, 0, 0 );
3595 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3596 pos->SetUParameter( u );
3600 gp_XY uv( Precision::Infinite(), 0 );
3601 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3602 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3603 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3604 pos->SetUParameter( uv.X() );
3605 pos->SetVParameter( uv.Y() );
3607 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3609 dumpMove( n ); //debug
3612 //================================================================================
3614 * \brief Remove last inflation step
3616 //================================================================================
3618 void _LayerEdge::InvalidateStep( int curStep )
3620 if ( _pos.size() > curStep )
3622 _pos.resize( curStep );
3623 gp_Pnt nXYZ = _pos.back();
3624 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3625 if ( !_sWOL.IsNull() )
3627 TopLoc_Location loc;
3628 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3630 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3631 pos->SetUParameter( nXYZ.X() );
3633 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3634 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3638 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3639 pos->SetUParameter( nXYZ.X() );
3640 pos->SetVParameter( nXYZ.Y() );
3641 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3642 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3645 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3650 //================================================================================
3652 * \brief Create layers of prisms
3654 //================================================================================
3656 bool _ViscousBuilder::refine(_SolidData& data)
3658 SMESH_MesherHelper helper( *_mesh );
3659 helper.SetSubShape( data._solid );
3660 helper.SetElementsOnShape(false);
3662 Handle(Geom_Curve) curve;
3663 Handle(Geom_Surface) surface;
3664 TopoDS_Edge geomEdge;
3665 TopoDS_Face geomFace;
3666 TopLoc_Location loc;
3667 double f,l, u/*, distXYZ[4]*/;
3671 for ( size_t i = 0; i < data._edges.size(); ++i )
3673 _LayerEdge& edge = *data._edges[i];
3675 // get accumulated length of segments
3676 vector< double > segLen( edge._pos.size() );
3678 for ( size_t j = 1; j < edge._pos.size(); ++j )
3679 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3681 // allocate memory for new nodes if it is not yet refined
3682 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3683 if ( edge._nodes.size() == 2 )
3685 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3687 edge._nodes.back() = tgtNode;
3689 if ( !edge._sWOL.IsNull() )
3691 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3692 // restore position of the last node
3696 geomEdge = TopoDS::Edge( edge._sWOL );
3697 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3698 // double u = helper.GetNodeU( tgtNode );
3699 // p = curve->Value( u );
3703 geomFace = TopoDS::Face( edge._sWOL );
3704 surface = BRep_Tool::Surface( geomFace, loc );
3705 // gp_XY uv = helper.GetNodeUV( tgtNode );
3706 // p = surface->Value( uv.X(), uv.Y() );
3708 // p.Transform( loc );
3709 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3711 // calculate height of the first layer
3713 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3714 const double f = data._hyp->GetStretchFactor();
3715 const int N = data._hyp->GetNumberLayers();
3716 const double fPowN = pow( f, N );
3717 if ( fPowN - 1 <= numeric_limits<double>::min() )
3720 h0 = T * ( f - 1 )/( fPowN - 1 );
3722 const double zeroLen = std::numeric_limits<double>::min();
3724 // create intermediate nodes
3725 double hSum = 0, hi = h0/f;
3727 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3729 // compute an intermediate position
3732 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3734 int iPrevSeg = iSeg-1;
3735 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3737 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3738 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3740 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3741 if ( !edge._sWOL.IsNull() )
3743 // compute XYZ by parameters <pos>
3747 pos = curve->Value( u ).Transformed(loc);
3751 uv.SetCoord( pos.X(), pos.Y() );
3752 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3755 // create or update the node
3758 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3759 if ( !edge._sWOL.IsNull() )
3762 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3764 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3768 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3773 if ( !edge._sWOL.IsNull() )
3775 // make average pos from new and current parameters
3778 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3779 pos = curve->Value( u ).Transformed(loc);
3783 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3784 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3787 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3792 if ( !getMeshDS()->IsEmbeddedMode() )
3793 // Log node movement
3794 for ( size_t i = 0; i < data._edges.size(); ++i )
3796 _LayerEdge& edge = *data._edges[i];
3797 SMESH_TNodeXYZ p ( edge._nodes.back() );
3798 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3801 // TODO: make quadratic prisms and polyhedrons(?)
3803 helper.SetElementsOnShape(true);
3805 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3806 for ( ; exp.More(); exp.Next() )
3808 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3810 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3811 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3812 vector< vector<const SMDS_MeshNode*>* > nnVec;
3813 while ( fIt->more() )
3815 const SMDS_MeshElement* face = fIt->next();
3816 int nbNodes = face->NbCornerNodes();
3817 nnVec.resize( nbNodes );
3818 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3819 for ( int iN = 0; iN < nbNodes; ++iN )
3821 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3822 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3825 int nbZ = nnVec[0]->size();
3829 for ( int iZ = 1; iZ < nbZ; ++iZ )
3830 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3831 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3834 for ( int iZ = 1; iZ < nbZ; ++iZ )
3835 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3836 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3837 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3838 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3841 return error("Not supported type of element", data._index);
3848 //================================================================================
3850 * \brief Shrink 2D mesh on faces to let space for inflated layers
3852 //================================================================================
3854 bool _ViscousBuilder::shrink()
3856 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3857 // inflated along FACE or EDGE)
3858 map< TGeomID, _SolidData* > f2sdMap;
3859 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3861 _SolidData& data = _sdVec[i];
3862 TopTools_MapOfShape FFMap;
3863 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3864 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3865 if ( s2s->second.ShapeType() == TopAbs_FACE )
3867 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3869 if ( FFMap.Add( (*s2s).second ))
3870 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3871 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3872 // by StdMeshers_QuadToTriaAdaptor
3873 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3875 SMESH_ProxyMesh::SubMesh* proxySub =
3876 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3877 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3878 while ( fIt->more() )
3879 proxySub->AddElement( fIt->next() );
3880 // as a result 3D algo will use elements from proxySub and not from smDS
3885 SMESH_MesherHelper helper( *_mesh );
3886 helper.ToFixNodeParameters( true );
3889 map< TGeomID, _Shrinker1D > e2shrMap;
3891 // loop on FACES to srink mesh on
3892 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3893 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3895 _SolidData& data = *f2sd->second;
3896 TNode2Edge& n2eMap = data._n2eMap;
3897 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3899 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3901 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3902 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3904 helper.SetSubShape(F);
3906 // ===========================
3907 // Prepare data for shrinking
3908 // ===========================
3910 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3911 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3912 vector < const SMDS_MeshNode* > smoothNodes;
3914 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3915 while ( nIt->more() )
3917 const SMDS_MeshNode* n = nIt->next();
3918 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3919 smoothNodes.push_back( n );
3922 // Find out face orientation
3924 const set<TGeomID> ignoreShapes;
3926 if ( !smoothNodes.empty() )
3928 vector<_Simplex> simplices;
3929 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3930 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3931 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3932 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3933 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3937 // Find _LayerEdge's inflated along F
3938 vector< _LayerEdge* > lEdges;
3940 SMESH_subMeshIteratorPtr subIt =
3941 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3942 while ( subIt->more() )
3944 SMESH_subMesh* sub = subIt->next();
3945 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3946 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3948 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3949 while ( nIt->more() )
3951 _LayerEdge* edge = n2eMap[ nIt->next() ];
3952 lEdges.push_back( edge );
3953 prepareEdgeToShrink( *edge, F, helper, smDS );
3958 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3959 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3960 while ( fIt->more() )
3961 if ( const SMDS_MeshElement* f = fIt->next() )
3962 dumpChangeNodes( f );
3964 // Replace source nodes by target nodes in mesh faces to shrink
3965 const SMDS_MeshNode* nodes[20];
3966 for ( size_t i = 0; i < lEdges.size(); ++i )
3968 _LayerEdge& edge = *lEdges[i];
3969 const SMDS_MeshNode* srcNode = edge._nodes[0];
3970 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3971 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3972 while ( fIt->more() )
3974 const SMDS_MeshElement* f = fIt->next();
3975 if ( !smDS->Contains( f ))
3977 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
3978 for ( int iN = 0; nIt->more(); ++iN )
3980 const SMDS_MeshNode* n = nIt->next();
3981 nodes[iN] = ( n == srcNode ? tgtNode : n );
3983 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3987 // find out if a FACE is concave
3988 const bool isConcaveFace = isConcave( F, helper );
3990 // Create _SmoothNode's on face F
3991 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3993 const bool sortSimplices = isConcaveFace;
3994 for ( size_t i = 0; i < smoothNodes.size(); ++i )
3996 const SMDS_MeshNode* n = smoothNodes[i];
3997 nodesToSmooth[ i ]._node = n;
3998 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3999 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
4000 // fix up incorrect uv of nodes on the FACE
4001 helper.GetNodeUV( F, n, 0, &isOkUV);
4005 //if ( nodesToSmooth.empty() ) continue;
4007 // Find EDGE's to shrink and set simpices to LayerEdge's
4008 set< _Shrinker1D* > eShri1D;
4010 for ( size_t i = 0; i < lEdges.size(); ++i )
4012 _LayerEdge* edge = lEdges[i];
4013 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4015 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4016 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4017 eShri1D.insert( & srinker );
4018 srinker.AddEdge( edge, helper );
4019 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4020 // restore params of nodes on EGDE if the EDGE has been already
4021 // srinked while srinking another FACE
4022 srinker.RestoreParams();
4024 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4028 bool toFixTria = false; // to improve quality of trias by diagonal swap
4029 if ( isConcaveFace )
4031 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4032 if ( hasTria != hasQuad ) {
4033 toFixTria = hasTria;
4036 set<int> nbNodesSet;
4037 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4038 while ( fIt->more() && nbNodesSet.size() < 2 )
4039 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4040 toFixTria = ( *nbNodesSet.begin() == 3 );
4044 // ==================
4045 // Perform shrinking
4046 // ==================
4048 bool shrinked = true;
4049 int badNb, shriStep=0, smooStep=0;
4050 _SmoothNode::SmoothType smoothType
4051 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4055 // Move boundary nodes (actually just set new UV)
4056 // -----------------------------------------------
4057 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4059 for ( size_t i = 0; i < lEdges.size(); ++i )
4061 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4065 // Move nodes on EDGE's
4066 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4067 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4068 for ( ; shr != eShri1D.end(); ++shr )
4069 (*shr)->Compute( /*set3D=*/false, helper );
4072 // -----------------
4073 int nbNoImpSteps = 0;
4076 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4078 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4080 int oldBadNb = badNb;
4083 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4085 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4086 smoothType, /*set3D=*/isConcaveFace);
4088 if ( badNb < oldBadNb )
4096 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4097 if ( shriStep > 200 )
4098 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4100 // Fix narrow triangles by swapping diagonals
4101 // ---------------------------------------
4104 set<const SMDS_MeshNode*> usedNodes;
4105 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4107 // update working data
4108 set<const SMDS_MeshNode*>::iterator n;
4109 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4111 n = usedNodes.find( nodesToSmooth[ i ]._node );
4112 if ( n != usedNodes.end())
4114 getSimplices( nodesToSmooth[ i ]._node,
4115 nodesToSmooth[ i ]._simplices,
4117 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4118 usedNodes.erase( n );
4121 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4123 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4124 if ( n != usedNodes.end())
4126 getSimplices( lEdges[i]->_nodes.back(),
4127 lEdges[i]->_simplices,
4129 usedNodes.erase( n );
4133 } // while ( shrinked )
4135 // No wrongly shaped faces remain; final smooth. Set node XYZ.
4136 bool isStructuredFixed = false;
4137 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4138 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4139 if ( !isStructuredFixed )
4141 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4142 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4144 for ( int st = 3; st; --st )
4147 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4148 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4149 case 3: smoothType = _SmoothNode::ANGULAR; break;
4151 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4152 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4154 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4155 smoothType,/*set3D=*/st==1 );
4160 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4161 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4163 if ( !getMeshDS()->IsEmbeddedMode() )
4164 // Log node movement
4165 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4167 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4168 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4171 } // loop on FACES to srink mesh on
4174 // Replace source nodes by target nodes in shrinked mesh edges
4176 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4177 for ( ; e2shr != e2shrMap.end(); ++e2shr )
4178 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4183 //================================================================================
4185 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4187 //================================================================================
4189 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
4190 const TopoDS_Face& F,
4191 SMESH_MesherHelper& helper,
4192 const SMESHDS_SubMesh* faceSubMesh)
4194 const SMDS_MeshNode* srcNode = edge._nodes[0];
4195 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4199 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4201 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4202 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4203 gp_Vec2d uvDir( srcUV, tgtUV );
4204 double uvLen = uvDir.Magnitude();
4206 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4209 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4210 // vector<const SMDS_MeshElement*> faces;
4211 // multimap< double, const SMDS_MeshNode* > proj2node;
4212 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4213 // while ( fIt->more() )
4215 // const SMDS_MeshElement* f = fIt->next();
4216 // if ( faceSubMesh->Contains( f ))
4217 // faces.push_back( f );
4219 // for ( size_t i = 0; i < faces.size(); ++i )
4221 // const int nbNodes = faces[i]->NbCornerNodes();
4222 // for ( int j = 0; j < nbNodes; ++j )
4224 // const SMDS_MeshNode* n = faces[i]->GetNode(j);
4225 // if ( n == srcNode ) continue;
4226 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
4227 // ( faces.size() > 1 || nbNodes > 3 ))
4229 // gp_Pnt2d uv = helper.GetNodeUV( F, n );
4230 // gp_Vec2d uvDirN( srcUV, uv );
4231 // double proj = uvDirN * uvDir;
4232 // proj2node.insert( make_pair( proj, n ));
4236 // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4237 // const double minProj = p2n->first;
4238 // const double projThreshold = 1.1 * uvLen;
4239 // if ( minProj > projThreshold )
4241 // // tgtNode is located so that it does not make faces with wrong orientation
4244 edge._pos.resize(1);
4245 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4247 // store most risky nodes in _simplices
4248 // p2nEnd = proj2node.lower_bound( projThreshold );
4249 // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4250 // edge._simplices.resize( nbSimpl );
4251 // for ( int i = 0; i < nbSimpl; ++i )
4253 // edge._simplices[i]._nPrev = p2n->second;
4254 // if ( ++p2n != p2nEnd )
4255 // edge._simplices[i]._nNext = p2n->second;
4257 // set UV of source node to target node
4258 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4259 pos->SetUParameter( srcUV.X() );
4260 pos->SetVParameter( srcUV.Y() );
4262 else // _sWOL is TopAbs_EDGE
4264 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4265 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4266 if ( !edgeSM || edgeSM->NbElements() == 0 )
4267 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4269 const SMDS_MeshNode* n2 = 0;
4270 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4271 while ( eIt->more() && !n2 )
4273 const SMDS_MeshElement* e = eIt->next();
4274 if ( !edgeSM->Contains(e)) continue;
4275 n2 = e->GetNode( 0 );
4276 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4279 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4281 double uSrc = helper.GetNodeU( E, srcNode, n2 );
4282 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4283 double u2 = helper.GetNodeU( E, n2, srcNode );
4285 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4287 // tgtNode is located so that it does not make faces with wrong orientation
4290 edge._pos.resize(1);
4291 edge._pos[0].SetCoord( U_TGT, uTgt );
4292 edge._pos[0].SetCoord( U_SRC, uSrc );
4293 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4295 edge._simplices.resize( 1 );
4296 edge._simplices[0]._nPrev = n2;
4298 // set UV of source node to target node
4299 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4300 pos->SetUParameter( uSrc );
4304 //================================================================================
4306 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4308 //================================================================================
4310 // Compute UV to follow during shrinking
4312 // const SMDS_MeshNode* srcNode = edge._nodes[0];
4313 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
4315 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4316 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4317 // gp_Vec2d uvDir( srcUV, tgtUV );
4318 // double uvLen = uvDir.Magnitude();
4321 // // Select shrinking step such that not to make faces with wrong orientation.
4322 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4323 // const double minStepSize = uvLen / 20;
4324 // double stepSize = uvLen;
4325 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4326 // while ( fIt->more() )
4328 // const SMDS_MeshElement* f = fIt->next();
4329 // if ( !faceSubMesh->Contains( f )) continue;
4330 // const int nbNodes = f->NbCornerNodes();
4331 // for ( int i = 0; i < nbNodes; ++i )
4333 // const SMDS_MeshNode* n = f->GetNode(i);
4334 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4336 // gp_XY uv = helper.GetNodeUV( F, n );
4337 // gp_Vec2d uvDirN( srcUV, uv );
4338 // double proj = uvDirN * uvDir;
4339 // if ( proj < stepSize && proj > minStepSize )
4345 // const int nbSteps = ceil( uvLen / stepSize );
4346 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4347 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4348 // edge._pos.resize( nbSteps );
4349 // edge._pos[0] = tgtUV0;
4350 // for ( int i = 1; i < nbSteps; ++i )
4352 // double r = i / double( nbSteps );
4353 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4358 //================================================================================
4360 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4362 //================================================================================
4364 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
4365 SMESH_MesherHelper& helper,
4368 set<const SMDS_MeshNode*> * involvedNodes)
4370 SMESH::Controls::AspectRatio qualifier;
4371 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4372 const double maxAspectRatio = is2D ? 4. : 2;
4373 NodeCoordHelper xyz( F, helper, is2D );
4375 // find bad triangles
4377 vector< const SMDS_MeshElement* > badTrias;
4378 vector< double > badAspects;
4379 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
4380 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4381 while ( fIt->more() )
4383 const SMDS_MeshElement * f = fIt->next();
4384 if ( f->NbCornerNodes() != 3 ) continue;
4385 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4386 double aspect = qualifier.GetValue( points );
4387 if ( aspect > maxAspectRatio )
4389 badTrias.push_back( f );
4390 badAspects.push_back( aspect );
4395 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4396 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4397 while ( fIt->more() )
4399 const SMDS_MeshElement * f = fIt->next();
4400 if ( f->NbCornerNodes() == 3 )
4401 dumpChangeNodes( f );
4405 if ( badTrias.empty() )
4408 // find couples of faces to swap diagonal
4410 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4411 vector< T2Trias > triaCouples;
4413 TIDSortedElemSet involvedFaces, emptySet;
4414 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4417 double aspRatio [3];
4420 if ( !involvedFaces.insert( badTrias[iTia] ).second )
4422 for ( int iP = 0; iP < 3; ++iP )
4423 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4425 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4426 int bestCouple = -1;
4427 for ( int iSide = 0; iSide < 3; ++iSide )
4429 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4430 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4431 trias [iSide].first = badTrias[iTia];
4432 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4434 if (( ! trias[iSide].second ) ||
4435 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4436 ( ! sm->Contains( trias[iSide].second )))
4439 // aspect ratio of an adjacent tria
4440 for ( int iP = 0; iP < 3; ++iP )
4441 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4442 double aspectInit = qualifier.GetValue( points2 );
4444 // arrange nodes as after diag-swaping
4445 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4446 i3 = helper.WrapIndex( i1-1, 3 );
4448 i3 = helper.WrapIndex( i1+1, 3 );
4450 points1( 1+ iSide ) = points2( 1+ i3 );
4451 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
4453 // aspect ratio after diag-swaping
4454 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4455 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4458 // prevent inversion of a triangle
4459 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4460 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4461 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4464 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4468 if ( bestCouple >= 0 )
4470 triaCouples.push_back( trias[bestCouple] );
4471 involvedFaces.insert ( trias[bestCouple].second );
4475 involvedFaces.erase( badTrias[iTia] );
4478 if ( triaCouples.empty() )
4483 SMESH_MeshEditor editor( helper.GetMesh() );
4484 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4485 for ( size_t i = 0; i < triaCouples.size(); ++i )
4487 dumpChangeNodes( triaCouples[i].first );
4488 dumpChangeNodes( triaCouples[i].second );
4489 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4492 if ( involvedNodes )
4493 for ( size_t i = 0; i < triaCouples.size(); ++i )
4495 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4496 triaCouples[i].first->end_nodes() );
4497 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4498 triaCouples[i].second->end_nodes() );
4501 // just for debug dump resulting triangles
4502 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4503 for ( size_t i = 0; i < triaCouples.size(); ++i )
4505 dumpChangeNodes( triaCouples[i].first );
4506 dumpChangeNodes( triaCouples[i].second );
4510 //================================================================================
4512 * \brief Move target node to it's final position on the FACE during shrinking
4514 //================================================================================
4516 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4517 const TopoDS_Face& F,
4518 SMESH_MesherHelper& helper )
4521 return false; // already at the target position
4523 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4525 if ( _sWOL.ShapeType() == TopAbs_FACE )
4527 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4528 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4529 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4530 const double uvLen = tgtUV.Distance( curUV );
4531 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4533 // Select shrinking step such that not to make faces with wrong orientation.
4534 double stepSize = uvLen;
4535 for ( size_t i = 0; i < _simplices.size(); ++i )
4537 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4538 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4539 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4540 gp_XY dirN = uvN2 - uvN1;
4541 double det = uvDir.Crossed( dirN );
4542 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
4543 gp_XY dirN2Cur = curUV - uvN1;
4544 double step = dirN.Crossed( dirN2Cur ) / det;
4546 stepSize = Min( step, stepSize );
4549 if ( uvLen - stepSize < _len / 200. )
4554 else if ( stepSize > 0 )
4556 newUV = curUV + uvDir.XY() * stepSize * kSafe;
4562 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4563 pos->SetUParameter( newUV.X() );
4564 pos->SetVParameter( newUV.Y() );
4567 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4568 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4569 dumpMove( tgtNode );
4572 else // _sWOL is TopAbs_EDGE
4574 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4575 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4576 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4578 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4579 const double uSrc = _pos[0].Coord( U_SRC );
4580 const double lenTgt = _pos[0].Coord( LEN_TGT );
4582 double newU = _pos[0].Coord( U_TGT );
4583 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4589 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4591 tgtPos->SetUParameter( newU );
4593 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4594 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4595 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4596 dumpMove( tgtNode );
4602 //================================================================================
4604 * \brief Perform smooth on the FACE
4605 * \retval bool - true if the node has been moved
4607 //================================================================================
4609 bool _SmoothNode::Smooth(int& badNb,
4610 Handle(Geom_Surface)& surface,
4611 SMESH_MesherHelper& helper,
4612 const double refSign,
4616 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4618 // get uv of surrounding nodes
4619 vector<gp_XY> uv( _simplices.size() );
4620 for ( size_t i = 0; i < _simplices.size(); ++i )
4621 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4623 // compute new UV for the node
4625 if ( how == TFI && _simplices.size() == 4 )
4628 for ( size_t i = 0; i < _simplices.size(); ++i )
4629 if ( _simplices[i]._nOpp )
4630 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4632 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4634 newPos = helper.calcTFI ( 0.5, 0.5,
4635 corners[0], corners[1], corners[2], corners[3],
4636 uv[1], uv[2], uv[3], uv[0] );
4638 else if ( how == ANGULAR )
4640 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4642 else if ( how == CENTROIDAL && _simplices.size() > 3 )
4644 // average centers of diagonals wieghted with their reciprocal lengths
4645 if ( _simplices.size() == 4 )
4647 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4648 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4649 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4653 double sumWeight = 0;
4654 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4655 for ( int i = 0; i < nb; ++i )
4658 int iTo = i + _simplices.size() - 1;
4659 for ( int j = iFrom; j < iTo; ++j )
4661 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4662 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4664 newPos += w * ( uv[i]+uv[i2] );
4667 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4673 for ( size_t i = 0; i < _simplices.size(); ++i )
4675 newPos /= _simplices.size();
4678 // count quality metrics (orientation) of triangles around the node
4680 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4681 for ( size_t i = 0; i < _simplices.size(); ++i )
4682 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4685 for ( size_t i = 0; i < _simplices.size(); ++i )
4686 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4688 if ( nbOkAfter < nbOkBefore )
4690 badNb += _simplices.size() - nbOkBefore;
4694 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4695 pos->SetUParameter( newPos.X() );
4696 pos->SetVParameter( newPos.Y() );
4703 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4704 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4708 badNb += _simplices.size() - nbOkAfter;
4709 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4712 //================================================================================
4714 * \brief Computes new UV using angle based smoothing technic
4716 //================================================================================
4718 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4719 const gp_XY& uvToFix,
4720 const double refSign)
4722 uv.push_back( uv.front() );
4724 vector< gp_XY > edgeDir ( uv.size() );
4725 vector< double > edgeSize( uv.size() );
4726 for ( size_t i = 1; i < edgeDir.size(); ++i )
4728 edgeDir [i-1] = uv[i] - uv[i-1];
4729 edgeSize[i-1] = edgeDir[i-1].Modulus();
4730 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4731 edgeDir[i-1].SetX( 100 );
4733 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4735 edgeDir.back() = edgeDir.front();
4736 edgeSize.back() = edgeSize.front();
4741 for ( size_t i = 1; i < edgeDir.size(); ++i )
4743 if ( edgeDir[i-1].X() > 1. ) continue;
4745 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4746 if ( i == edgeDir.size() ) break;
4748 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4749 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4750 gp_XY bisec = norm1 + norm2;
4751 double bisecSize = bisec.Modulus();
4752 if ( bisecSize < numeric_limits<double>::min() )
4754 bisec = -edgeDir[i1] + edgeDir[i];
4755 bisecSize = bisec.Modulus();
4759 gp_XY dirToN = uvToFix - p;
4760 double distToN = dirToN.Modulus();
4761 if ( bisec * dirToN < 0 )
4764 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4766 sumSize += edgeSize[i1] + edgeSize[i];
4768 newPos /= /*nbEdges * */sumSize;
4772 //================================================================================
4774 * \brief Delete _SolidData
4776 //================================================================================
4778 _SolidData::~_SolidData()
4780 for ( size_t i = 0; i < _edges.size(); ++i )
4782 if ( _edges[i] && _edges[i]->_2neibors )
4783 delete _edges[i]->_2neibors;
4788 //================================================================================
4790 * \brief Add a _LayerEdge inflated along the EDGE
4792 //================================================================================
4794 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4797 if ( _nodes.empty() )
4799 _edges[0] = _edges[1] = 0;
4803 if ( e == _edges[0] || e == _edges[1] )
4805 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4806 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4807 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4808 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4811 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4813 BRep_Tool::Range( E, f,l );
4814 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4815 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4819 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4820 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4822 if ( _nodes.empty() )
4824 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4825 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4827 TopLoc_Location loc;
4828 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4829 GeomAdaptor_Curve aCurve(C, f,l);
4830 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4832 int nbExpectNodes = eSubMesh->NbNodes();
4833 _initU .reserve( nbExpectNodes );
4834 _normPar.reserve( nbExpectNodes );
4835 _nodes .reserve( nbExpectNodes );
4836 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4837 while ( nIt->more() )
4839 const SMDS_MeshNode* node = nIt->next();
4840 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4841 node == tgtNode0 || node == tgtNode1 )
4842 continue; // refinement nodes
4843 _nodes.push_back( node );
4844 _initU.push_back( helper.GetNodeU( E, node ));
4845 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4846 _normPar.push_back( len / totLen );
4851 // remove target node of the _LayerEdge from _nodes
4853 for ( size_t i = 0; i < _nodes.size(); ++i )
4854 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4855 _nodes[i] = 0, nbFound++;
4856 if ( nbFound == _nodes.size() )
4861 //================================================================================
4863 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4865 //================================================================================
4867 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4869 if ( _done || _nodes.empty())
4871 const _LayerEdge* e = _edges[0];
4872 if ( !e ) e = _edges[1];
4875 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4876 ( !_edges[1] || _edges[1]->_pos.empty() ));
4878 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4880 if ( set3D || _done )
4882 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4883 GeomAdaptor_Curve aCurve(C, f,l);
4886 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4888 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4889 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4891 for ( size_t i = 0; i < _nodes.size(); ++i )
4893 if ( !_nodes[i] ) continue;
4894 double len = totLen * _normPar[i];
4895 GCPnts_AbscissaPoint discret( aCurve, len, f );
4896 if ( !discret.IsDone() )
4897 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4898 double u = discret.Parameter();
4899 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4900 pos->SetUParameter( u );
4901 gp_Pnt p = C->Value( u );
4902 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4907 BRep_Tool::Range( E, f,l );
4909 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4911 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4913 for ( size_t i = 0; i < _nodes.size(); ++i )
4915 if ( !_nodes[i] ) continue;
4916 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4917 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4918 pos->SetUParameter( u );
4923 //================================================================================
4925 * \brief Restore initial parameters of nodes on EDGE
4927 //================================================================================
4929 void _Shrinker1D::RestoreParams()
4932 for ( size_t i = 0; i < _nodes.size(); ++i )
4934 if ( !_nodes[i] ) continue;
4935 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4936 pos->SetUParameter( _initU[i] );
4941 //================================================================================
4943 * \brief Replace source nodes by target nodes in shrinked mesh edges
4945 //================================================================================
4947 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4949 const SMDS_MeshNode* nodes[3];
4950 for ( int i = 0; i < 2; ++i )
4952 if ( !_edges[i] ) continue;
4954 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4955 if ( !eSubMesh ) return;
4956 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4957 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4958 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4959 while ( eIt->more() )
4961 const SMDS_MeshElement* e = eIt->next();
4962 if ( !eSubMesh->Contains( e ))
4964 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4965 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4967 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4968 nodes[iN] = ( n == srcNode ? tgtNode : n );
4970 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4975 //================================================================================
4977 * \brief Creates 2D and 1D elements on boundaries of new prisms
4979 //================================================================================
4981 bool _ViscousBuilder::addBoundaryElements()
4983 SMESH_MesherHelper helper( *_mesh );
4985 for ( size_t i = 0; i < _sdVec.size(); ++i )
4987 _SolidData& data = _sdVec[i];
4988 TopTools_IndexedMapOfShape geomEdges;
4989 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4990 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4992 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4994 // Get _LayerEdge's based on E
4996 map< double, const SMDS_MeshNode* > u2nodes;
4997 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
5000 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
5001 TNode2Edge & n2eMap = data._n2eMap;
5002 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5004 //check if 2D elements are needed on E
5005 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5006 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5007 ledges.push_back( n2e->second );
5009 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5010 continue; // no layers on E
5011 ledges.push_back( n2eMap[ u2n->second ]);
5013 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5014 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5015 int nbSharedPyram = 0;
5016 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5017 while ( vIt->more() )
5019 const SMDS_MeshElement* v = vIt->next();
5020 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5022 if ( nbSharedPyram > 1 )
5023 continue; // not free border of the pyramid
5025 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5026 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5027 continue; // faces already created
5029 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5030 ledges.push_back( n2eMap[ u2n->second ]);
5032 // Find out orientation and type of face to create
5034 bool reverse = false, isOnFace;
5036 map< TGeomID, TopoDS_Shape >::iterator e2f =
5037 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5039 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5041 F = e2f->second.Oriented( TopAbs_FORWARD );
5042 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5043 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5044 reverse = !reverse, F.Reverse();
5045 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5050 // find FACE with layers sharing E
5051 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5052 while ( fIt->more() && F.IsNull() )
5054 const TopoDS_Shape* pF = fIt->next();
5055 if ( helper.IsSubShape( *pF, data._solid) &&
5056 !data._ignoreFaceIds.count( e2f->first ))
5060 // Find the sub-mesh to add new faces
5061 SMESHDS_SubMesh* sm = 0;
5063 sm = getMeshDS()->MeshElements( F );
5065 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5067 return error("error in addBoundaryElements()", data._index);
5070 const int dj1 = reverse ? 0 : 1;
5071 const int dj2 = reverse ? 1 : 0;
5072 for ( size_t j = 1; j < ledges.size(); ++j )
5074 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
5075 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
5077 for ( size_t z = 1; z < nn1.size(); ++z )
5078 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5080 for ( size_t z = 1; z < nn1.size(); ++z )
5081 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5085 for ( int isFirst = 0; isFirst < 2; ++isFirst )
5087 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5088 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5090 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
5091 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5093 helper.SetSubShape( edge->_sWOL );
5094 helper.SetElementsOnShape( true );
5095 for ( size_t z = 1; z < nn.size(); ++z )
5096 helper.AddEdge( nn[z-1], nn[z] );