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 };
97 const double theMinSmoothCosin = 0.1;
100 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
101 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
103 struct _MeshOfSolid : public SMESH_ProxyMesh,
104 public SMESH_subMeshEventListenerData
106 bool _n2nMapComputed;
108 _MeshOfSolid( SMESH_Mesh* mesh)
109 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
111 SMESH_ProxyMesh::setMesh( *mesh );
114 // returns submesh for a geom face
115 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
117 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
118 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
120 void setNode2Node(const SMDS_MeshNode* srcNode,
121 const SMDS_MeshNode* proxyNode,
122 const SMESH_ProxyMesh::SubMesh* subMesh)
124 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
127 //--------------------------------------------------------------------------------
129 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
130 * It is used to clear an inferior dim sub-meshes modified by viscous layers
132 class _ShrinkShapeListener : SMESH_subMeshEventListener
134 _ShrinkShapeListener()
135 : SMESH_subMeshEventListener(/*isDeletable=*/false,
136 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
138 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
139 virtual void ProcessEvent(const int event,
141 SMESH_subMesh* solidSM,
142 SMESH_subMeshEventListenerData* data,
143 const SMESH_Hypothesis* hyp)
145 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
147 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
151 //--------------------------------------------------------------------------------
153 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
154 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
155 * delete the data as soon as it has been used
157 class _ViscousListener : SMESH_subMeshEventListener
160 SMESH_subMeshEventListener(/*isDeletable=*/false,
161 "StdMeshers_ViscousLayers::_ViscousListener") {}
162 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
164 virtual void ProcessEvent(const int event,
166 SMESH_subMesh* subMesh,
167 SMESH_subMeshEventListenerData* data,
168 const SMESH_Hypothesis* hyp)
170 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
172 // delete SMESH_ProxyMesh containing temporary faces
173 subMesh->DeleteEventListener( this );
176 // Finds or creates proxy mesh of the solid
177 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
178 const TopoDS_Shape& solid,
181 if ( !mesh ) return 0;
182 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
183 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
184 if ( !data && toCreate )
186 data = new _MeshOfSolid(mesh);
187 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
188 sm->SetEventListener( Get(), data, sm );
192 // Removes proxy mesh of the solid
193 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
195 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
199 //================================================================================
201 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
202 * the main shape when sub-mesh of the main shape is cleared,
203 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
206 //================================================================================
208 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
210 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
211 SMESH_subMeshEventListenerData* data =
212 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
215 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
216 data->mySubMeshes.end())
217 data->mySubMeshes.push_back( sub );
221 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
222 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
225 //--------------------------------------------------------------------------------
227 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
228 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
229 * The class is used to check validity of face or volumes around a smoothed node;
230 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
234 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
235 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
236 _Simplex(const SMDS_MeshNode* nPrev=0,
237 const SMDS_MeshNode* nNext=0,
238 const SMDS_MeshNode* nOpp=0)
239 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
240 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
242 const double M[3][3] =
243 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
244 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
245 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
246 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
247 + M[0][1]*M[1][2]*M[2][0]
248 + M[0][2]*M[1][0]*M[2][1]
249 - M[0][0]*M[1][2]*M[2][1]
250 - M[0][1]*M[1][0]*M[2][2]
251 - M[0][2]*M[1][1]*M[2][0]);
252 return determinant > 1e-100;
254 bool IsForward(const gp_XY& tgtUV,
255 const SMDS_MeshNode* smoothedNode,
256 const TopoDS_Face& face,
257 SMESH_MesherHelper& helper,
258 const double refSign) const
260 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
261 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
262 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
264 return d*refSign > 1e-100;
266 bool IsNeighbour(const _Simplex& other) const
268 return _nPrev == other._nNext || _nNext == other._nPrev;
271 //--------------------------------------------------------------------------------
273 * Structure used to take into account surface curvature while smoothing
278 double _k; // factor to correct node smoothed position
279 double _h2lenRatio; // avgNormProj / (2*avgDist)
281 static _Curvature* New( double avgNormProj, double avgDist )
284 if ( fabs( avgNormProj / avgDist ) > 1./200 )
287 c->_r = avgDist * avgDist / avgNormProj;
288 c->_k = avgDist * avgDist / c->_r / c->_r;
289 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
290 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
294 double lenDelta(double len) const { return _k * ( _r + len ); }
295 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
298 //--------------------------------------------------------------------------------
300 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
304 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
305 const SMDS_MeshNode* _nodes[2];
306 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
308 double _wgt[2]; // weights of _nodes
309 _LayerEdge* _edges[2];
311 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
314 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
316 std::swap( _nodes[0], _nodes[1] );
317 std::swap( _wgt [0], _wgt [1] );
318 std::swap( _edges[0], _edges[1] );
321 //--------------------------------------------------------------------------------
323 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
324 * and a node of the most internal layer (_nodes.back())
328 vector< const SMDS_MeshNode*> _nodes;
330 gp_XYZ _normal; // to solid surface
331 vector<gp_XYZ> _pos; // points computed during inflation
332 double _len; // length achived with the last inflation step
333 double _cosin; // of angle (_normal ^ surface)
334 double _lenFactor; // to compute _len taking _cosin into account
336 // face or edge w/o layer along or near which _LayerEdge is inflated
338 // simplices connected to the source node (_nodes[0]);
339 // used for smoothing and quality check of _LayerEdge's based on the FACE
340 vector<_Simplex> _simplices;
341 // data for smoothing of _LayerEdge's based on the EDGE
342 _2NearEdges* _2neibors;
344 _Curvature* _curvature;
345 // TODO:: detele _Curvature, _plnNorm
347 void SetNewLength( double len, SMESH_MesherHelper& helper );
348 bool SetNewLength2d( Handle(Geom_Surface)& surface,
349 const TopoDS_Face& F,
350 SMESH_MesherHelper& helper );
351 void SetDataByNeighbors( const SMDS_MeshNode* n1,
352 const SMDS_MeshNode* n2,
353 SMESH_MesherHelper& helper);
354 void InvalidateStep( int curStep, bool restoreLength=false );
355 bool Smooth(int& badNb);
356 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
357 const TopoDS_Face& F,
358 SMESH_MesherHelper& helper);
359 bool FindIntersection( SMESH_ElementSearcher& searcher,
361 const double& epsilon,
362 const SMDS_MeshElement** face = 0);
363 bool SegTriaInter( const gp_Ax1& lastSegment,
364 const SMDS_MeshNode* n0,
365 const SMDS_MeshNode* n1,
366 const SMDS_MeshNode* n2,
368 const double& epsilon) const;
369 gp_Ax1 LastSegment(double& segLen) const;
370 bool IsOnEdge() const { return _2neibors; }
371 gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
372 void SetCosin( double cosin );
376 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
378 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
379 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
382 //--------------------------------------------------------------------------------
384 * \brief Convex FACE whose radius of curvature is less than the thickness of
385 * layers. It is used to detect distortion of prisms based on a convex
386 * FACE and to update normals to enable further increasing the thickness
392 // edges whose _simplices are used to detect prism destorsion
393 vector< _LayerEdge* > _simplexTestEdges;
395 // map a sub-shape to it's index in _SolidData::_endEdgeOnShape vector
396 map< TGeomID, int > _subIdToEdgeEnd;
400 bool GetCenterOfCurvature( _LayerEdge* ledge,
401 BRepLProp_SLProps& surfProp,
402 SMESH_MesherHelper& helper,
403 gp_Pnt & center ) const;
404 bool CheckPrisms() const;
407 //--------------------------------------------------------------------------------
409 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
411 //--------------------------------------------------------------------------------
413 * \brief Data of a SOLID
418 const StdMeshers_ViscousLayers* _hyp;
419 TopoDS_Shape _hypShape;
420 _MeshOfSolid* _proxyMesh;
421 set<TGeomID> _reversedFaceIds;
422 set<TGeomID> _ignoreFaceIds;
424 double _stepSize, _stepSizeCoeff;
425 const SMDS_MeshNode* _stepSizeNodes[2];
428 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
429 map< TGeomID, TNode2Edge* > _s2neMap;
430 // edges of _n2eMap. We keep same data in two containers because
431 // iteration over the map is 5 time longer than over the vector
432 vector< _LayerEdge* > _edges;
434 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
435 // layers and a FACE w/o layers
436 // value: the shape (FACE or EDGE) to shrink mesh on.
437 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
438 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
440 // Convex FACEs whose radius of curvature is less than the thickness of layers
441 map< TGeomID, _ConvexFace > _convexFaces;
443 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
444 set< TGeomID > _noShrinkFaces;
446 // <EDGE to smooth on> to <it's curve> -- for analytic smooth
447 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
449 // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
450 vector< int > _endEdgeOnShape;
451 int _nbShapesToSmooth;
453 double _epsilon; // precision for SegTriaInter()
455 int _index; // for debug
457 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
458 const StdMeshers_ViscousLayers* h=0,
459 const TopoDS_Shape& hs=TopoDS_Shape(),
461 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
464 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
467 Handle(Geom_Surface)& surface,
468 const TopoDS_Face& F,
469 SMESH_MesherHelper& helper);
471 void SortOnEdge( const TopoDS_Edge& E,
474 SMESH_MesherHelper& helper);
476 _ConvexFace* GetConvexFace( const TGeomID faceID )
478 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
479 return id2face == _convexFaces.end() ? 0 : & id2face->second;
481 void GetEdgesOnShape( size_t end, int & iBeg, int & iEnd )
483 iBeg = end > 0 ? _endEdgeOnShape[ end-1 ] : 0;
484 iEnd = _endEdgeOnShape[ end ];
487 bool GetShapeEdges(const TGeomID shapeID, size_t& edgeEnd, int* iBeg=0, int* iEnd=0 ) const;
489 void AddFacesToSmooth( const set< TGeomID >& faceIDs );
491 //--------------------------------------------------------------------------------
493 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
495 struct _CentralCurveOnEdge
498 vector< gp_Pnt > _curvaCenters;
499 vector< _LayerEdge* > _ledges;
500 vector< gp_XYZ > _normals; // new normal for each of _ledges
501 vector< double > _segLength2;
504 TopoDS_Face _adjFace;
505 bool _adjFaceToSmooth;
507 void Append( const gp_Pnt& center, _LayerEdge* ledge )
509 if ( _curvaCenters.size() > 0 )
510 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
511 _curvaCenters.push_back( center );
512 _ledges.push_back( ledge );
513 _normals.push_back( ledge->_normal );
515 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
516 void SetShapes( const TopoDS_Edge& edge,
517 const _ConvexFace& convFace,
518 const _SolidData& data,
519 SMESH_MesherHelper& helper);
521 //--------------------------------------------------------------------------------
523 * \brief Data of node on a shrinked FACE
527 const SMDS_MeshNode* _node;
528 vector<_Simplex> _simplices; // for quality check
530 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
532 bool Smooth(int& badNb,
533 Handle(Geom_Surface)& surface,
534 SMESH_MesherHelper& helper,
535 const double refSign,
539 gp_XY computeAngularPos(vector<gp_XY>& uv,
540 const gp_XY& uvToFix,
541 const double refSign );
543 //--------------------------------------------------------------------------------
545 * \brief Builder of viscous layers
547 class _ViscousBuilder
552 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
553 const TopoDS_Shape& shape);
555 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
556 void RestoreListeners();
558 // computes SMESH_ProxyMesh::SubMesh::_n2n;
559 bool MakeN2NMap( _MeshOfSolid* pm );
563 bool findSolidsWithLayers();
564 bool findFacesWithLayers();
565 bool makeLayer(_SolidData& data);
566 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
567 SMESH_MesherHelper& helper, _SolidData& data);
568 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
569 const TopoDS_Face& face,
570 SMESH_MesherHelper& helper,
572 bool shiftInside=false);
573 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
574 std::pair< TGeomID, gp_XYZ > fId2Normal[],
576 bool findNeiborsOnEdge(const _LayerEdge* edge,
577 const SMDS_MeshNode*& n1,
578 const SMDS_MeshNode*& n2,
580 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
581 const set<TGeomID>& ingnoreShapes,
582 const _SolidData* dataToCheckOri = 0,
583 const bool toSort = false);
584 void findSimplexTestEdges( _SolidData& data,
585 vector< vector<_LayerEdge*> >& edgesByGeom);
586 bool sortEdges( _SolidData& data,
587 vector< vector<_LayerEdge*> >& edgesByGeom);
588 void limitStepSizeByCurvature( _SolidData& data );
589 void limitStepSize( _SolidData& data,
590 const SMDS_MeshElement* face,
592 void limitStepSize( _SolidData& data, const double minSize);
593 bool inflate(_SolidData& data);
594 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
595 bool smoothAnalyticEdge( _SolidData& data,
598 Handle(Geom_Surface)& surface,
599 const TopoDS_Face& F,
600 SMESH_MesherHelper& helper);
601 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
602 bool updateNormalsOfConvexFaces( _SolidData& data,
603 SMESH_MesherHelper& helper,
605 bool refine(_SolidData& data);
607 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
608 SMESH_MesherHelper& helper,
609 const SMESHDS_SubMesh* faceSubMesh );
610 void fixBadFaces(const TopoDS_Face& F,
611 SMESH_MesherHelper& helper,
614 set<const SMDS_MeshNode*> * involvedNodes=NULL);
615 bool addBoundaryElements();
617 bool error( const string& text, int solidID=-1 );
618 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
621 void makeGroupOfLE();
624 SMESH_ComputeErrorPtr _error;
626 vector< _SolidData > _sdVec;
629 //--------------------------------------------------------------------------------
631 * \brief Shrinker of nodes on the EDGE
635 vector<double> _initU;
636 vector<double> _normPar;
637 vector<const SMDS_MeshNode*> _nodes;
638 const _LayerEdge* _edges[2];
641 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
642 void Compute(bool set3D, SMESH_MesherHelper& helper);
643 void RestoreParams();
644 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
646 //--------------------------------------------------------------------------------
648 * \brief Class of temporary mesh face.
649 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
650 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
652 struct _TmpMeshFace : public SMDS_MeshElement
654 vector<const SMDS_MeshNode* > _nn;
655 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
656 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
657 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
658 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
659 virtual vtkIdType GetVtkType() const { return -1; }
660 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
661 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
662 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
663 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
665 //--------------------------------------------------------------------------------
667 * \brief Class of temporary mesh face storing _LayerEdge it's based on
669 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
671 _LayerEdge *_le1, *_le2;
672 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
673 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
675 _nn[0]=_le1->_nodes[0];
676 _nn[1]=_le1->_nodes.back();
677 _nn[2]=_le2->_nodes.back();
678 _nn[3]=_le2->_nodes[0];
681 //--------------------------------------------------------------------------------
683 * \brief Retriever of node coordinates either directly of from a surface by node UV.
684 * \warning Location of a surface is ignored
686 struct _NodeCoordHelper
688 SMESH_MesherHelper& _helper;
689 const TopoDS_Face& _face;
690 Handle(Geom_Surface) _surface;
691 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
693 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
694 : _helper( helper ), _face( F )
699 _surface = BRep_Tool::Surface( _face, loc );
701 if ( _surface.IsNull() )
702 _fun = & _NodeCoordHelper::direct;
704 _fun = & _NodeCoordHelper::byUV;
706 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
709 gp_XYZ direct(const SMDS_MeshNode* n) const
711 return SMESH_TNodeXYZ( n );
713 gp_XYZ byUV (const SMDS_MeshNode* n) const
715 gp_XY uv = _helper.GetNodeUV( _face, n );
716 return _surface->Value( uv.X(), uv.Y() ).XYZ();
719 } // namespace VISCOUS_3D
723 //================================================================================
724 // StdMeshers_ViscousLayers hypothesis
726 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
727 :SMESH_Hypothesis(hypId, studyId, gen),
728 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
730 _name = StdMeshers_ViscousLayers::GetHypType();
731 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
732 } // --------------------------------------------------------------------------------
733 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
735 if ( faceIds != _shapeIds )
736 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
737 if ( _isToIgnoreShapes != toIgnore )
738 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
739 } // --------------------------------------------------------------------------------
740 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
742 if ( thickness != _thickness )
743 _thickness = thickness, NotifySubMeshesHypothesisModification();
744 } // --------------------------------------------------------------------------------
745 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
747 if ( _nbLayers != nb )
748 _nbLayers = nb, NotifySubMeshesHypothesisModification();
749 } // --------------------------------------------------------------------------------
750 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
752 if ( _stretchFactor != factor )
753 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
754 } // --------------------------------------------------------------------------------
756 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
757 const TopoDS_Shape& theShape,
758 const bool toMakeN2NMap) const
760 using namespace VISCOUS_3D;
761 _ViscousBuilder bulder;
762 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
763 if ( err && !err->IsOK() )
764 return SMESH_ProxyMesh::Ptr();
766 vector<SMESH_ProxyMesh::Ptr> components;
767 TopExp_Explorer exp( theShape, TopAbs_SOLID );
768 for ( ; exp.More(); exp.Next() )
770 if ( _MeshOfSolid* pm =
771 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
773 if ( toMakeN2NMap && !pm->_n2nMapComputed )
774 if ( !bulder.MakeN2NMap( pm ))
775 return SMESH_ProxyMesh::Ptr();
776 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
777 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
779 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
781 switch ( components.size() )
785 case 1: return components[0];
787 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
789 return SMESH_ProxyMesh::Ptr();
790 } // --------------------------------------------------------------------------------
791 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
793 save << " " << _nbLayers
795 << " " << _stretchFactor
796 << " " << _shapeIds.size();
797 for ( size_t i = 0; i < _shapeIds.size(); ++i )
798 save << " " << _shapeIds[i];
799 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
801 } // --------------------------------------------------------------------------------
802 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
804 int nbFaces, faceID, shapeToTreat;
805 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
806 while ( _shapeIds.size() < nbFaces && load >> faceID )
807 _shapeIds.push_back( faceID );
808 if ( load >> shapeToTreat )
809 _isToIgnoreShapes = !shapeToTreat;
811 _isToIgnoreShapes = true; // old behavior
813 } // --------------------------------------------------------------------------------
814 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
815 const TopoDS_Shape& theShape)
820 // END StdMeshers_ViscousLayers hypothesis
821 //================================================================================
825 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
829 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
830 gp_Pnt p = BRep_Tool::Pnt( fromV );
831 double distF = p.SquareDistance( c->Value( f ));
832 double distL = p.SquareDistance( c->Value( l ));
833 c->D1(( distF < distL ? f : l), p, dir );
834 if ( distL < distF ) dir.Reverse();
837 //--------------------------------------------------------------------------------
838 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
839 SMESH_MesherHelper& helper)
842 double f,l; gp_Pnt p;
843 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
844 double u = helper.GetNodeU( E, atNode );
848 //--------------------------------------------------------------------------------
849 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
850 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
852 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
853 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
854 gp_Pnt p; gp_Vec du, dv, norm;
855 surface->D1( uv.X(),uv.Y(), p, du,dv );
859 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
860 double u = helper.GetNodeU( fromE, node, 0, &ok );
862 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
863 if ( o == TopAbs_REVERSED )
866 gp_Vec dir = norm ^ du;
868 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
869 helper.IsClosedEdge( fromE ))
871 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
872 else c->D1( f, p, dv );
873 if ( o == TopAbs_REVERSED )
875 gp_Vec dir2 = norm ^ dv;
876 dir = dir.Normalized() + dir2.Normalized();
880 //--------------------------------------------------------------------------------
881 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
882 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
883 bool& ok, double* cosin=0)
885 TopoDS_Face faceFrw = F;
886 faceFrw.Orientation( TopAbs_FORWARD );
887 double f,l; TopLoc_Location loc;
888 TopoDS_Edge edges[2]; // sharing a vertex
892 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
893 for ( ; exp.More() && nbEdges < 2; exp.Next() )
895 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
896 if ( SMESH_Algo::isDegenerated( e )) continue;
897 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
898 if ( VV[1].IsSame( fromV )) {
902 else if ( VV[0].IsSame( fromV )) {
908 gp_XYZ dir(0,0,0), edgeDir[2];
911 // get dirs of edges going fromV
913 for ( size_t i = 0; i < nbEdges && ok; ++i )
915 edgeDir[i] = getEdgeDir( edges[i], fromV );
916 double size2 = edgeDir[i].SquareModulus();
917 if (( ok = size2 > numeric_limits<double>::min() ))
918 edgeDir[i] /= sqrt( size2 );
920 if ( !ok ) return dir;
922 // get angle between the 2 edges
924 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, &faceNormal );
925 if ( Abs( angle ) < 5 * M_PI/180 )
927 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
931 dir = edgeDir[0] + edgeDir[1];
936 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
937 *cosin = Cos( angle );
940 else if ( nbEdges == 1 )
942 dir = getFaceDir( faceFrw, edges[0], node, helper, ok );
943 if ( cosin ) *cosin = 1.;
952 //================================================================================
954 * \brief Returns true if a FACE is bound by a concave EDGE
956 //================================================================================
958 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
960 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
964 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
965 for ( ; eExp.More(); eExp.Next() )
967 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
968 if ( SMESH_Algo::isDegenerated( E )) continue;
969 // check if 2D curve is concave
970 BRepAdaptor_Curve2d curve( E, F );
971 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
972 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
973 curve.Intervals( intervals, GeomAbs_C2 );
974 bool isConvex = true;
975 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
977 double u1 = intervals( i );
978 double u2 = intervals( i+1 );
979 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
980 double cross = drv2 ^ drv1;
981 if ( E.Orientation() == TopAbs_REVERSED )
983 isConvex = ( cross > 0.1 ); //-1e-9 );
987 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
991 // check angles at VERTEXes
993 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
994 for ( size_t iW = 0; iW < wires.size(); ++iW )
996 const int nbEdges = wires[iW]->NbEdges();
997 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
999 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1001 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1002 int iE2 = ( iE1 + 1 ) % nbEdges;
1003 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1004 iE2 = ( iE2 + 1 ) % nbEdges;
1005 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1006 wires[iW]->Edge( iE2 ), F );
1007 if ( angle < -5. * M_PI / 180. )
1013 //--------------------------------------------------------------------------------
1014 // DEBUG. Dump intermediate node positions into a python script
1019 const char* fname = "/tmp/viscous.py";
1020 cout << "execfile('"<<fname<<"')"<<endl;
1021 py = new ofstream(fname);
1022 *py << "import SMESH" << endl
1023 << "from salome.smesh import smeshBuilder" << endl
1024 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1025 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
1026 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1030 *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
1033 ~PyDump() { Finish(); }
1035 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1036 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1037 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1038 void _dumpFunction(const string& fun, int ln)
1039 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
1040 void _dumpMove(const SMDS_MeshNode* n, int ln)
1041 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1042 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
1043 void _dumpCmd(const string& txt, int ln)
1044 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1045 void dumpFunctionEnd()
1046 { if (py) *py<< " return"<< endl; }
1047 void dumpChangeNodes( const SMDS_MeshElement* f )
1048 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1049 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1050 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1051 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1053 struct PyDump { void Finish() {} };
1054 #define dumpFunction(f) f
1056 #define dumpCmd(txt)
1057 #define dumpFunctionEnd()
1058 #define dumpChangeNodes(f)
1059 #define debugMsg( txt ) {}
1063 using namespace VISCOUS_3D;
1065 //================================================================================
1067 * \brief Constructor of _ViscousBuilder
1069 //================================================================================
1071 _ViscousBuilder::_ViscousBuilder()
1073 _error = SMESH_ComputeError::New(COMPERR_OK);
1077 //================================================================================
1079 * \brief Stores error description and returns false
1081 //================================================================================
1083 bool _ViscousBuilder::error(const string& text, int solidId )
1085 _error->myName = COMPERR_ALGO_FAILED;
1086 _error->myComment = string("Viscous layers builder: ") + text;
1089 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1090 if ( !sm && !_sdVec.empty() )
1091 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1092 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1094 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1095 if ( smError && smError->myAlgo )
1096 _error->myAlgo = smError->myAlgo;
1100 makeGroupOfLE(); // debug
1105 //================================================================================
1107 * \brief At study restoration, restore event listeners used to clear an inferior
1108 * dim sub-mesh modified by viscous layers
1110 //================================================================================
1112 void _ViscousBuilder::RestoreListeners()
1117 //================================================================================
1119 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1121 //================================================================================
1123 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1125 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1126 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1127 for ( ; fExp.More(); fExp.Next() )
1129 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1130 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1132 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1134 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1137 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1138 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1140 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1141 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1142 while( prxIt->more() )
1144 const SMDS_MeshElement* fSrc = srcIt->next();
1145 const SMDS_MeshElement* fPrx = prxIt->next();
1146 if ( fSrc->NbNodes() != fPrx->NbNodes())
1147 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1148 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1149 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1152 pm->_n2nMapComputed = true;
1156 //================================================================================
1158 * \brief Does its job
1160 //================================================================================
1162 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1163 const TopoDS_Shape& theShape)
1165 // TODO: set priority of solids during Gen::Compute()
1169 // check if proxy mesh already computed
1170 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1172 return error("No SOLID's in theShape"), _error;
1174 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1175 return SMESH_ComputeErrorPtr(); // everything already computed
1179 // TODO: ignore already computed SOLIDs
1180 if ( !findSolidsWithLayers())
1183 if ( !findFacesWithLayers() )
1186 for ( size_t i = 0; i < _sdVec.size(); ++i )
1188 if ( ! makeLayer(_sdVec[i]) )
1191 if ( _sdVec[i]._edges.size() == 0 )
1194 if ( ! inflate(_sdVec[i]) )
1197 if ( ! refine(_sdVec[i]) )
1203 addBoundaryElements();
1205 makeGroupOfLE(); // debug
1211 //================================================================================
1213 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1215 //================================================================================
1217 bool _ViscousBuilder::findSolidsWithLayers()
1220 TopTools_IndexedMapOfShape allSolids;
1221 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1222 _sdVec.reserve( allSolids.Extent());
1224 SMESH_Gen* gen = _mesh->GetGen();
1225 SMESH_HypoFilter filter;
1226 for ( int i = 1; i <= allSolids.Extent(); ++i )
1228 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1229 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1230 if ( !algo ) continue;
1231 // TODO: check if algo is hidden
1232 const list <const SMESHDS_Hypothesis *> & allHyps =
1233 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1234 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1235 const StdMeshers_ViscousLayers* viscHyp = 0;
1236 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1237 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1240 TopoDS_Shape hypShape;
1241 filter.Init( filter.Is( viscHyp ));
1242 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1244 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1247 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1248 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1251 if ( _sdVec.empty() )
1253 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1258 //================================================================================
1262 //================================================================================
1264 bool _ViscousBuilder::findFacesWithLayers()
1266 SMESH_MesherHelper helper( *_mesh );
1267 TopExp_Explorer exp;
1268 TopTools_IndexedMapOfShape solids;
1270 // collect all faces to ignore defined by hyp
1271 for ( size_t i = 0; i < _sdVec.size(); ++i )
1273 solids.Add( _sdVec[i]._solid );
1275 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1276 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1278 for ( size_t ii = 0; ii < ids.size(); ++ii )
1280 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1281 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1282 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1285 else // FACEs with layers are given
1287 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1288 for ( ; exp.More(); exp.Next() )
1290 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1291 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1292 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1296 // ignore internal FACEs if inlets and outlets are specified
1298 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1299 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1300 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1301 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1303 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1304 for ( ; exp.More(); exp.Next() )
1306 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1307 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1310 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1311 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1313 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1315 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1318 if ( helper.IsReversedSubMesh( face ))
1320 _sdVec[i]._reversedFaceIds.insert( faceInd );
1326 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1327 TopTools_IndexedMapOfShape shapes;
1328 for ( size_t i = 0; i < _sdVec.size(); ++i )
1331 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1332 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1334 const TopoDS_Shape& edge = shapes(iE);
1335 // find 2 faces sharing an edge
1337 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1338 while ( fIt->more())
1340 const TopoDS_Shape* f = fIt->next();
1341 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1342 FF[ int( !FF[0].IsNull()) ] = *f;
1344 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1345 // check presence of layers on them
1347 for ( int j = 0; j < 2; ++j )
1348 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1349 if ( ignore[0] == ignore[1] )
1350 continue; // nothing interesting
1351 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1352 // check presence of layers on fWOL within an adjacent SOLID
1353 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1354 while ( const TopoDS_Shape* solid = sIt->next() )
1355 if ( !solid->IsSame( _sdVec[i]._solid ))
1357 int iSolid = solids.FindIndex( *solid );
1358 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1359 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1361 _sdVec[i]._noShrinkFaces.insert( iFace );
1366 if ( !fWOL.IsNull())
1368 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1369 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1373 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1374 // the algo of the SOLID sharing the FACE does not support it
1375 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1376 for ( size_t i = 0; i < _sdVec.size(); ++i )
1378 TopTools_MapOfShape noShrinkVertices;
1379 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1380 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1382 const TopoDS_Shape& fWOL = e2f->second;
1383 TGeomID edgeID = e2f->first;
1384 bool notShrinkFace = false;
1385 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1386 while ( soIt->more())
1388 const TopoDS_Shape* solid = soIt->next();
1389 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1390 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1391 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1392 notShrinkFace = true;
1393 for ( size_t j = 0; j < _sdVec.size(); ++j )
1395 if ( _sdVec[j]._solid.IsSame( *solid ) )
1396 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1397 notShrinkFace = false;
1400 if ( notShrinkFace )
1402 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1403 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1404 noShrinkVertices.Add( vExp.Current() );
1407 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1408 // to the found not shrinked fWOL's
1409 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1410 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1412 TGeomID edgeID = e2f->first;
1413 TopoDS_Vertex VV[2];
1414 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1415 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1417 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1418 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1427 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1429 for ( size_t i = 0; i < _sdVec.size(); ++i )
1432 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1433 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1435 const TopoDS_Shape& vertex = shapes(iV);
1436 // find faces WOL sharing the vertex
1437 vector< TopoDS_Shape > facesWOL;
1438 int totalNbFaces = 0;
1439 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1440 while ( fIt->more())
1442 const TopoDS_Shape* f = fIt->next();
1443 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1446 const int fID = getMeshDS()->ShapeToIndex( *f );
1447 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1448 !_sdVec[i]._noShrinkFaces.count( fID ))
1449 facesWOL.push_back( *f );
1452 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1453 continue; // no layers at this vertex or no WOL
1454 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1455 switch ( facesWOL.size() )
1459 helper.SetSubShape( facesWOL[0] );
1460 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1462 TopoDS_Shape seamEdge;
1463 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1464 while ( eIt->more() && seamEdge.IsNull() )
1466 const TopoDS_Shape* e = eIt->next();
1467 if ( helper.IsRealSeam( *e ) )
1470 if ( !seamEdge.IsNull() )
1472 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1476 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1481 // find an edge shared by 2 faces
1482 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1483 while ( eIt->more())
1485 const TopoDS_Shape* e = eIt->next();
1486 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1487 helper.IsSubShape( *e, facesWOL[1]))
1489 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1495 return error("Not yet supported case", _sdVec[i]._index);
1500 // add FACEs of other SOLIDs to _ignoreFaceIds
1501 for ( size_t i = 0; i < _sdVec.size(); ++i )
1504 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1506 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1508 if ( !shapes.Contains( exp.Current() ))
1509 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1516 //================================================================================
1518 * \brief Create the inner surface of the viscous layer and prepare data for infation
1520 //================================================================================
1522 bool _ViscousBuilder::makeLayer(_SolidData& data)
1524 // get all sub-shapes to make layers on
1525 set<TGeomID> subIds, faceIds;
1526 subIds = data._noShrinkFaces;
1527 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1528 for ( ; exp.More(); exp.Next() )
1530 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1531 if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1532 faceIds.insert( fSubM->GetId() );
1533 SMESH_subMeshIteratorPtr subIt =
1534 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1535 while ( subIt->more() )
1536 subIds.insert( subIt->next()->GetId() );
1539 // make a map to find new nodes on sub-shapes shared with other SOLID
1540 map< TGeomID, TNode2Edge* >::iterator s2ne;
1541 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1542 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1544 TGeomID shapeInd = s2s->first;
1545 for ( size_t i = 0; i < _sdVec.size(); ++i )
1547 if ( _sdVec[i]._index == data._index ) continue;
1548 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1549 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1550 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1552 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1558 // Create temporary faces and _LayerEdge's
1560 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1562 data._stepSize = Precision::Infinite();
1563 data._stepSizeNodes[0] = 0;
1565 SMESH_MesherHelper helper( *_mesh );
1566 helper.SetSubShape( data._solid );
1567 helper.SetElementsOnShape(true);
1569 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1570 TNode2Edge::iterator n2e2;
1572 // collect _LayerEdge's of shapes they are based on
1573 const int nbShapes = getMeshDS()->MaxShapeIndex();
1574 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1576 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1578 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1579 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1581 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1582 SMESH_ProxyMesh::SubMesh* proxySub =
1583 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1585 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1586 while ( eIt->more() )
1588 const SMDS_MeshElement* face = eIt->next();
1589 newNodes.resize( face->NbCornerNodes() );
1590 double faceMaxCosin = -1;
1591 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1593 const SMDS_MeshNode* n = face->GetNode(i);
1594 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1595 if ( !(*n2e).second )
1598 _LayerEdge* edge = new _LayerEdge();
1600 edge->_nodes.push_back( n );
1601 const int shapeID = n->getshapeId();
1602 edgesByGeom[ shapeID ].push_back( edge );
1604 SMESH_TNodeXYZ xyz( n );
1606 // set edge data or find already refined _LayerEdge and get data from it
1607 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1608 ( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() &&
1609 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1611 _LayerEdge* foundEdge = (*n2e2).second;
1612 gp_XYZ lastPos = edge->Copy( *foundEdge, helper );
1613 foundEdge->_pos.push_back( lastPos );
1614 // location of the last node is modified and we restore it by foundEdge->_pos.back()
1615 const_cast< SMDS_MeshNode* >
1616 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
1620 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
1621 if ( !setEdgeData( *edge, subIds, helper, data ))
1624 dumpMove(edge->_nodes.back());
1625 if ( edge->_cosin > 0.01 )
1627 if ( edge->_cosin > faceMaxCosin )
1628 faceMaxCosin = edge->_cosin;
1631 newNodes[ i ] = n2e->second->_nodes.back();
1633 // create a temporary face
1634 const SMDS_MeshElement* newFace =
1635 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
1636 proxySub->AddElement( newFace );
1638 // compute inflation step size by min size of element on a convex surface
1639 if ( faceMaxCosin > theMinSmoothCosin )
1640 limitStepSize( data, face, faceMaxCosin );
1641 } // loop on 2D elements on a FACE
1642 } // loop on FACEs of a SOLID
1644 data._epsilon = 1e-7;
1645 if ( data._stepSize < 1. )
1646 data._epsilon *= data._stepSize;
1648 // Put _LayerEdge's into the vector data._edges
1649 if ( !sortEdges( data, edgesByGeom ))
1652 // limit data._stepSize depending on surface curvature and fill data._convexFaces
1653 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
1655 // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1656 TNode2Edge::iterator n2e;
1657 for ( size_t i = 0; i < data._edges.size(); ++i )
1659 if ( data._edges[i]->IsOnEdge())
1660 for ( int j = 0; j < 2; ++j )
1662 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1663 break; // _LayerEdge is shared by two _SolidData's
1664 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1665 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1666 return error("_LayerEdge not found by src node", data._index);
1667 n = (*n2e).second->_nodes.back();
1668 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1671 for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1673 _Simplex& s = data._edges[i]->_simplices[j];
1674 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1675 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1683 //================================================================================
1685 * \brief Compute inflation step size by min size of element on a convex surface
1687 //================================================================================
1689 void _ViscousBuilder::limitStepSize( _SolidData& data,
1690 const SMDS_MeshElement* face,
1694 double minSize = 10 * data._stepSize;
1695 const int nbNodes = face->NbCornerNodes();
1696 for ( int i = 0; i < nbNodes; ++i )
1698 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1699 const SMDS_MeshNode* curN = face->GetNode( i );
1700 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1701 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1703 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1704 if ( dist < minSize )
1705 minSize = dist, iN = i;
1708 double newStep = 0.8 * minSize / cosin;
1709 if ( newStep < data._stepSize )
1711 data._stepSize = newStep;
1712 data._stepSizeCoeff = 0.8 / cosin;
1713 data._stepSizeNodes[0] = face->GetNode( iN );
1714 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1718 //================================================================================
1720 * \brief Compute inflation step size by min size of element on a convex surface
1722 //================================================================================
1724 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1726 if ( minSize < data._stepSize )
1728 data._stepSize = minSize;
1729 if ( data._stepSizeNodes[0] )
1732 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1733 data._stepSizeCoeff = data._stepSize / dist;
1738 //================================================================================
1740 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
1742 //================================================================================
1744 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
1746 const int nbTestPnt = 5; // on a FACE sub-shape
1747 const double minCurvature = 0.9 / data._hyp->GetTotalThickness();
1749 BRepLProp_SLProps surfProp( 2, 1e-6 );
1750 SMESH_MesherHelper helper( *_mesh );
1752 data._convexFaces.clear();
1754 TopExp_Explorer face( data._solid, TopAbs_FACE );
1755 for ( ; face.More(); face.Next() )
1757 const TopoDS_Face& F = TopoDS::Face( face.Current() );
1758 BRepAdaptor_Surface surface( F, false );
1759 surfProp.SetSurface( surface );
1761 bool isTooCurved = false;
1764 _ConvexFace cnvFace;
1765 SMESH_subMesh * sm = _mesh->GetSubMesh( F );
1766 const TGeomID faceID = sm->GetId();
1767 if ( data._ignoreFaceIds.count( faceID )) continue;
1768 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
1769 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1770 while ( smIt->more() )
1773 const TGeomID subID = sm->GetId();
1774 // find _LayerEdge's of a sub-shape
1776 if ( data.GetShapeEdges( subID, edgesEnd, &iBeg, &iEnd ))
1777 cnvFace._subIdToEdgeEnd.insert( make_pair( subID, edgesEnd ));
1780 // check concavity and curvature and limit data._stepSize
1781 int nbLEdges = iEnd - iBeg;
1782 int step = Max( 1, nbLEdges / nbTestPnt );
1783 for ( ; iBeg < iEnd; iBeg += step )
1785 gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
1786 surfProp.SetParameters( uv.X(), uv.Y() );
1787 if ( !surfProp.IsCurvatureDefined() )
1789 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
1791 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
1794 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
1796 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
1800 } // loop on sub-shapes of the FACE
1802 if ( !isTooCurved ) continue;
1804 _ConvexFace & convFace =
1805 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
1808 convFace._normalsFixed = false;
1810 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
1811 // prism distortion.
1812 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
1813 if ( id2end != convFace._subIdToEdgeEnd.end() )
1815 // there are _LayerEdge's on the FACE it-self;
1816 // select _LayerEdge's near EDGEs
1817 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
1818 for ( ; iBeg < iEnd; ++iBeg )
1820 _LayerEdge* ledge = data._edges[ iBeg ];
1821 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
1822 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
1824 convFace._simplexTestEdges.push_back( ledge );
1831 // where there are no _LayerEdge's on a _ConvexFace,
1832 // as e.g. on a fillet surface with no internal nodes - issue 22580,
1833 // so that collision of viscous internal faces is not detected by check of
1834 // intersection of _LayerEdge's with the viscous internal faces.
1836 set< const SMDS_MeshNode* > usedNodes;
1838 // look for _LayerEdge's with null _sWOL
1839 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
1840 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
1842 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
1843 if ( iBeg >= iEnd || !data._edges[ iBeg ]->_sWOL.IsNull() )
1845 for ( ; iBeg < iEnd; ++iBeg )
1847 _LayerEdge* ledge = data._edges[ iBeg ];
1848 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1849 if ( !usedNodes.insert( srcNode ).second ) continue;
1851 getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1852 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1854 usedNodes.insert( ledge->_simplices[i]._nPrev );
1855 usedNodes.insert( ledge->_simplices[i]._nNext );
1857 convFace._simplexTestEdges.push_back( ledge );
1861 } // loop on FACEs of data._solid
1864 //================================================================================
1866 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1868 //================================================================================
1870 bool _ViscousBuilder::sortEdges( _SolidData& data,
1871 vector< vector<_LayerEdge*> >& edgesByGeom)
1873 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1874 // boundry inclined at a sharp angle to the shape
1876 list< TGeomID > shapesToSmooth;
1878 SMESH_MesherHelper helper( *_mesh );
1881 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1883 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1884 if ( eS.empty() ) continue;
1885 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1886 bool needSmooth = false;
1887 switch ( S.ShapeType() )
1891 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1892 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1894 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1895 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1896 if ( eV.empty() ) continue;
1897 double cosin = eV[0]->_cosin;
1899 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1903 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1904 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1906 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1907 eV[0]->_nodes[0], helper, ok);
1908 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1909 double angle = dir1.Angle( dir2 );
1910 cosin = cos( angle );
1912 needSmooth = ( cosin > theMinSmoothCosin );
1918 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1920 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1921 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1922 if ( eE.empty() ) continue;
1923 if ( eE[0]->_sWOL.IsNull() )
1925 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1926 needSmooth = ( eE[i]->_cosin > theMinSmoothCosin );
1930 const TopoDS_Face& F1 = TopoDS::Face( S );
1931 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1932 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1933 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1935 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1936 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1937 double angle = dir1.Angle( dir2 );
1938 double cosin = cos( angle );
1939 needSmooth = ( cosin > theMinSmoothCosin );
1951 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1952 else shapesToSmooth.push_back ( iS );
1955 } // loop on edgesByGeom
1957 data._edges.reserve( data._n2eMap.size() );
1958 data._endEdgeOnShape.clear();
1960 // first we put _LayerEdge's on shapes to smooth
1961 data._nbShapesToSmooth = 0;
1962 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1963 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1965 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1966 if ( eVec.empty() ) continue;
1967 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1968 data._endEdgeOnShape.push_back( data._edges.size() );
1969 data._nbShapesToSmooth++;
1973 // then the rest _LayerEdge's
1974 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1976 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1977 if ( eVec.empty() ) continue;
1978 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1979 data._endEdgeOnShape.push_back( data._edges.size() );
1986 //================================================================================
1988 * \brief Set data of _LayerEdge needed for smoothing
1989 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1991 //================================================================================
1993 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1994 const set<TGeomID>& subIds,
1995 SMESH_MesherHelper& helper,
1998 SMESH_MeshEditor editor(_mesh);
2000 const SMDS_MeshNode* node = edge._nodes[0]; // source node
2001 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
2005 edge._curvature = 0;
2007 // --------------------------
2008 // Compute _normal and _cosin
2009 // --------------------------
2012 edge._normal.SetCoord(0,0,0);
2014 int totalNbFaces = 0;
2016 gp_Vec du, dv, geomNorm;
2019 TGeomID shapeInd = node->getshapeId();
2020 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
2021 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
2022 TopoDS_Shape vertEdge;
2024 if ( onShrinkShape ) // one of faces the node is on has no layers
2026 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
2027 if ( s2s->second.ShapeType() == TopAbs_EDGE )
2029 // inflate from VERTEX along EDGE
2030 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
2032 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
2034 // inflate from VERTEX along FACE
2035 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
2036 node, helper, normOK, &edge._cosin);
2040 // inflate from EDGE along FACE
2041 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
2042 node, helper, normOK);
2045 else // layers are on all faces of SOLID the node is on
2047 // find indices of geom faces the node lies on
2048 set<TGeomID> faceIds;
2049 if ( posType == SMDS_TOP_FACE )
2051 faceIds.insert( node->getshapeId() );
2055 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2056 while ( fIt->more() )
2057 faceIds.insert( editor.FindShape(fIt->next()));
2060 set<TGeomID>::iterator id = faceIds.begin();
2062 std::pair< TGeomID, gp_XYZ > id2Norm[20];
2063 for ( ; id != faceIds.end(); ++id )
2065 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2066 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2068 F = TopoDS::Face( s );
2069 geomNorm = getFaceNormal( node, F, helper, normOK );
2070 if ( !normOK ) continue;
2072 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2074 id2Norm[ totalNbFaces ].first = *id;
2075 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
2077 edge._normal += geomNorm.XYZ();
2079 if ( totalNbFaces == 0 )
2080 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2082 if ( normOK && edge._normal.Modulus() < 1e-3 && totalNbFaces > 1 )
2084 // opposite normals, re-get normals at shifted positions (IPAL 52426)
2085 edge._normal.SetCoord( 0,0,0 );
2086 for ( int i = 0; i < totalNbFaces; ++i )
2088 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[i].first ));
2089 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2090 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2093 id2Norm[ i ].second = geomNorm.XYZ();
2094 edge._normal += id2Norm[ i ].second;
2098 if ( totalNbFaces < 3 )
2100 //edge._normal /= totalNbFaces;
2104 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
2110 edge._cosin = 0; break;
2112 case SMDS_TOP_EDGE: {
2113 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
2114 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2115 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2116 edge._cosin = cos( angle );
2117 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2120 case SMDS_TOP_VERTEX: {
2121 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2122 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2123 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2124 edge._cosin = cos( angle );
2125 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2129 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2131 } // case _sWOL.IsNull()
2133 double normSize = edge._normal.SquareModulus();
2134 if ( normSize < numeric_limits<double>::min() )
2135 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2137 edge._normal /= sqrt( normSize );
2139 // TODO: if ( !normOK ) then get normal by mesh faces
2141 // Set the rest data
2142 // --------------------
2143 if ( onShrinkShape )
2145 edge._sWOL = (*s2s).second;
2147 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2148 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2149 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2151 // set initial position which is parameters on _sWOL in this case
2152 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2154 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2155 edge._pos.push_back( gp_XYZ( u, 0, 0));
2156 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2160 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2161 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2162 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2167 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2169 if ( posType == SMDS_TOP_FACE )
2171 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2172 double avgNormProj = 0, avgLen = 0;
2173 for ( size_t i = 0; i < edge._simplices.size(); ++i )
2175 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2176 avgNormProj += edge._normal * vec;
2177 avgLen += vec.Modulus();
2179 avgNormProj /= edge._simplices.size();
2180 avgLen /= edge._simplices.size();
2181 edge._curvature = _Curvature::New( avgNormProj, avgLen );
2185 // Set neighbour nodes for a _LayerEdge based on EDGE
2187 if ( posType == SMDS_TOP_EDGE /*||
2188 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2190 edge._2neibors = new _2NearEdges;
2191 // target node instead of source ones will be set later
2192 if ( ! findNeiborsOnEdge( &edge,
2193 edge._2neibors->_nodes[0],
2194 edge._2neibors->_nodes[1],
2197 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2198 edge._2neibors->_nodes[1],
2202 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2207 //================================================================================
2209 * \brief Return normal to a FACE at a node
2210 * \param [in] n - node
2211 * \param [in] face - FACE
2212 * \param [in] helper - helper
2213 * \param [out] isOK - true or false
2214 * \param [in] shiftInside - to find normal at a position shifted inside the face
2215 * \return gp_XYZ - normal
2217 //================================================================================
2219 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
2220 const TopoDS_Face& face,
2221 SMESH_MesherHelper& helper,
2228 // get a shifted position
2229 gp_Pnt p = SMESH_TNodeXYZ( node );
2230 gp_XYZ shift( 0,0,0 );
2231 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
2232 switch ( S.ShapeType() ) {
2235 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
2240 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
2248 p.Translate( shift * 1e-5 );
2250 TopLoc_Location loc;
2251 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
2253 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
2255 projector.Perform( p );
2256 if ( !projector.IsDone() || projector.NbPoints() < 1 )
2261 Quantity_Parameter U,V;
2262 projector.LowerDistanceParameters(U,V);
2267 uv = helper.GetNodeUV( face, node, 0, &isOK );
2273 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
2274 if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
2279 else // hard singularity
2281 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
2283 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2284 while ( fIt->more() )
2286 const SMDS_MeshElement* f = fIt->next();
2287 if ( f->getshapeId() == faceID )
2289 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
2292 if ( helper.IsReversedSubMesh( face ))
2299 return normal.XYZ();
2302 //================================================================================
2304 * \brief Return a normal at a node weighted with angles taken by FACEs
2305 * \param [in] n - the node
2306 * \param [in] fId2Normal - FACE ids and normals
2307 * \param [in] nbFaces - nb of FACEs meeting at the node
2308 * \return gp_XYZ - computed normal
2310 //================================================================================
2312 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
2313 std::pair< TGeomID, gp_XYZ > fId2Normal[],
2316 gp_XYZ resNorm(0,0,0);
2317 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2318 if ( V.ShapeType() != TopAbs_VERTEX )
2320 for ( int i = 0; i < nbFaces; ++i )
2321 resNorm += fId2Normal[i].second / nbFaces ;
2326 for ( int i = 0; i < nbFaces; ++i )
2328 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2330 // look for two EDGEs shared by F and other FACEs within fId2Normal
2333 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2334 while ( const TopoDS_Shape* E = eIt->next() )
2336 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2338 bool isSharedEdge = false;
2339 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2341 if ( i == j ) continue;
2342 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2343 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2345 if ( !isSharedEdge )
2347 ee[ nbE ] = TopoDS::Edge( *E );
2348 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2353 // get an angle between the two EDGEs
2355 if ( nbE < 1 ) continue;
2362 TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2363 TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2364 if ( !v10.IsSame( v01 ))
2365 std::swap( ee[0], ee[1] );
2367 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2370 // compute a weighted normal
2371 double sumAngle = 0;
2372 for ( int i = 0; i < nbFaces; ++i )
2374 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
2375 sumAngle += angles[i];
2377 for ( int i = 0; i < nbFaces; ++i )
2378 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2383 //================================================================================
2385 * \brief Find 2 neigbor nodes of a node on EDGE
2387 //================================================================================
2389 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
2390 const SMDS_MeshNode*& n1,
2391 const SMDS_MeshNode*& n2,
2394 const SMDS_MeshNode* node = edge->_nodes[0];
2395 const int shapeInd = node->getshapeId();
2396 SMESHDS_SubMesh* edgeSM = 0;
2397 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2400 edgeSM = getMeshDS()->MeshElements( shapeInd );
2401 if ( !edgeSM || edgeSM->NbElements() == 0 )
2402 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2406 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2407 while ( eIt->more() && !n2 )
2409 const SMDS_MeshElement* e = eIt->next();
2410 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
2411 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2414 if (!edgeSM->Contains(e)) continue;
2418 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2419 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2421 ( iN++ ? n2 : n1 ) = nNeibor;
2424 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2428 //================================================================================
2430 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2432 //================================================================================
2434 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2435 const SMDS_MeshNode* n2,
2436 SMESH_MesherHelper& helper)
2438 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2441 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2442 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2443 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2447 double sumLen = vec1.Modulus() + vec2.Modulus();
2448 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2449 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2450 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2451 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2452 if ( _curvature ) delete _curvature;
2453 _curvature = _Curvature::New( avgNormProj, avgLen );
2454 // if ( _curvature )
2455 // debugMsg( _nodes[0]->GetID()
2456 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2457 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2458 // << _curvature->lenDelta(0) );
2462 if ( _sWOL.IsNull() )
2464 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2465 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2466 gp_XYZ plnNorm = dirE ^ _normal;
2467 double proj0 = plnNorm * vec1;
2468 double proj1 = plnNorm * vec2;
2469 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2471 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2472 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2477 //================================================================================
2479 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2480 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2482 //================================================================================
2484 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2486 _nodes = other._nodes;
2487 _normal = other._normal;
2489 _lenFactor = other._lenFactor;
2490 _cosin = other._cosin;
2491 _sWOL = other._sWOL;
2492 _2neibors = other._2neibors;
2493 _curvature = 0; std::swap( _curvature, other._curvature );
2494 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2496 gp_XYZ lastPos( 0,0,0 );
2497 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2499 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2500 _pos.push_back( gp_XYZ( u, 0, 0));
2502 u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
2507 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2508 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2510 uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
2511 lastPos.SetX( uv.X() );
2512 lastPos.SetY( uv.Y() );
2517 //================================================================================
2519 * \brief Set _cosin and _lenFactor
2521 //================================================================================
2523 void _LayerEdge::SetCosin( double cosin )
2526 cosin = Abs( _cosin );
2527 _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ? 1./sqrt(1-cosin*cosin) : 1.0;
2530 //================================================================================
2532 * \brief Fills a vector<_Simplex >
2534 //================================================================================
2536 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2537 vector<_Simplex>& simplices,
2538 const set<TGeomID>& ingnoreShapes,
2539 const _SolidData* dataToCheckOri,
2543 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2544 while ( fIt->more() )
2546 const SMDS_MeshElement* f = fIt->next();
2547 const TGeomID shapeInd = f->getshapeId();
2548 if ( ingnoreShapes.count( shapeInd )) continue;
2549 const int nbNodes = f->NbCornerNodes();
2550 const int srcInd = f->GetNodeIndex( node );
2551 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2552 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2553 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2554 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2555 std::swap( nPrev, nNext );
2556 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2561 vector<_Simplex> sortedSimplices( simplices.size() );
2562 sortedSimplices[0] = simplices[0];
2564 for ( size_t i = 1; i < simplices.size(); ++i )
2566 for ( size_t j = 1; j < simplices.size(); ++j )
2567 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2569 sortedSimplices[i] = simplices[j];
2574 if ( nbFound == simplices.size() - 1 )
2575 simplices.swap( sortedSimplices );
2579 //================================================================================
2581 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2583 //================================================================================
2585 void _ViscousBuilder::makeGroupOfLE()
2588 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2590 if ( _sdVec[i]._edges.empty() ) continue;
2592 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2593 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2595 _LayerEdge* le = _sdVec[i]._edges[j];
2596 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2597 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2598 << ", " << le->_nodes[iN]->GetID() <<"])");
2602 dumpFunction( SMESH_Comment("makeNormals") << i );
2603 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2605 _LayerEdge& edge = *_sdVec[i]._edges[j];
2606 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2607 nXYZ += edge._normal * _sdVec[i]._stepSize;
2608 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2609 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2613 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2614 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2615 for ( ; fExp.More(); fExp.Next() )
2617 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2619 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2620 while ( fIt->more())
2622 const SMDS_MeshElement* e = fIt->next();
2623 SMESH_Comment cmd("mesh.AddFace([");
2624 for ( int j=0; j < e->NbCornerNodes(); ++j )
2625 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2635 //================================================================================
2637 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2639 //================================================================================
2641 bool _ViscousBuilder::inflate(_SolidData& data)
2643 SMESH_MesherHelper helper( *_mesh );
2645 // Limit inflation step size by geometry size found by itersecting
2646 // normals of _LayerEdge's with mesh faces
2647 double geomSize = Precision::Infinite(), intersecDist;
2648 auto_ptr<SMESH_ElementSearcher> searcher
2649 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2650 data._proxyMesh->GetFaces( data._solid )) );
2651 for ( size_t i = 0; i < data._edges.size(); ++i )
2653 if ( data._edges[i]->IsOnEdge() ) continue;
2654 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2655 if ( geomSize > intersecDist && intersecDist > 0 )
2656 geomSize = intersecDist;
2658 if ( data._stepSize > 0.3 * geomSize )
2659 limitStepSize( data, 0.3 * geomSize );
2661 const double tgtThick = data._hyp->GetTotalThickness();
2662 if ( data._stepSize > tgtThick )
2663 limitStepSize( data, tgtThick );
2665 if ( data._stepSize < 1. )
2666 data._epsilon = data._stepSize * 1e-7;
2668 debugMsg( "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize );
2670 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2671 int nbSteps = 0, nbRepeats = 0;
2672 while ( 1.01 * avgThick < tgtThick )
2674 // new target length
2675 curThick += data._stepSize;
2676 if ( curThick > tgtThick )
2678 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2682 // Elongate _LayerEdge's
2683 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2684 for ( size_t i = 0; i < data._edges.size(); ++i )
2686 data._edges[i]->SetNewLength( curThick, helper );
2690 if ( !updateNormals( data, helper, nbSteps ))
2693 // Improve and check quality
2694 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2698 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2699 for ( size_t i = 0; i < data._edges.size(); ++i )
2701 data._edges[i]->InvalidateStep( nbSteps+1 );
2705 break; // no more inflating possible
2709 // Evaluate achieved thickness
2711 for ( size_t i = 0; i < data._edges.size(); ++i )
2712 avgThick += data._edges[i]->_len;
2713 avgThick /= data._edges.size();
2714 debugMsg( "-- Thickness " << avgThick << " reached" );
2716 if ( distToIntersection < avgThick*1.5 )
2718 debugMsg( "-- Stop inflation since "
2719 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2720 << avgThick << " ) * 1.5" );
2724 limitStepSize( data, 0.25 * distToIntersection );
2725 if ( data._stepSizeNodes[0] )
2726 data._stepSize = data._stepSizeCoeff *
2727 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2729 } // while ( 1.01 * avgThick < tgtThick )
2732 return error("failed at the very first inflation step", data._index);
2734 if ( 1.01 * avgThick < tgtThick )
2735 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( data._index ))
2737 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2738 if ( !smError || smError->IsOK() )
2740 ( new SMESH_ComputeError (COMPERR_WARNING,
2741 SMESH_Comment("Thickness ") << tgtThick <<
2742 " of viscous layers not reached,"
2743 " average reached thickness is " << avgThick ));
2749 //================================================================================
2751 * \brief Improve quality of layer inner surface and check intersection
2753 //================================================================================
2755 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2757 double & distToIntersection)
2759 if ( data._nbShapesToSmooth == 0 )
2760 return true; // no shapes needing smoothing
2762 bool moved, improved;
2764 SMESH_MesherHelper helper(*_mesh);
2765 Handle(Geom_Surface) surface;
2769 for ( int iS = 0; iS < data._nbShapesToSmooth; ++iS )
2772 iEnd = data._endEdgeOnShape[ iS ];
2774 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2775 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2777 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2778 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2779 helper.SetSubShape( F );
2780 surface = BRep_Tool::Surface( F );
2785 F.Nullify(); surface.Nullify();
2787 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2789 if ( data._edges[ iBeg ]->IsOnEdge() )
2791 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2793 // try a simple solution on an analytic EDGE
2794 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2800 for ( int i = iBeg; i < iEnd; ++i )
2802 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2804 dumpCmd( SMESH_Comment("# end step ")<<step);
2806 while ( moved && step++ < 5 );
2813 int step = 0, stepLimit = 5, badNb = 0; moved = true;
2814 while (( ++step <= stepLimit && moved ) || improved )
2816 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2817 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2818 int oldBadNb = badNb;
2821 for ( int i = iBeg; i < iEnd; ++i )
2822 moved |= data._edges[i]->Smooth(badNb);
2823 improved = ( badNb < oldBadNb );
2825 // issue 22576. no bad faces but still there are intersections to fix
2826 if ( improved && badNb == 0 )
2827 stepLimit = step + 3;
2834 for ( int i = iBeg; i < iEnd; ++i )
2836 _LayerEdge* edge = data._edges[i];
2837 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2838 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2839 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2841 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2842 << " "<< edge->_simplices[j]._nPrev->GetID()
2843 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2851 } // loop on shapes to smooth
2853 // Check orientation of simplices of _ConvexFace::_simplexTestEdges
2854 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
2855 for ( ; id2face != data._convexFaces.end(); ++id2face )
2857 _ConvexFace & convFace = (*id2face).second;
2858 if ( !convFace._simplexTestEdges.empty() &&
2859 convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
2860 continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
2862 if ( !convFace.CheckPrisms() )
2866 // Check if the last segments of _LayerEdge intersects 2D elements;
2867 // checked elements are either temporary faces or faces on surfaces w/o the layers
2869 auto_ptr<SMESH_ElementSearcher> searcher
2870 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2871 data._proxyMesh->GetFaces( data._solid )) );
2873 distToIntersection = Precision::Infinite();
2875 const SMDS_MeshElement* intFace = 0;
2876 const SMDS_MeshElement* closestFace = 0;
2878 for ( size_t i = 0; i < data._edges.size(); ++i )
2880 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2882 if ( distToIntersection > dist )
2884 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
2885 // lying on this _ConvexFace
2886 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
2887 if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
2890 distToIntersection = dist;
2892 closestFace = intFace;
2898 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2899 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2900 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2901 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2902 << ") distance = " << distToIntersection<< endl;
2909 //================================================================================
2911 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2912 * _LayerEdge's to be in a consequent order
2914 //================================================================================
2916 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2919 Handle(Geom_Surface)& surface,
2920 const TopoDS_Face& F,
2921 SMESH_MesherHelper& helper)
2923 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2925 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2927 if ( i2curve == _edge2curve.end() )
2929 // sort _LayerEdge's by position on the EDGE
2930 SortOnEdge( E, iFrom, iTo, helper );
2932 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2934 TopLoc_Location loc; double f,l;
2936 Handle(Geom_Line) line;
2937 Handle(Geom_Circle) circle;
2938 bool isLine, isCirc;
2939 if ( F.IsNull() ) // 3D case
2941 // check if the EDGE is a line
2942 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2943 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2944 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2946 line = Handle(Geom_Line)::DownCast( curve );
2947 circle = Handle(Geom_Circle)::DownCast( curve );
2948 isLine = (!line.IsNull());
2949 isCirc = (!circle.IsNull());
2951 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2954 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2955 while ( nIt->more() )
2956 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2957 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2959 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2960 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2961 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2962 for ( int i = 0; i < 3 && !isLine; ++i )
2963 isLine = ( size.Coord( i+1 ) <= lineTol );
2965 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2972 // check if the EDGE is a line
2973 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2974 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2975 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2977 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2978 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2979 isLine = (!line2d.IsNull());
2980 isCirc = (!circle2d.IsNull());
2982 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2985 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2986 while ( nIt->more() )
2987 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2988 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2990 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2991 for ( int i = 0; i < 2 && !isLine; ++i )
2992 isLine = ( size.Coord( i+1 ) <= lineTol );
2994 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3000 line = new Geom_Line( gp::OX() ); // only type does matter
3004 gp_Pnt2d p = circle2d->Location();
3005 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
3006 circle = new Geom_Circle( ax, 1.); // only center position does matter
3010 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
3018 return i2curve->second;
3021 //================================================================================
3023 * \brief Sort _LayerEdge's by a parameter on a given EDGE
3025 //================================================================================
3027 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
3030 SMESH_MesherHelper& helper)
3032 map< double, _LayerEdge* > u2edge;
3033 for ( int i = iFrom; i < iTo; ++i )
3034 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
3036 ASSERT( u2edge.size() == iTo - iFrom );
3037 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
3038 for ( int i = iFrom; i < iTo; ++i, ++u2e )
3039 _edges[i] = u2e->second;
3041 // set _2neibors according to the new order
3042 for ( int i = iFrom; i < iTo-1; ++i )
3043 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
3044 _edges[i]->_2neibors->reverse();
3045 if ( u2edge.size() > 1 &&
3046 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
3047 _edges[iTo-1]->_2neibors->reverse();
3050 //================================================================================
3052 * \brief Return index corresponding to the shape in _endEdgeOnShape
3054 //================================================================================
3056 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
3061 int beg = 0, end = 0;
3062 for ( edgesEnd = 0; edgesEnd < _endEdgeOnShape.size(); ++edgesEnd )
3064 end = _endEdgeOnShape[ edgesEnd ];
3065 TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
3066 if ( sID == shapeID )
3068 if ( iBeg ) *iBeg = beg;
3069 if ( iEnd ) *iEnd = end;
3077 //================================================================================
3079 * \brief Add faces for smoothing
3081 //================================================================================
3083 void _SolidData::AddFacesToSmooth( const set< TGeomID >& faceIDs )
3085 // convert faceIDs to indices in _endEdgeOnShape
3086 set< size_t > iEnds;
3088 set< TGeomID >::const_iterator fId = faceIDs.begin();
3089 for ( ; fId != faceIDs.end(); ++fId )
3090 if ( GetShapeEdges( *fId, end ) && end >= _nbShapesToSmooth )
3091 iEnds.insert( end );
3093 set< size_t >::iterator endsIt = iEnds.begin();
3095 // "add" by move of _nbShapesToSmooth
3096 int nbFacesToAdd = faceIDs.size();
3097 while ( endsIt != iEnds.end() && *endsIt == _nbShapesToSmooth )
3100 ++_nbShapesToSmooth;
3103 if ( endsIt == iEnds.end() )
3106 // Move _LayerEdge's on FACEs just after _nbShapesToSmooth
3108 vector< _LayerEdge* > nonSmoothLE, smoothLE;
3109 size_t lastSmooth = *iEnds.rbegin();
3111 for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
3113 vector< _LayerEdge* > & edgesVec = iEnds.count(i) ? smoothLE : nonSmoothLE;
3114 iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
3115 iEnd = _endEdgeOnShape[ i ];
3116 edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd );
3119 iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
3120 std::copy( smoothLE.begin(), smoothLE.end(), &_edges[ iBeg ] );
3121 std::copy( nonSmoothLE.begin(), nonSmoothLE.end(), &_edges[ iBeg + smoothLE.size()]);
3123 // update _endEdgeOnShape
3124 for ( size_t i = _nbShapesToSmooth; i < _endEdgeOnShape.size(); ++i )
3126 TGeomID curShape = _edges[ iBeg ]->_nodes[0]->getshapeId();
3127 while ( ++iBeg < _edges.size() &&
3128 curShape == _edges[ iBeg ]->_nodes[0]->getshapeId() );
3130 _endEdgeOnShape[ i ] = iBeg;
3133 _nbShapesToSmooth += nbFacesToAdd;
3136 //================================================================================
3138 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
3140 //================================================================================
3142 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
3145 Handle(Geom_Surface)& surface,
3146 const TopoDS_Face& F,
3147 SMESH_MesherHelper& helper)
3149 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
3150 helper.GetMeshDS());
3151 TopoDS_Edge E = TopoDS::Edge( S );
3153 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
3154 if ( curve.IsNull() ) return false;
3156 // compute a relative length of segments
3157 vector< double > len( iTo-iFrom+1 );
3159 double curLen, prevLen = len[0] = 1.0;
3160 for ( int i = iFrom; i < iTo; ++i )
3162 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
3163 len[i-iFrom+1] = len[i-iFrom] + curLen;
3168 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
3170 if ( F.IsNull() ) // 3D
3172 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
3173 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
3174 for ( int i = iFrom; i < iTo; ++i )
3176 double r = len[i-iFrom] / len.back();
3177 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
3178 data._edges[i]->_pos.back() = newPos;
3179 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3180 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3181 dumpMove( tgtNode );
3186 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
3187 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
3188 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
3189 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
3191 int iPeriodic = helper.GetPeriodicIndex();
3192 if ( iPeriodic == 1 || iPeriodic == 2 )
3194 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
3195 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
3196 std::swap( uv0, uv1 );
3199 const gp_XY rangeUV = uv1 - uv0;
3200 for ( int i = iFrom; i < iTo; ++i )
3202 double r = len[i-iFrom] / len.back();
3203 gp_XY newUV = uv0 + r * rangeUV;
3204 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
3206 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
3207 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3208 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3209 dumpMove( tgtNode );
3211 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3212 pos->SetUParameter( newUV.X() );
3213 pos->SetVParameter( newUV.Y() );
3219 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
3221 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
3222 gp_Pnt center3D = circle->Location();
3224 if ( F.IsNull() ) // 3D
3226 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
3227 data._edges[iTo-1]->_2neibors->_nodes[1] )
3228 return true; // closed EDGE - nothing to do
3230 return false; // TODO ???
3234 const gp_XY center( center3D.X(), center3D.Y() );
3236 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
3237 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
3238 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
3239 gp_Vec2d vec0( center, uv0 );
3240 gp_Vec2d vecM( center, uvM );
3241 gp_Vec2d vec1( center, uv1 );
3242 double uLast = vec0.Angle( vec1 ); // -PI - +PI
3243 double uMidl = vec0.Angle( vecM );
3244 if ( uLast * uMidl <= 0. )
3245 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
3246 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
3248 gp_Ax2d axis( center, vec0 );
3249 gp_Circ2d circ( axis, radius );
3250 for ( int i = iFrom; i < iTo; ++i )
3252 double newU = uLast * len[i-iFrom] / len.back();
3253 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
3254 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
3256 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
3257 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3258 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3259 dumpMove( tgtNode );
3261 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3262 pos->SetUParameter( newUV.X() );
3263 pos->SetVParameter( newUV.Y() );
3272 //================================================================================
3274 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
3275 * _LayerEdge's on neighbor EDGE's
3277 //================================================================================
3279 bool _ViscousBuilder::updateNormals( _SolidData& data,
3280 SMESH_MesherHelper& helper,
3284 return updateNormalsOfConvexFaces( data, helper, stepNb );
3286 // make temporary quadrangles got by extrusion of
3287 // mesh edges along _LayerEdge._normal's
3289 vector< const SMDS_MeshElement* > tmpFaces;
3291 set< SMESH_TLink > extrudedLinks; // contains target nodes
3292 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
3294 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
3295 for ( size_t i = 0; i < data._edges.size(); ++i )
3297 _LayerEdge* edge = data._edges[i];
3298 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3299 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
3300 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
3302 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
3303 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
3304 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
3305 if ( !link_isnew.second )
3307 extrudedLinks.erase( link_isnew.first );
3308 continue; // already extruded and will no more encounter
3310 // a _LayerEdge containg tgt2
3311 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3313 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3314 tmpFaces.push_back( f );
3316 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3317 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3318 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3323 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3324 // Perform two loops on _LayerEdge on EDGE's:
3325 // 1) to find and fix intersection
3326 // 2) to check that no new intersection appears as result of 1)
3328 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3330 auto_ptr<SMESH_ElementSearcher> searcher
3331 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3333 // 1) Find intersections
3335 const SMDS_MeshElement* face;
3336 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3337 TLEdge2LEdgeSet edge2CloseEdge;
3339 const double eps = data._epsilon * data._epsilon;
3340 for ( size_t i = 0; i < data._edges.size(); ++i )
3342 _LayerEdge* edge = data._edges[i];
3343 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3344 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3346 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
3347 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3348 ee.insert( f->_le1 );
3349 ee.insert( f->_le2 );
3350 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
3351 edge2CloseEdge[ f->_le1 ].insert( edge );
3352 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
3353 edge2CloseEdge[ f->_le2 ].insert( edge );
3357 // Set _LayerEdge._normal
3359 if ( !edge2CloseEdge.empty() )
3361 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3363 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3364 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3366 _LayerEdge* edge1 = e2ee->first;
3367 _LayerEdge* edge2 = 0;
3368 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
3370 // find EDGEs the edges reside
3372 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3373 if ( S.ShapeType() != TopAbs_EDGE )
3374 continue; // TODO: find EDGE by VERTEX
3375 E1 = TopoDS::Edge( S );
3376 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3377 while ( E2.IsNull() && eIt != ee.end())
3379 _LayerEdge* e2 = *eIt++;
3380 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3381 if ( S.ShapeType() == TopAbs_EDGE )
3382 E2 = TopoDS::Edge( S ), edge2 = e2;
3384 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3386 // find 3 FACEs sharing 2 EDGEs
3388 TopoDS_Face FF1[2], FF2[2];
3389 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3390 while ( fIt->more() && FF1[1].IsNull())
3392 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3393 if ( helper.IsSubShape( *F, data._solid))
3394 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3396 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3397 while ( fIt->more() && FF2[1].IsNull())
3399 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3400 if ( helper.IsSubShape( *F, data._solid))
3401 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3403 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3404 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3405 std::swap( FF1[0], FF1[1] );
3406 if ( FF2[0].IsSame( FF1[0]) )
3407 std::swap( FF2[0], FF2[1] );
3408 if ( FF1[0].IsNull() || FF2[0].IsNull() )
3411 // get a new normal for edge1
3413 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3414 if ( edge1->_cosin < 0 )
3415 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3416 if ( edge2->_cosin < 0 )
3417 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3418 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3419 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3420 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3421 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3422 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3423 // newNorm.Normalize();
3425 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3426 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3427 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3428 newNorm.Normalize();
3430 edge1->_normal = newNorm.XYZ();
3432 // update data of edge1 depending on _normal
3433 const SMDS_MeshNode *n1, *n2;
3434 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3435 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3436 edge1->SetDataByNeighbors( n1, n2, helper );
3438 if ( edge1->_cosin < 0 )
3441 dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3442 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3443 edge1->SetCosin( cos( angle ));
3445 // limit data._stepSize
3446 if ( edge1->_cosin > theMinSmoothCosin )
3448 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3449 while ( fIt->more() )
3450 limitStepSize( data, fIt->next(), edge1->_cosin );
3452 // set new XYZ of target node
3453 edge1->InvalidateStep( 1 );
3455 edge1->SetNewLength( data._stepSize, helper );
3458 // Update normals and other dependent data of not intersecting _LayerEdge's
3459 // neighboring the intersecting ones
3461 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3463 _LayerEdge* edge1 = e2ee->first;
3464 if ( !edge1->_2neibors )
3466 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3468 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3469 if ( edge2CloseEdge.count ( neighbor ))
3470 continue; // j-th neighbor is also intersected
3471 _LayerEdge* prevEdge = edge1;
3472 const int nbSteps = 6;
3473 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3475 if ( !neighbor->_2neibors )
3476 break; // neighbor is on VERTEX
3478 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3479 if ( nextEdge == prevEdge )
3480 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3481 double r = double(step-1)/nbSteps;
3482 if ( !nextEdge->_2neibors )
3485 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3486 newNorm.Normalize();
3488 neighbor->_normal = newNorm;
3489 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3490 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3492 neighbor->InvalidateStep( 1 );
3494 neighbor->SetNewLength( data._stepSize, helper );
3496 // goto the next neighbor
3497 prevEdge = neighbor;
3498 neighbor = nextEdge;
3504 // 2) Check absence of intersections
3507 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3513 //================================================================================
3515 * \brief Modify normals of _LayerEdge's on _ConvexFace's
3517 //================================================================================
3519 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
3520 SMESH_MesherHelper& helper,
3523 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
3526 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3527 for ( ; id2face != data._convexFaces.end(); ++id2face )
3529 _ConvexFace & convFace = (*id2face).second;
3530 if ( convFace._normalsFixed )
3531 continue; // already fixed
3532 if ( convFace.CheckPrisms() )
3533 continue; // nothing to fix
3535 convFace._normalsFixed = true;
3537 BRepAdaptor_Surface surface ( convFace._face, false );
3538 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
3540 // check if the convex FACE is of spherical shape
3542 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
3547 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
3548 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3550 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3552 if ( meshDS->IndexToShape( id2end->first ).ShapeType() == TopAbs_VERTEX )
3554 _LayerEdge* ledge = data._edges[ iBeg ];
3555 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
3556 centersBox.Add( center );
3558 for ( ; iBeg < iEnd; ++iBeg )
3559 nodesBox.Add( SMESH_TNodeXYZ( data._edges[ iBeg ]->_nodes[0] ));
3561 if ( centersBox.IsVoid() )
3563 debugMsg( "Error: centersBox.IsVoid()" );
3566 const bool isSpherical =
3567 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
3569 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
3570 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
3574 // set _LayerEdge::_normal as average of all normals
3576 // WARNING: different density of nodes on EDGEs is not taken into account that
3577 // can lead to an improper new normal
3579 gp_XYZ avgNormal( 0,0,0 );
3581 id2end = convFace._subIdToEdgeEnd.begin();
3582 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3584 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3585 // set data of _CentralCurveOnEdge
3586 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
3587 if ( S.ShapeType() == TopAbs_EDGE )
3589 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
3590 ceCurve.SetShapes( TopoDS::Edge(S), convFace, data, helper );
3591 if ( !data._edges[ iBeg ]->_sWOL.IsNull() )
3592 ceCurve._adjFace.Nullify();
3594 ceCurve._ledges.insert( ceCurve._ledges.end(),
3595 &data._edges[ iBeg ], &data._edges[ iEnd ]);
3597 // summarize normals
3598 for ( ; iBeg < iEnd; ++iBeg )
3599 avgNormal += data._edges[ iBeg ]->_normal;
3601 avgNormal.Normalize();
3603 // compute new _LayerEdge::_cosin on EDGEs
3604 double avgCosin = 0;
3607 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3609 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
3610 if ( ceCurve._adjFace.IsNull() )
3612 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
3614 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
3615 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
3618 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
3619 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
3620 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
3626 avgCosin /= nbCosin;
3628 // set _LayerEdge::_normal = avgNormal
3629 id2end = convFace._subIdToEdgeEnd.begin();
3630 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3632 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3633 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
3634 if ( S.ShapeType() != TopAbs_EDGE )
3635 for ( int i = iBeg; i < iEnd; ++i )
3636 data._edges[ i ]->_cosin = avgCosin;
3638 for ( ; iBeg < iEnd; ++iBeg )
3639 data._edges[ iBeg ]->_normal = avgNormal;
3642 else // if ( isSpherical )
3644 // We suppose that centers of curvature at all points of the FACE
3645 // lie on some curve, let's call it "central curve". For all _LayerEdge's
3646 // having a common center of curvature we define the same new normal
3647 // as a sum of normals of _LayerEdge's on EDGEs among them.
3649 // get all centers of curvature for each EDGE
3651 helper.SetSubShape( convFace._face );
3652 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
3654 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
3655 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
3657 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
3659 // set adjacent FACE
3660 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
3662 // get _LayerEdge's of the EDGE
3663 TGeomID edgeID = meshDS->ShapeToIndex( edge );
3664 id2end = convFace._subIdToEdgeEnd.find( edgeID );
3665 if ( id2end == convFace._subIdToEdgeEnd.end() )
3667 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
3668 for ( int iV = 0; iV < 2; ++iV )
3670 TopoDS_Vertex v = helper.IthVertex( iV, edge );
3671 TGeomID vID = meshDS->ShapeToIndex( v );
3672 int end = convFace._subIdToEdgeEnd[ vID ];
3673 int iBeg = end > 0 ? data._endEdgeOnShape[ end-1 ] : 0;
3674 vertexLEdges[ iV ] = data._edges[ iBeg ];
3676 edgeLEdge = &vertexLEdges[0];
3677 edgeLEdgeEnd = edgeLEdge + 2;
3679 centerCurves[ iE ]._adjFace.Nullify();
3683 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3684 if ( id2end->second >= data._nbShapesToSmooth )
3685 data.SortOnEdge( edge, iBeg, iEnd, helper );
3686 edgeLEdge = &data._edges[ iBeg ];
3687 edgeLEdgeEnd = edgeLEdge + iEnd - iBeg;
3688 vertexLEdges[0] = data._edges[ iBeg ]->_2neibors->_edges[0];
3689 vertexLEdges[1] = data._edges[ iEnd-1 ]->_2neibors->_edges[1];
3691 if ( ! data._edges[ iBeg ]->_sWOL.IsNull() )
3692 centerCurves[ iE ]._adjFace.Nullify();
3695 // Get curvature centers
3699 if ( edgeLEdge[0]->IsOnEdge() &&
3700 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
3702 centerCurves[ iE ].Append( center, vertexLEdges[0] );
3703 centersBox.Add( center );
3705 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
3706 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
3707 { // EDGE or VERTEXes
3708 centerCurves[ iE ].Append( center, *edgeLEdge );
3709 centersBox.Add( center );
3711 if ( edgeLEdge[-1]->IsOnEdge() &&
3712 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
3714 centerCurves[ iE ].Append( center, vertexLEdges[1] );
3715 centersBox.Add( center );
3717 centerCurves[ iE ]._isDegenerated =
3718 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
3720 } // loop on EDGES of convFace._face to set up data of centerCurves
3722 // Compute new normals for _LayerEdge's on EDGEs
3724 double avgCosin = 0;
3727 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
3729 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
3730 if ( ceCurve._isDegenerated )
3732 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
3733 vector< gp_XYZ > & newNormals = ceCurve._normals;
3734 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
3737 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
3740 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
3742 if ( isOK && !ceCurve._adjFace.IsNull() )
3744 // compute new _LayerEdge::_cosin
3745 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
3746 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
3749 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
3750 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
3751 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
3757 // set new normals to _LayerEdge's of NOT degenerated central curves
3758 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3760 if ( centerCurves[ iE ]._isDegenerated )
3762 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
3763 centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
3765 // set new normals to _LayerEdge's of degenerated central curves
3766 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3768 if ( !centerCurves[ iE ]._isDegenerated ||
3769 centerCurves[ iE ]._ledges.size() < 3 )
3771 // new normal is an average of new normals at VERTEXes that
3772 // was computed on non-degenerated _CentralCurveOnEdge's
3773 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
3774 centerCurves[ iE ]._ledges.back ()->_normal );
3775 double sz = newNorm.Modulus();
3779 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
3780 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
3781 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
3783 centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
3784 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
3788 // Find new normals for _LayerEdge's based on FACE
3791 avgCosin /= nbCosin;
3792 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
3793 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
3794 if ( id2end != convFace._subIdToEdgeEnd.end() )
3798 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3799 for ( ; iBeg < iEnd; ++iBeg )
3801 _LayerEdge* ledge = data._edges[ iBeg ];
3802 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
3804 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
3806 iE = iE % centerCurves.size();
3807 if ( centerCurves[ iE ]._isDegenerated )
3809 newNorm.SetCoord( 0,0,0 );
3810 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
3812 ledge->_normal = newNorm;
3813 ledge->_cosin = avgCosin;
3820 } // not a quasi-spherical FACE
3822 // Update _LayerEdge's data according to a new normal
3824 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
3825 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
3827 id2end = convFace._subIdToEdgeEnd.begin();
3828 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3830 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3831 for ( ; iBeg < iEnd; ++iBeg )
3833 _LayerEdge* & ledge = data._edges[ iBeg ];
3834 double len = ledge->_len;
3835 ledge->InvalidateStep( stepNb + 1, /*restoreLength=*/true );
3836 ledge->SetCosin( ledge->_cosin );
3837 ledge->SetNewLength( len, helper );
3840 } // loop on sub-shapes of convFace._face
3842 // Find FACEs adjacent to convFace._face that got necessity to smooth
3843 // as a result of normals modification
3845 set< TGeomID > adjFacesToSmooth;
3846 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3848 if ( centerCurves[ iE ]._adjFace.IsNull() ||
3849 centerCurves[ iE ]._adjFaceToSmooth )
3851 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
3853 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
3855 adjFacesToSmooth.insert( meshDS->ShapeToIndex( centerCurves[ iE ]._adjFace ));
3860 data.AddFacesToSmooth( adjFacesToSmooth );
3865 } // loop on data._convexFaces
3870 //================================================================================
3872 * \brief Finds a center of curvature of a surface at a _LayerEdge
3874 //================================================================================
3876 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
3877 BRepLProp_SLProps& surfProp,
3878 SMESH_MesherHelper& helper,
3879 gp_Pnt & center ) const
3881 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
3882 surfProp.SetParameters( uv.X(), uv.Y() );
3883 if ( !surfProp.IsCurvatureDefined() )
3886 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
3887 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
3888 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
3889 if ( surfCurvatureMin > surfCurvatureMax )
3890 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
3892 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
3897 //================================================================================
3899 * \brief Check that prisms are not distorted
3901 //================================================================================
3903 bool _ConvexFace::CheckPrisms() const
3905 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
3907 const _LayerEdge* edge = _simplexTestEdges[i];
3908 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3909 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3910 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
3912 debugMsg( "Bad simplex of _simplexTestEdges ("
3913 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3914 << " "<< edge->_simplices[j]._nPrev->GetID()
3915 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
3922 //================================================================================
3924 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
3925 * stored in this _CentralCurveOnEdge.
3926 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
3927 * \param [in,out] newNormal - current normal at this point, to be redefined
3928 * \return bool - true if succeeded.
3930 //================================================================================
3932 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
3934 if ( this->_isDegenerated )
3937 // find two centers the given one lies between
3939 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
3941 double sl2 = 1.001 * _segLength2[ i ];
3943 double d1 = center.SquareDistance( _curvaCenters[ i ]);
3947 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
3948 if ( d2 > sl2 || d2 + d1 < 1e-100 )
3953 double r = d1 / ( d1 + d2 );
3954 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
3955 ( r ) * _ledges[ i+1 ]->_normal );
3959 double sz = newNormal.Modulus();
3960 if ( Abs ( sz ) < 1e-200 )
3968 //================================================================================
3970 * \brief Set shape members
3972 //================================================================================
3974 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
3975 const _ConvexFace& convFace,
3976 const _SolidData& data,
3977 SMESH_MesherHelper& helper)
3981 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
3982 while ( const TopoDS_Shape* F = fIt->next())
3983 if ( !convFace._face.IsSame( *F ))
3985 _adjFace = TopoDS::Face( *F );
3986 _adjFaceToSmooth = false;
3987 // _adjFace already in a smoothing queue ?
3989 TGeomID adjFaceID = helper.GetMeshDS()->ShapeToIndex( *F );
3990 if ( data.GetShapeEdges( adjFaceID, end ))
3991 _adjFaceToSmooth = ( end < data._nbShapesToSmooth );
3996 //================================================================================
3998 * \brief Looks for intersection of it's last segment with faces
3999 * \param distance - returns shortest distance from the last node to intersection
4001 //================================================================================
4003 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
4005 const double& epsilon,
4006 const SMDS_MeshElement** face)
4008 vector< const SMDS_MeshElement* > suspectFaces;
4010 gp_Ax1 lastSegment = LastSegment(segLen);
4011 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
4013 bool segmentIntersected = false;
4014 distance = Precision::Infinite();
4015 int iFace = -1; // intersected face
4016 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
4018 const SMDS_MeshElement* face = suspectFaces[j];
4019 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
4020 face->GetNodeIndex( _nodes[0] ) >= 0 )
4021 continue; // face sharing _LayerEdge node
4022 const int nbNodes = face->NbCornerNodes();
4023 bool intFound = false;
4025 SMDS_MeshElement::iterator nIt = face->begin_nodes();
4028 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
4032 const SMDS_MeshNode* tria[3];
4035 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
4038 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
4044 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
4045 segmentIntersected = true;
4046 if ( distance > dist )
4047 distance = dist, iFace = j;
4050 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
4052 if ( segmentIntersected )
4055 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
4056 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
4057 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
4058 << ", intersection with face ("
4059 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4060 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
4061 << ") distance = " << distance - segLen<< endl;
4067 return segmentIntersected;
4070 //================================================================================
4072 * \brief Returns size and direction of the last segment
4074 //================================================================================
4076 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
4078 // find two non-coincident positions
4079 gp_XYZ orig = _pos.back();
4081 int iPrev = _pos.size() - 2;
4082 while ( iPrev >= 0 )
4084 dir = orig - _pos[iPrev];
4085 if ( dir.SquareModulus() > 1e-100 )
4095 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
4096 segDir.SetDirection( _normal );
4101 gp_Pnt pPrev = _pos[ iPrev ];
4102 if ( !_sWOL.IsNull() )
4104 TopLoc_Location loc;
4105 if ( _sWOL.ShapeType() == TopAbs_EDGE )
4108 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
4109 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
4113 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
4114 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
4116 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
4118 segDir.SetLocation( pPrev );
4119 segDir.SetDirection( dir );
4120 segLen = dir.Modulus();
4126 //================================================================================
4128 * \brief Test intersection of the last segment with a given triangle
4129 * using Moller-Trumbore algorithm
4130 * Intersection is detected if distance to intersection is less than _LayerEdge._len
4132 //================================================================================
4134 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
4135 const SMDS_MeshNode* n0,
4136 const SMDS_MeshNode* n1,
4137 const SMDS_MeshNode* n2,
4139 const double& EPSILON) const
4141 //const double EPSILON = 1e-6;
4143 gp_XYZ orig = lastSegment.Location().XYZ();
4144 gp_XYZ dir = lastSegment.Direction().XYZ();
4146 SMESH_TNodeXYZ vert0( n0 );
4147 SMESH_TNodeXYZ vert1( n1 );
4148 SMESH_TNodeXYZ vert2( n2 );
4150 /* calculate distance from vert0 to ray origin */
4151 gp_XYZ tvec = orig - vert0;
4153 if ( tvec * dir > EPSILON )
4154 // intersected face is at back side of the temporary face this _LayerEdge belongs to
4157 gp_XYZ edge1 = vert1 - vert0;
4158 gp_XYZ edge2 = vert2 - vert0;
4160 /* begin calculating determinant - also used to calculate U parameter */
4161 gp_XYZ pvec = dir ^ edge2;
4163 /* if determinant is near zero, ray lies in plane of triangle */
4164 double det = edge1 * pvec;
4166 if (det > -EPSILON && det < EPSILON)
4168 double inv_det = 1.0 / det;
4170 /* calculate U parameter and test bounds */
4171 double u = ( tvec * pvec ) * inv_det;
4172 if (u < 0.0 || u > 1.0)
4175 /* prepare to test V parameter */
4176 gp_XYZ qvec = tvec ^ edge1;
4178 /* calculate V parameter and test bounds */
4179 double v = (dir * qvec) * inv_det;
4180 if ( v < 0.0 || u + v > 1.0 )
4183 /* calculate t, ray intersects triangle */
4184 t = (edge2 * qvec) * inv_det;
4189 //================================================================================
4191 * \brief Perform smooth of _LayerEdge's based on EDGE's
4192 * \retval bool - true if node has been moved
4194 //================================================================================
4196 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
4197 const TopoDS_Face& F,
4198 SMESH_MesherHelper& helper)
4200 ASSERT( IsOnEdge() );
4202 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
4203 SMESH_TNodeXYZ oldPos( tgtNode );
4204 double dist01, distNewOld;
4206 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
4207 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
4208 dist01 = p0.Distance( _2neibors->_nodes[1] );
4210 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
4211 double lenDelta = 0;
4214 //lenDelta = _curvature->lenDelta( _len );
4215 lenDelta = _curvature->lenDeltaByDist( dist01 );
4216 newPos.ChangeCoord() += _normal * lenDelta;
4219 distNewOld = newPos.Distance( oldPos );
4223 if ( _2neibors->_plnNorm )
4225 // put newPos on the plane defined by source node and _plnNorm
4226 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
4227 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
4228 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
4230 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4231 _pos.back() = newPos.XYZ();
4235 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4236 gp_XY uv( Precision::Infinite(), 0 );
4237 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
4238 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
4240 newPos = surface->Value( uv.X(), uv.Y() );
4241 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4244 if ( _curvature && lenDelta < 0 )
4246 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
4247 _len -= prevPos.Distance( oldPos );
4248 _len += prevPos.Distance( newPos );
4250 bool moved = distNewOld > dist01/50;
4252 dumpMove( tgtNode ); // debug
4257 //================================================================================
4259 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
4260 * \retval bool - true if _tgtNode has been moved
4262 //================================================================================
4264 bool _LayerEdge::Smooth(int& badNb)
4266 if ( _simplices.size() < 2 )
4267 return false; // _LayerEdge inflated along EDGE or FACE
4269 // compute new position for the last _pos
4270 gp_XYZ newPos (0,0,0);
4271 for ( size_t i = 0; i < _simplices.size(); ++i )
4272 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
4273 newPos /= _simplices.size();
4276 newPos += _normal * _curvature->lenDelta( _len );
4278 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
4280 // count quality metrics (orientation) of tetras around _tgtNode
4282 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
4283 for ( size_t i = 0; i < _simplices.size(); ++i )
4284 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
4287 for ( size_t i = 0; i < _simplices.size(); ++i )
4288 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
4290 if ( nbOkAfter < nbOkBefore )
4293 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
4295 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
4296 _len += prevPos.Distance(newPos);
4298 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
4299 _pos.back() = newPos;
4301 badNb += _simplices.size() - nbOkAfter;
4308 //================================================================================
4310 * \brief Add a new segment to _LayerEdge during inflation
4312 //================================================================================
4314 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
4316 if ( _len - len > -1e-6 )
4318 _pos.push_back( _pos.back() );
4322 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
4323 SMESH_TNodeXYZ oldXYZ( n );
4324 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
4325 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
4327 _pos.push_back( nXYZ );
4329 if ( !_sWOL.IsNull() )
4332 if ( _sWOL.ShapeType() == TopAbs_EDGE )
4334 double u = Precision::Infinite(); // to force projection w/o distance check
4335 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
4336 _pos.back().SetCoord( u, 0, 0 );
4337 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
4338 pos->SetUParameter( u );
4342 gp_XY uv( Precision::Infinite(), 0 );
4343 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
4344 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
4345 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
4346 pos->SetUParameter( uv.X() );
4347 pos->SetVParameter( uv.Y() );
4349 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
4351 dumpMove( n ); //debug
4354 //================================================================================
4356 * \brief Remove last inflation step
4358 //================================================================================
4360 void _LayerEdge::InvalidateStep( int curStep, bool restoreLength )
4362 if ( _pos.size() > curStep )
4364 if ( restoreLength )
4365 _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
4367 _pos.resize( curStep );
4368 gp_Pnt nXYZ = _pos.back();
4369 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
4370 if ( !_sWOL.IsNull() )
4372 TopLoc_Location loc;
4373 if ( _sWOL.ShapeType() == TopAbs_EDGE )
4375 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
4376 pos->SetUParameter( nXYZ.X() );
4378 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
4379 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
4383 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
4384 pos->SetUParameter( nXYZ.X() );
4385 pos->SetVParameter( nXYZ.Y() );
4386 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
4387 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
4390 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
4395 //================================================================================
4397 * \brief Create layers of prisms
4399 //================================================================================
4401 bool _ViscousBuilder::refine(_SolidData& data)
4403 SMESH_MesherHelper helper( *_mesh );
4404 helper.SetSubShape( data._solid );
4405 helper.SetElementsOnShape(false);
4407 Handle(Geom_Curve) curve;
4408 Handle(Geom_Surface) surface;
4409 TopoDS_Edge geomEdge;
4410 TopoDS_Face geomFace;
4411 TopoDS_Shape prevSWOL;
4412 TopLoc_Location loc;
4416 TGeomID prevBaseId = -1;
4417 TNode2Edge* n2eMap = 0;
4418 TNode2Edge::iterator n2e;
4420 for ( size_t i = 0; i < data._edges.size(); ++i )
4422 _LayerEdge& edge = *data._edges[i];
4424 // get accumulated length of segments
4425 vector< double > segLen( edge._pos.size() );
4427 for ( size_t j = 1; j < edge._pos.size(); ++j )
4428 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
4430 // allocate memory for new nodes if it is not yet refined
4431 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4432 if ( edge._nodes.size() == 2 )
4434 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
4436 edge._nodes.back() = tgtNode;
4438 // get data of a shrink shape
4439 if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
4441 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
4444 geomEdge = TopoDS::Edge( edge._sWOL );
4445 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
4449 geomFace = TopoDS::Face( edge._sWOL );
4450 surface = BRep_Tool::Surface( geomFace, loc );
4452 prevSWOL = edge._sWOL;
4454 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
4455 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
4456 if ( baseShapeId != prevBaseId )
4458 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
4459 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
4460 prevBaseId = baseShapeId;
4462 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
4464 _LayerEdge* foundEdge = n2e->second;
4465 const gp_XYZ& foundPos = foundEdge->_pos.back();
4466 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
4469 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
4470 epos->SetUParameter( foundPos.X() );
4474 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
4475 fpos->SetUParameter( foundPos.X() );
4476 fpos->SetVParameter( foundPos.Y() );
4479 // calculate height of the first layer
4481 const double T = segLen.back(); //data._hyp.GetTotalThickness();
4482 const double f = data._hyp->GetStretchFactor();
4483 const int N = data._hyp->GetNumberLayers();
4484 const double fPowN = pow( f, N );
4485 if ( fPowN - 1 <= numeric_limits<double>::min() )
4488 h0 = T * ( f - 1 )/( fPowN - 1 );
4490 const double zeroLen = std::numeric_limits<double>::min();
4492 // create intermediate nodes
4493 double hSum = 0, hi = h0/f;
4495 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
4497 // compute an intermediate position
4500 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
4502 int iPrevSeg = iSeg-1;
4503 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
4505 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
4506 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
4508 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
4509 if ( !edge._sWOL.IsNull() )
4511 // compute XYZ by parameters <pos>
4516 pos = curve->Value( u ).Transformed(loc);
4520 uv.SetCoord( pos.X(), pos.Y() );
4522 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
4525 // create or update the node
4528 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
4529 if ( !edge._sWOL.IsNull() )
4532 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
4534 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
4538 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
4543 if ( !edge._sWOL.IsNull() )
4545 // make average pos from new and current parameters
4548 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
4549 pos = curve->Value( u ).Transformed(loc);
4551 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
4552 epos->SetUParameter( u );
4556 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
4557 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
4559 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
4560 fpos->SetUParameter( uv.X() );
4561 fpos->SetVParameter( uv.Y() );
4564 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
4569 if ( !getMeshDS()->IsEmbeddedMode() )
4570 // Log node movement
4571 for ( size_t i = 0; i < data._edges.size(); ++i )
4573 _LayerEdge& edge = *data._edges[i];
4574 SMESH_TNodeXYZ p ( edge._nodes.back() );
4575 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
4578 // TODO: make quadratic prisms and polyhedrons(?)
4580 helper.SetElementsOnShape(true);
4582 TopExp_Explorer exp( data._solid, TopAbs_FACE );
4583 for ( ; exp.More(); exp.Next() )
4585 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
4587 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
4588 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
4589 vector< vector<const SMDS_MeshNode*>* > nnVec;
4590 while ( fIt->more() )
4592 const SMDS_MeshElement* face = fIt->next();
4593 int nbNodes = face->NbCornerNodes();
4594 nnVec.resize( nbNodes );
4595 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
4596 for ( int iN = 0; iN < nbNodes; ++iN )
4598 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4599 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
4602 int nbZ = nnVec[0]->size();
4606 for ( int iZ = 1; iZ < nbZ; ++iZ )
4607 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
4608 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
4611 for ( int iZ = 1; iZ < nbZ; ++iZ )
4612 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
4613 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
4614 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
4615 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
4618 return error("Not supported type of element", data._index);
4625 //================================================================================
4627 * \brief Shrink 2D mesh on faces to let space for inflated layers
4629 //================================================================================
4631 bool _ViscousBuilder::shrink()
4633 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
4634 // inflated along FACE or EDGE)
4635 map< TGeomID, _SolidData* > f2sdMap;
4636 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4638 _SolidData& data = _sdVec[i];
4639 TopTools_MapOfShape FFMap;
4640 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
4641 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
4642 if ( s2s->second.ShapeType() == TopAbs_FACE )
4644 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
4646 if ( FFMap.Add( (*s2s).second ))
4647 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
4648 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
4649 // by StdMeshers_QuadToTriaAdaptor
4650 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
4652 SMESH_ProxyMesh::SubMesh* proxySub =
4653 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
4654 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4655 while ( fIt->more() )
4656 proxySub->AddElement( fIt->next() );
4657 // as a result 3D algo will use elements from proxySub and not from smDS
4662 SMESH_MesherHelper helper( *_mesh );
4663 helper.ToFixNodeParameters( true );
4666 map< TGeomID, _Shrinker1D > e2shrMap;
4668 // loop on FACES to srink mesh on
4669 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
4670 for ( ; f2sd != f2sdMap.end(); ++f2sd )
4672 _SolidData& data = *f2sd->second;
4673 TNode2Edge& n2eMap = data._n2eMap;
4674 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
4676 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
4678 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
4679 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
4681 helper.SetSubShape(F);
4683 // ===========================
4684 // Prepare data for shrinking
4685 // ===========================
4687 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
4688 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
4689 vector < const SMDS_MeshNode* > smoothNodes;
4691 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
4692 while ( nIt->more() )
4694 const SMDS_MeshNode* n = nIt->next();
4695 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
4696 smoothNodes.push_back( n );
4699 // Find out face orientation
4701 const set<TGeomID> ignoreShapes;
4703 if ( !smoothNodes.empty() )
4705 vector<_Simplex> simplices;
4706 getSimplices( smoothNodes[0], simplices, ignoreShapes );
4707 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
4708 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
4709 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
4710 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
4714 // Find _LayerEdge's inflated along F
4715 vector< _LayerEdge* > lEdges;
4717 SMESH_subMeshIteratorPtr subIt =
4718 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
4719 while ( subIt->more() )
4721 SMESH_subMesh* sub = subIt->next();
4722 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
4723 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
4725 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
4726 while ( nIt->more() )
4728 _LayerEdge* edge = n2eMap[ nIt->next() ];
4729 lEdges.push_back( edge );
4730 prepareEdgeToShrink( *edge, F, helper, smDS );
4735 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
4736 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4737 while ( fIt->more() )
4738 if ( const SMDS_MeshElement* f = fIt->next() )
4739 dumpChangeNodes( f );
4741 // Replace source nodes by target nodes in mesh faces to shrink
4742 const SMDS_MeshNode* nodes[20];
4743 for ( size_t i = 0; i < lEdges.size(); ++i )
4745 _LayerEdge& edge = *lEdges[i];
4746 const SMDS_MeshNode* srcNode = edge._nodes[0];
4747 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4748 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4749 while ( fIt->more() )
4751 const SMDS_MeshElement* f = fIt->next();
4752 if ( !smDS->Contains( f ))
4754 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
4755 for ( int iN = 0; nIt->more(); ++iN )
4757 const SMDS_MeshNode* n = nIt->next();
4758 nodes[iN] = ( n == srcNode ? tgtNode : n );
4760 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
4764 // find out if a FACE is concave
4765 const bool isConcaveFace = isConcave( F, helper );
4767 // Create _SmoothNode's on face F
4768 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
4770 const bool sortSimplices = isConcaveFace;
4771 for ( size_t i = 0; i < smoothNodes.size(); ++i )
4773 const SMDS_MeshNode* n = smoothNodes[i];
4774 nodesToSmooth[ i ]._node = n;
4775 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
4776 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
4777 // fix up incorrect uv of nodes on the FACE
4778 helper.GetNodeUV( F, n, 0, &isOkUV);
4782 //if ( nodesToSmooth.empty() ) continue;
4784 // Find EDGE's to shrink and set simpices to LayerEdge's
4785 set< _Shrinker1D* > eShri1D;
4787 for ( size_t i = 0; i < lEdges.size(); ++i )
4789 _LayerEdge* edge = lEdges[i];
4790 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4792 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4793 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4794 eShri1D.insert( & srinker );
4795 srinker.AddEdge( edge, helper );
4796 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4797 // restore params of nodes on EGDE if the EDGE has been already
4798 // srinked while srinking another FACE
4799 srinker.RestoreParams();
4801 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4805 bool toFixTria = false; // to improve quality of trias by diagonal swap
4806 if ( isConcaveFace )
4808 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4809 if ( hasTria != hasQuad ) {
4810 toFixTria = hasTria;
4813 set<int> nbNodesSet;
4814 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4815 while ( fIt->more() && nbNodesSet.size() < 2 )
4816 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4817 toFixTria = ( *nbNodesSet.begin() == 3 );
4821 // ==================
4822 // Perform shrinking
4823 // ==================
4825 bool shrinked = true;
4826 int badNb, shriStep=0, smooStep=0;
4827 _SmoothNode::SmoothType smoothType
4828 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4832 // Move boundary nodes (actually just set new UV)
4833 // -----------------------------------------------
4834 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4836 for ( size_t i = 0; i < lEdges.size(); ++i )
4838 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4842 // Move nodes on EDGE's
4843 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4844 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4845 for ( ; shr != eShri1D.end(); ++shr )
4846 (*shr)->Compute( /*set3D=*/false, helper );
4849 // -----------------
4850 int nbNoImpSteps = 0;
4853 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4855 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4857 int oldBadNb = badNb;
4860 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4862 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4863 smoothType, /*set3D=*/isConcaveFace);
4865 if ( badNb < oldBadNb )
4873 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4874 if ( shriStep > 200 )
4875 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4877 // Fix narrow triangles by swapping diagonals
4878 // ---------------------------------------
4881 set<const SMDS_MeshNode*> usedNodes;
4882 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4884 // update working data
4885 set<const SMDS_MeshNode*>::iterator n;
4886 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4888 n = usedNodes.find( nodesToSmooth[ i ]._node );
4889 if ( n != usedNodes.end())
4891 getSimplices( nodesToSmooth[ i ]._node,
4892 nodesToSmooth[ i ]._simplices,
4894 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4895 usedNodes.erase( n );
4898 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4900 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4901 if ( n != usedNodes.end())
4903 getSimplices( lEdges[i]->_nodes.back(),
4904 lEdges[i]->_simplices,
4906 usedNodes.erase( n );
4910 } // while ( shrinked )
4912 // No wrongly shaped faces remain; final smooth. Set node XYZ.
4913 bool isStructuredFixed = false;
4914 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4915 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4916 if ( !isStructuredFixed )
4918 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4919 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4921 for ( int st = 3; st; --st )
4924 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4925 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4926 case 3: smoothType = _SmoothNode::ANGULAR; break;
4928 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4929 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4931 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4932 smoothType,/*set3D=*/st==1 );
4937 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4938 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4940 if ( !getMeshDS()->IsEmbeddedMode() )
4941 // Log node movement
4942 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4944 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4945 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4948 } // loop on FACES to srink mesh on
4951 // Replace source nodes by target nodes in shrinked mesh edges
4953 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4954 for ( ; e2shr != e2shrMap.end(); ++e2shr )
4955 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4960 //================================================================================
4962 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4964 //================================================================================
4966 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
4967 const TopoDS_Face& F,
4968 SMESH_MesherHelper& helper,
4969 const SMESHDS_SubMesh* faceSubMesh)
4971 const SMDS_MeshNode* srcNode = edge._nodes[0];
4972 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4976 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4978 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4979 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4980 gp_Vec2d uvDir( srcUV, tgtUV );
4981 double uvLen = uvDir.Magnitude();
4983 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4986 edge._pos.resize(1);
4987 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4989 // set UV of source node to target node
4990 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4991 pos->SetUParameter( srcUV.X() );
4992 pos->SetVParameter( srcUV.Y() );
4994 else // _sWOL is TopAbs_EDGE
4996 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4997 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4998 if ( !edgeSM || edgeSM->NbElements() == 0 )
4999 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
5001 const SMDS_MeshNode* n2 = 0;
5002 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5003 while ( eIt->more() && !n2 )
5005 const SMDS_MeshElement* e = eIt->next();
5006 if ( !edgeSM->Contains(e)) continue;
5007 n2 = e->GetNode( 0 );
5008 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
5011 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
5013 double uSrc = helper.GetNodeU( E, srcNode, n2 );
5014 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
5015 double u2 = helper.GetNodeU( E, n2, srcNode );
5017 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
5019 // tgtNode is located so that it does not make faces with wrong orientation
5022 edge._pos.resize(1);
5023 edge._pos[0].SetCoord( U_TGT, uTgt );
5024 edge._pos[0].SetCoord( U_SRC, uSrc );
5025 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
5027 edge._simplices.resize( 1 );
5028 edge._simplices[0]._nPrev = n2;
5030 // set UV of source node to target node
5031 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
5032 pos->SetUParameter( uSrc );
5037 //================================================================================
5039 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
5041 //================================================================================
5043 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
5044 SMESH_MesherHelper& helper,
5047 set<const SMDS_MeshNode*> * involvedNodes)
5049 SMESH::Controls::AspectRatio qualifier;
5050 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
5051 const double maxAspectRatio = is2D ? 4. : 2;
5052 _NodeCoordHelper xyz( F, helper, is2D );
5054 // find bad triangles
5056 vector< const SMDS_MeshElement* > badTrias;
5057 vector< double > badAspects;
5058 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
5059 SMDS_ElemIteratorPtr fIt = sm->GetElements();
5060 while ( fIt->more() )
5062 const SMDS_MeshElement * f = fIt->next();
5063 if ( f->NbCornerNodes() != 3 ) continue;
5064 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
5065 double aspect = qualifier.GetValue( points );
5066 if ( aspect > maxAspectRatio )
5068 badTrias.push_back( f );
5069 badAspects.push_back( aspect );
5074 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
5075 SMDS_ElemIteratorPtr fIt = sm->GetElements();
5076 while ( fIt->more() )
5078 const SMDS_MeshElement * f = fIt->next();
5079 if ( f->NbCornerNodes() == 3 )
5080 dumpChangeNodes( f );
5084 if ( badTrias.empty() )
5087 // find couples of faces to swap diagonal
5089 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
5090 vector< T2Trias > triaCouples;
5092 TIDSortedElemSet involvedFaces, emptySet;
5093 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
5096 double aspRatio [3];
5099 if ( !involvedFaces.insert( badTrias[iTia] ).second )
5101 for ( int iP = 0; iP < 3; ++iP )
5102 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
5104 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
5105 int bestCouple = -1;
5106 for ( int iSide = 0; iSide < 3; ++iSide )
5108 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
5109 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
5110 trias [iSide].first = badTrias[iTia];
5111 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
5113 if (( ! trias[iSide].second ) ||
5114 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
5115 ( ! sm->Contains( trias[iSide].second )))
5118 // aspect ratio of an adjacent tria
5119 for ( int iP = 0; iP < 3; ++iP )
5120 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
5121 double aspectInit = qualifier.GetValue( points2 );
5123 // arrange nodes as after diag-swaping
5124 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
5125 i3 = helper.WrapIndex( i1-1, 3 );
5127 i3 = helper.WrapIndex( i1+1, 3 );
5129 points1( 1+ iSide ) = points2( 1+ i3 );
5130 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
5132 // aspect ratio after diag-swaping
5133 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
5134 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
5137 // prevent inversion of a triangle
5138 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
5139 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
5140 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
5143 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
5147 if ( bestCouple >= 0 )
5149 triaCouples.push_back( trias[bestCouple] );
5150 involvedFaces.insert ( trias[bestCouple].second );
5154 involvedFaces.erase( badTrias[iTia] );
5157 if ( triaCouples.empty() )
5162 SMESH_MeshEditor editor( helper.GetMesh() );
5163 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
5164 for ( size_t i = 0; i < triaCouples.size(); ++i )
5166 dumpChangeNodes( triaCouples[i].first );
5167 dumpChangeNodes( triaCouples[i].second );
5168 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
5171 if ( involvedNodes )
5172 for ( size_t i = 0; i < triaCouples.size(); ++i )
5174 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
5175 triaCouples[i].first->end_nodes() );
5176 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
5177 triaCouples[i].second->end_nodes() );
5180 // just for debug dump resulting triangles
5181 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
5182 for ( size_t i = 0; i < triaCouples.size(); ++i )
5184 dumpChangeNodes( triaCouples[i].first );
5185 dumpChangeNodes( triaCouples[i].second );
5189 //================================================================================
5191 * \brief Move target node to it's final position on the FACE during shrinking
5193 //================================================================================
5195 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
5196 const TopoDS_Face& F,
5197 SMESH_MesherHelper& helper )
5200 return false; // already at the target position
5202 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
5204 if ( _sWOL.ShapeType() == TopAbs_FACE )
5206 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
5207 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
5208 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
5209 const double uvLen = tgtUV.Distance( curUV );
5210 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
5212 // Select shrinking step such that not to make faces with wrong orientation.
5213 double stepSize = uvLen;
5214 for ( size_t i = 0; i < _simplices.size(); ++i )
5216 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
5217 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
5218 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
5219 gp_XY dirN = uvN2 - uvN1;
5220 double det = uvDir.Crossed( dirN );
5221 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
5222 gp_XY dirN2Cur = curUV - uvN1;
5223 double step = dirN.Crossed( dirN2Cur ) / det;
5225 stepSize = Min( step, stepSize );
5228 if ( uvLen - stepSize < _len / 200. )
5233 else if ( stepSize > 0 )
5235 newUV = curUV + uvDir.XY() * stepSize * kSafe;
5241 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5242 pos->SetUParameter( newUV.X() );
5243 pos->SetVParameter( newUV.Y() );
5246 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
5247 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5248 dumpMove( tgtNode );
5251 else // _sWOL is TopAbs_EDGE
5253 TopoDS_Edge E = TopoDS::Edge( _sWOL );
5254 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
5255 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
5257 const double u2 = helper.GetNodeU( E, n2, tgtNode );
5258 const double uSrc = _pos[0].Coord( U_SRC );
5259 const double lenTgt = _pos[0].Coord( LEN_TGT );
5261 double newU = _pos[0].Coord( U_TGT );
5262 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
5268 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
5270 tgtPos->SetUParameter( newU );
5272 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
5273 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
5274 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5275 dumpMove( tgtNode );
5281 //================================================================================
5283 * \brief Perform smooth on the FACE
5284 * \retval bool - true if the node has been moved
5286 //================================================================================
5288 bool _SmoothNode::Smooth(int& badNb,
5289 Handle(Geom_Surface)& surface,
5290 SMESH_MesherHelper& helper,
5291 const double refSign,
5295 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
5297 // get uv of surrounding nodes
5298 vector<gp_XY> uv( _simplices.size() );
5299 for ( size_t i = 0; i < _simplices.size(); ++i )
5300 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
5302 // compute new UV for the node
5304 if ( how == TFI && _simplices.size() == 4 )
5307 for ( size_t i = 0; i < _simplices.size(); ++i )
5308 if ( _simplices[i]._nOpp )
5309 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
5311 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
5313 newPos = helper.calcTFI ( 0.5, 0.5,
5314 corners[0], corners[1], corners[2], corners[3],
5315 uv[1], uv[2], uv[3], uv[0] );
5317 else if ( how == ANGULAR )
5319 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
5321 else if ( how == CENTROIDAL && _simplices.size() > 3 )
5323 // average centers of diagonals wieghted with their reciprocal lengths
5324 if ( _simplices.size() == 4 )
5326 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
5327 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
5328 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
5332 double sumWeight = 0;
5333 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
5334 for ( int i = 0; i < nb; ++i )
5337 int iTo = i + _simplices.size() - 1;
5338 for ( int j = iFrom; j < iTo; ++j )
5340 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
5341 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
5343 newPos += w * ( uv[i]+uv[i2] );
5346 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
5352 for ( size_t i = 0; i < _simplices.size(); ++i )
5354 newPos /= _simplices.size();
5357 // count quality metrics (orientation) of triangles around the node
5359 gp_XY tgtUV = helper.GetNodeUV( face, _node );
5360 for ( size_t i = 0; i < _simplices.size(); ++i )
5361 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
5364 for ( size_t i = 0; i < _simplices.size(); ++i )
5365 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
5367 if ( nbOkAfter < nbOkBefore )
5369 badNb += _simplices.size() - nbOkBefore;
5373 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
5374 pos->SetUParameter( newPos.X() );
5375 pos->SetVParameter( newPos.Y() );
5382 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
5383 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
5387 badNb += _simplices.size() - nbOkAfter;
5388 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
5391 //================================================================================
5393 * \brief Computes new UV using angle based smoothing technic
5395 //================================================================================
5397 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
5398 const gp_XY& uvToFix,
5399 const double refSign)
5401 uv.push_back( uv.front() );
5403 vector< gp_XY > edgeDir ( uv.size() );
5404 vector< double > edgeSize( uv.size() );
5405 for ( size_t i = 1; i < edgeDir.size(); ++i )
5407 edgeDir [i-1] = uv[i] - uv[i-1];
5408 edgeSize[i-1] = edgeDir[i-1].Modulus();
5409 if ( edgeSize[i-1] < numeric_limits<double>::min() )
5410 edgeDir[i-1].SetX( 100 );
5412 edgeDir[i-1] /= edgeSize[i-1] * refSign;
5414 edgeDir.back() = edgeDir.front();
5415 edgeSize.back() = edgeSize.front();
5420 for ( size_t i = 1; i < edgeDir.size(); ++i )
5422 if ( edgeDir[i-1].X() > 1. ) continue;
5424 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
5425 if ( i == edgeDir.size() ) break;
5427 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
5428 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
5429 gp_XY bisec = norm1 + norm2;
5430 double bisecSize = bisec.Modulus();
5431 if ( bisecSize < numeric_limits<double>::min() )
5433 bisec = -edgeDir[i1] + edgeDir[i];
5434 bisecSize = bisec.Modulus();
5438 gp_XY dirToN = uvToFix - p;
5439 double distToN = dirToN.Modulus();
5440 if ( bisec * dirToN < 0 )
5443 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
5445 sumSize += edgeSize[i1] + edgeSize[i];
5447 newPos /= /*nbEdges * */sumSize;
5451 //================================================================================
5453 * \brief Delete _SolidData
5455 //================================================================================
5457 _SolidData::~_SolidData()
5459 for ( size_t i = 0; i < _edges.size(); ++i )
5461 if ( _edges[i] && _edges[i]->_2neibors )
5462 delete _edges[i]->_2neibors;
5467 //================================================================================
5469 * \brief Add a _LayerEdge inflated along the EDGE
5471 //================================================================================
5473 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
5476 if ( _nodes.empty() )
5478 _edges[0] = _edges[1] = 0;
5482 if ( e == _edges[0] || e == _edges[1] )
5484 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
5485 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
5486 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
5487 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
5490 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
5492 BRep_Tool::Range( E, f,l );
5493 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
5494 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
5498 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
5499 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
5501 if ( _nodes.empty() )
5503 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
5504 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
5506 TopLoc_Location loc;
5507 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
5508 GeomAdaptor_Curve aCurve(C, f,l);
5509 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
5511 int nbExpectNodes = eSubMesh->NbNodes();
5512 _initU .reserve( nbExpectNodes );
5513 _normPar.reserve( nbExpectNodes );
5514 _nodes .reserve( nbExpectNodes );
5515 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
5516 while ( nIt->more() )
5518 const SMDS_MeshNode* node = nIt->next();
5519 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
5520 node == tgtNode0 || node == tgtNode1 )
5521 continue; // refinement nodes
5522 _nodes.push_back( node );
5523 _initU.push_back( helper.GetNodeU( E, node ));
5524 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
5525 _normPar.push_back( len / totLen );
5530 // remove target node of the _LayerEdge from _nodes
5532 for ( size_t i = 0; i < _nodes.size(); ++i )
5533 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
5534 _nodes[i] = 0, nbFound++;
5535 if ( nbFound == _nodes.size() )
5540 //================================================================================
5542 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
5544 //================================================================================
5546 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
5548 if ( _done || _nodes.empty())
5550 const _LayerEdge* e = _edges[0];
5551 if ( !e ) e = _edges[1];
5554 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
5555 ( !_edges[1] || _edges[1]->_pos.empty() ));
5557 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
5559 if ( set3D || _done )
5561 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
5562 GeomAdaptor_Curve aCurve(C, f,l);
5565 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
5567 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
5568 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
5570 for ( size_t i = 0; i < _nodes.size(); ++i )
5572 if ( !_nodes[i] ) continue;
5573 double len = totLen * _normPar[i];
5574 GCPnts_AbscissaPoint discret( aCurve, len, f );
5575 if ( !discret.IsDone() )
5576 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
5577 double u = discret.Parameter();
5578 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
5579 pos->SetUParameter( u );
5580 gp_Pnt p = C->Value( u );
5581 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
5586 BRep_Tool::Range( E, f,l );
5588 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
5590 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
5592 for ( size_t i = 0; i < _nodes.size(); ++i )
5594 if ( !_nodes[i] ) continue;
5595 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
5596 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
5597 pos->SetUParameter( u );
5602 //================================================================================
5604 * \brief Restore initial parameters of nodes on EDGE
5606 //================================================================================
5608 void _Shrinker1D::RestoreParams()
5611 for ( size_t i = 0; i < _nodes.size(); ++i )
5613 if ( !_nodes[i] ) continue;
5614 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
5615 pos->SetUParameter( _initU[i] );
5620 //================================================================================
5622 * \brief Replace source nodes by target nodes in shrinked mesh edges
5624 //================================================================================
5626 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
5628 const SMDS_MeshNode* nodes[3];
5629 for ( int i = 0; i < 2; ++i )
5631 if ( !_edges[i] ) continue;
5633 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
5634 if ( !eSubMesh ) return;
5635 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
5636 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
5637 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5638 while ( eIt->more() )
5640 const SMDS_MeshElement* e = eIt->next();
5641 if ( !eSubMesh->Contains( e ))
5643 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5644 for ( int iN = 0; iN < e->NbNodes(); ++iN )
5646 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
5647 nodes[iN] = ( n == srcNode ? tgtNode : n );
5649 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
5654 //================================================================================
5656 * \brief Creates 2D and 1D elements on boundaries of new prisms
5658 //================================================================================
5660 bool _ViscousBuilder::addBoundaryElements()
5662 SMESH_MesherHelper helper( *_mesh );
5664 for ( size_t i = 0; i < _sdVec.size(); ++i )
5666 _SolidData& data = _sdVec[i];
5667 TopTools_IndexedMapOfShape geomEdges;
5668 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
5669 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
5671 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
5673 // Get _LayerEdge's based on E
5675 map< double, const SMDS_MeshNode* > u2nodes;
5676 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
5679 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
5680 TNode2Edge & n2eMap = data._n2eMap;
5681 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5683 //check if 2D elements are needed on E
5684 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5685 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5686 ledges.push_back( n2e->second );
5688 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5689 continue; // no layers on E
5690 ledges.push_back( n2eMap[ u2n->second ]);
5692 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5693 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5694 int nbSharedPyram = 0;
5695 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5696 while ( vIt->more() )
5698 const SMDS_MeshElement* v = vIt->next();
5699 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5701 if ( nbSharedPyram > 1 )
5702 continue; // not free border of the pyramid
5704 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5705 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5706 continue; // faces already created
5708 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5709 ledges.push_back( n2eMap[ u2n->second ]);
5711 // Find out orientation and type of face to create
5713 bool reverse = false, isOnFace;
5715 map< TGeomID, TopoDS_Shape >::iterator e2f =
5716 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5718 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5720 F = e2f->second.Oriented( TopAbs_FORWARD );
5721 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5722 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5723 reverse = !reverse, F.Reverse();
5724 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5729 // find FACE with layers sharing E
5730 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5731 while ( fIt->more() && F.IsNull() )
5733 const TopoDS_Shape* pF = fIt->next();
5734 if ( helper.IsSubShape( *pF, data._solid) &&
5735 !data._ignoreFaceIds.count( e2f->first ))
5739 // Find the sub-mesh to add new faces
5740 SMESHDS_SubMesh* sm = 0;
5742 sm = getMeshDS()->MeshElements( F );
5744 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5746 return error("error in addBoundaryElements()", data._index);
5749 const int dj1 = reverse ? 0 : 1;
5750 const int dj2 = reverse ? 1 : 0;
5751 for ( size_t j = 1; j < ledges.size(); ++j )
5753 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
5754 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
5756 for ( size_t z = 1; z < nn1.size(); ++z )
5757 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5759 for ( size_t z = 1; z < nn1.size(); ++z )
5760 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5764 for ( int isFirst = 0; isFirst < 2; ++isFirst )
5766 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5767 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5769 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
5770 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5772 helper.SetSubShape( edge->_sWOL );
5773 helper.SetElementsOnShape( true );
5774 for ( size_t z = 1; z < nn.size(); ++z )
5775 helper.AddEdge( nn[z-1], nn[z] );