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>
88 //#define __NOT_INVALIDATE_BAD_SMOOTH
93 //================================================================================
98 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
100 const double theMinSmoothCosin = 0.1;
101 const double theSmoothThickToElemSizeRatio = 0.3;
103 // what part of thickness is allowed till intersection
104 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
105 const double theThickToIntersection = 1.5;
107 bool needSmoothing( double cosin, double tgtThick, double elemSize )
109 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
113 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
114 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
116 struct _MeshOfSolid : public SMESH_ProxyMesh,
117 public SMESH_subMeshEventListenerData
119 bool _n2nMapComputed;
120 SMESH_ComputeErrorPtr _warning;
122 _MeshOfSolid( SMESH_Mesh* mesh)
123 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
125 SMESH_ProxyMesh::setMesh( *mesh );
128 // returns submesh for a geom face
129 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
131 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
132 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
134 void setNode2Node(const SMDS_MeshNode* srcNode,
135 const SMDS_MeshNode* proxyNode,
136 const SMESH_ProxyMesh::SubMesh* subMesh)
138 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
141 //--------------------------------------------------------------------------------
143 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
144 * It is used to clear an inferior dim sub-meshes modified by viscous layers
146 class _ShrinkShapeListener : SMESH_subMeshEventListener
148 _ShrinkShapeListener()
149 : SMESH_subMeshEventListener(/*isDeletable=*/false,
150 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
152 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
153 virtual void ProcessEvent(const int event,
155 SMESH_subMesh* solidSM,
156 SMESH_subMeshEventListenerData* data,
157 const SMESH_Hypothesis* hyp)
159 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
161 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
165 //--------------------------------------------------------------------------------
167 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
168 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
169 * delete the data as soon as it has been used
171 class _ViscousListener : SMESH_subMeshEventListener
174 SMESH_subMeshEventListener(/*isDeletable=*/false,
175 "StdMeshers_ViscousLayers::_ViscousListener") {}
176 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
178 virtual void ProcessEvent(const int event,
180 SMESH_subMesh* subMesh,
181 SMESH_subMeshEventListenerData* data,
182 const SMESH_Hypothesis* hyp)
184 if ( SMESH_subMesh::COMPUTE_EVENT == eventType &&
185 SMESH_subMesh::CHECK_COMPUTE_STATE != event)
187 // delete SMESH_ProxyMesh containing temporary faces
188 subMesh->DeleteEventListener( this );
191 // Finds or creates proxy mesh of the solid
192 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
193 const TopoDS_Shape& solid,
196 if ( !mesh ) return 0;
197 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
198 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
199 if ( !data && toCreate )
201 data = new _MeshOfSolid(mesh);
202 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
203 sm->SetEventListener( Get(), data, sm );
207 // Removes proxy mesh of the solid
208 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
210 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
214 //================================================================================
216 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
217 * the main shape when sub-mesh of the main shape is cleared,
218 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
221 //================================================================================
223 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
225 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
226 SMESH_subMeshEventListenerData* data =
227 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
230 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
231 data->mySubMeshes.end())
232 data->mySubMeshes.push_back( sub );
236 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
237 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
241 //--------------------------------------------------------------------------------
243 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
244 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
245 * The class is used to check validity of face or volumes around a smoothed node;
246 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
250 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
251 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
252 _Simplex(const SMDS_MeshNode* nPrev=0,
253 const SMDS_MeshNode* nNext=0,
254 const SMDS_MeshNode* nOpp=0)
255 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
256 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt, double& vol) const
258 const double M[3][3] =
259 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
260 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
261 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
262 vol = ( + M[0][0]*M[1][1]*M[2][2]
263 + M[0][1]*M[1][2]*M[2][0]
264 + M[0][2]*M[1][0]*M[2][1]
265 - M[0][0]*M[1][2]*M[2][1]
266 - M[0][1]*M[1][0]*M[2][2]
267 - M[0][2]*M[1][1]*M[2][0]);
270 bool IsForward(const gp_XY& tgtUV,
271 const SMDS_MeshNode* smoothedNode,
272 const TopoDS_Face& face,
273 SMESH_MesherHelper& helper,
274 const double refSign) const
276 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
277 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
278 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
280 return d*refSign > 1e-100;
282 bool IsNeighbour(const _Simplex& other) const
284 return _nPrev == other._nNext || _nNext == other._nPrev;
286 static void GetSimplices( const SMDS_MeshNode* node,
287 vector<_Simplex>& simplices,
288 const set<TGeomID>& ingnoreShapes,
289 const _SolidData* dataToCheckOri = 0,
290 const bool toSort = false);
291 static void SortSimplices(vector<_Simplex>& simplices);
293 //--------------------------------------------------------------------------------
295 * Structure used to take into account surface curvature while smoothing
300 double _k; // factor to correct node smoothed position
301 double _h2lenRatio; // avgNormProj / (2*avgDist)
303 static _Curvature* New( double avgNormProj, double avgDist )
306 if ( fabs( avgNormProj / avgDist ) > 1./200 )
309 c->_r = avgDist * avgDist / avgNormProj;
310 c->_k = avgDist * avgDist / c->_r / c->_r;
311 //c->_k = avgNormProj / c->_r;
312 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
313 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
317 double lenDelta(double len) const { return _k * ( _r + len ); }
318 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
320 //--------------------------------------------------------------------------------
324 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
326 //--------------------------------------------------------------------------------
328 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
329 * and a node of the most internal layer (_nodes.back())
333 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
335 vector< const SMDS_MeshNode*> _nodes;
337 gp_XYZ _normal; // to solid surface
338 vector<gp_XYZ> _pos; // points computed during inflation
339 double _len; // length achived with the last inflation step
340 double _cosin; // of angle (_normal ^ surface)
341 double _lenFactor; // to compute _len taking _cosin into account
343 // face or edge w/o layer along or near which _LayerEdge is inflated
345 // simplices connected to the source node (_nodes[0]);
346 // used for smoothing and quality check of _LayerEdge's based on the FACE
347 vector<_Simplex> _simplices;
348 PSmooFun _smooFunction; // smoothing function
349 // data for smoothing of _LayerEdge's based on the EDGE
350 _2NearEdges* _2neibors;
352 _Curvature* _curvature;
353 // TODO:: detele _Curvature, _plnNorm
355 void SetNewLength( double len, SMESH_MesherHelper& helper );
356 bool SetNewLength2d( Handle(Geom_Surface)& surface,
357 const TopoDS_Face& F,
358 SMESH_MesherHelper& helper );
359 void SetDataByNeighbors( const SMDS_MeshNode* n1,
360 const SMDS_MeshNode* n2,
361 SMESH_MesherHelper& helper);
362 void InvalidateStep( int curStep, bool restoreLength=false );
363 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
364 const TNode2Edge& n2eMap);
365 bool Smooth(int& badNb, const int step, const bool isConcaveFace);
366 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
367 const TopoDS_Face& F,
368 SMESH_MesherHelper& helper);
369 bool FindIntersection( SMESH_ElementSearcher& searcher,
371 const double& epsilon,
372 const SMDS_MeshElement** face = 0);
373 bool SegTriaInter( const gp_Ax1& lastSegment,
374 const SMDS_MeshNode* n0,
375 const SMDS_MeshNode* n1,
376 const SMDS_MeshNode* n2,
378 const double& epsilon) const;
379 gp_Ax1 LastSegment(double& segLen) const;
380 gp_XY LastUV( const TopoDS_Face& F ) const;
381 bool IsOnEdge() const { return _2neibors; }
382 gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
383 void SetCosin( double cosin );
384 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
386 gp_XYZ smoothLaplacian();
387 gp_XYZ smoothAngular();
388 gp_XYZ smoothLengthWeighted();
389 gp_XYZ smoothCentroidal();
390 gp_XYZ smoothNefPolygon();
392 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
393 static const int theNbSmooFuns = FUN_NB;
394 static PSmooFun _funs[theNbSmooFuns];
395 static const char* _funNames[theNbSmooFuns+1];
396 int smooFunID( PSmooFun fun=0) const;
398 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
399 &_LayerEdge::smoothLengthWeighted,
400 &_LayerEdge::smoothCentroidal,
401 &_LayerEdge::smoothNefPolygon,
402 &_LayerEdge::smoothAngular };
403 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
411 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
413 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
414 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
417 //--------------------------------------------------------------------------------
419 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
423 gp_XY _pos, _dir, _inNorm;
424 bool IsOut( const gp_XY p, const double tol ) const
426 return _inNorm * ( p - _pos ) < -tol;
428 bool FindInterestion( const _halfPlane& hp, gp_XY & intPnt )
430 const double eps = 1e-10;
431 double D = _dir.Crossed( hp._dir );
432 if ( fabs(D) < std::numeric_limits<double>::min())
434 gp_XY vec21 = _pos - hp._pos;
435 double u = hp._dir.Crossed( vec21 ) / D;
436 intPnt = _pos + _dir * u;
440 //--------------------------------------------------------------------------------
442 * Structure used to smooth a _LayerEdge based on an EDGE.
446 double _wgt [2]; // weights of _nodes
447 _LayerEdge* _edges[2];
449 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
452 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
453 const SMDS_MeshNode* tgtNode(bool is2nd) {
454 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
456 const SMDS_MeshNode* srcNode(bool is2nd) {
457 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
460 std::swap( _wgt [0], _wgt [1] );
461 std::swap( _edges[0], _edges[1] );
464 //--------------------------------------------------------------------------------
466 * \brief Convex FACE whose radius of curvature is less than the thickness of
467 * layers. It is used to detect distortion of prisms based on a convex
468 * FACE and to update normals to enable further increasing the thickness
474 // edges whose _simplices are used to detect prism destorsion
475 vector< _LayerEdge* > _simplexTestEdges;
477 // map a sub-shape to it's index in _SolidData::_endEdgeOnShape vector
478 map< TGeomID, int > _subIdToEdgeEnd;
482 bool GetCenterOfCurvature( _LayerEdge* ledge,
483 BRepLProp_SLProps& surfProp,
484 SMESH_MesherHelper& helper,
485 gp_Pnt & center ) const;
486 bool CheckPrisms() const;
489 //--------------------------------------------------------------------------------
491 * \brief Layers parameters got by averaging several hypotheses
495 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
496 :_nbLayers(0), _nbHyps(0), _thickness(0), _stretchFactor(0)
500 void Add( const StdMeshers_ViscousLayers* hyp )
505 _nbLayers = hyp->GetNumberLayers();
506 //_thickness += hyp->GetTotalThickness();
507 _thickness = Max( _thickness, hyp->GetTotalThickness() );
508 _stretchFactor += hyp->GetStretchFactor();
511 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
512 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
513 int GetNumberLayers() const { return _nbLayers; }
515 int _nbLayers, _nbHyps;
516 double _thickness, _stretchFactor;
519 //--------------------------------------------------------------------------------
521 * \brief Data of a SOLID
525 typedef const StdMeshers_ViscousLayers* THyp;
527 TGeomID _index; // SOLID id
528 _MeshOfSolid* _proxyMesh;
530 list< TopoDS_Shape > _hypShapes;
531 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
532 set< TGeomID > _reversedFaceIds;
533 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
535 double _stepSize, _stepSizeCoeff, _geomSize;
536 const SMDS_MeshNode* _stepSizeNodes[2];
538 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
540 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
541 map< TGeomID, TNode2Edge* > _s2neMap;
542 // edges of _n2eMap. We keep same data in two containers because
543 // iteration over the map is 5 times longer than over the vector
544 vector< _LayerEdge* > _edges;
546 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
547 // layers and a FACE w/o layers
548 // value: the shape (FACE or EDGE) to shrink mesh on.
549 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
550 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
552 // Convex FACEs whose radius of curvature is less than the thickness of layers
553 map< TGeomID, _ConvexFace > _convexFaces;
555 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
556 // the adjacent SOLID
557 set< TGeomID > _noShrinkShapes;
559 // <EDGE to smooth on> to <it's curve> -- for analytic smooth
560 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
562 // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
563 vector< int > _endEdgeOnShape;
564 int _nbShapesToSmooth;
565 set< TGeomID > _concaveFaces;
567 // data of averaged StdMeshers_ViscousLayers parameters for each shape with _LayerEdge's
568 vector< AverageHyp > _hypOnShape;
569 double _maxThickness; // of all _hyps
570 double _minThickness; // of all _hyps
572 double _epsilon; // precision for SegTriaInter()
574 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
576 :_solid(s), _proxyMesh(m) {}
579 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
582 const TopoDS_Face& F,
583 SMESH_MesherHelper& helper,
584 vector<_LayerEdge* >* edges=0);
586 void SortOnEdge( const TopoDS_Edge& E,
589 SMESH_MesherHelper& helper);
591 void Sort2NeiborsOnEdge( const int iFrom, const int iTo);
593 _ConvexFace* GetConvexFace( const TGeomID faceID )
595 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
596 return id2face == _convexFaces.end() ? 0 : & id2face->second;
598 void GetEdgesOnShape( size_t end, int & iBeg, int & iEnd )
600 iBeg = end > 0 ? _endEdgeOnShape[ end-1 ] : 0;
601 iEnd = _endEdgeOnShape[ end ];
604 bool GetShapeEdges(const TGeomID shapeID, size_t& iEdgeEnd, int* iBeg=0, int* iEnd=0 ) const;
606 void AddShapesToSmooth( const set< TGeomID >& shapeIDs );
608 void PrepareEdgesToSmoothOnFace( _LayerEdge** edgeBeg,
609 _LayerEdge** edgeEnd,
610 const TopoDS_Face& face,
611 bool substituteSrcNodes );
613 //--------------------------------------------------------------------------------
615 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
617 struct _CentralCurveOnEdge
620 vector< gp_Pnt > _curvaCenters;
621 vector< _LayerEdge* > _ledges;
622 vector< gp_XYZ > _normals; // new normal for each of _ledges
623 vector< double > _segLength2;
626 TopoDS_Face _adjFace;
627 bool _adjFaceToSmooth;
629 void Append( const gp_Pnt& center, _LayerEdge* ledge )
631 if ( _curvaCenters.size() > 0 )
632 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
633 _curvaCenters.push_back( center );
634 _ledges.push_back( ledge );
635 _normals.push_back( ledge->_normal );
637 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
638 void SetShapes( const TopoDS_Edge& edge,
639 const _ConvexFace& convFace,
640 const _SolidData& data,
641 SMESH_MesherHelper& helper);
643 //--------------------------------------------------------------------------------
645 * \brief Data of node on a shrinked FACE
649 const SMDS_MeshNode* _node;
650 vector<_Simplex> _simplices; // for quality check
652 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
654 bool Smooth(int& badNb,
655 Handle(Geom_Surface)& surface,
656 SMESH_MesherHelper& helper,
657 const double refSign,
661 gp_XY computeAngularPos(vector<gp_XY>& uv,
662 const gp_XY& uvToFix,
663 const double refSign );
665 //--------------------------------------------------------------------------------
667 * \brief Builder of viscous layers
669 class _ViscousBuilder
674 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
675 const TopoDS_Shape& shape);
676 // check validity of hypotheses
677 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
678 const TopoDS_Shape& shape );
680 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
681 void RestoreListeners();
683 // computes SMESH_ProxyMesh::SubMesh::_n2n;
684 bool MakeN2NMap( _MeshOfSolid* pm );
688 bool findSolidsWithLayers();
689 bool findFacesWithLayers(const bool onlyWith=false);
690 void getIgnoreFaces(const TopoDS_Shape& solid,
691 const StdMeshers_ViscousLayers* hyp,
692 const TopoDS_Shape& hypShape,
693 set<TGeomID>& ignoreFaces);
694 bool makeLayer(_SolidData& data);
695 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
696 SMESH_MesherHelper& helper, _SolidData& data);
697 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
698 const TopoDS_Face& face,
699 SMESH_MesherHelper& helper,
701 bool shiftInside=false);
702 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
703 std::pair< TGeomID, gp_XYZ > fId2Normal[],
705 bool findNeiborsOnEdge(const _LayerEdge* edge,
706 const SMDS_MeshNode*& n1,
707 const SMDS_MeshNode*& n2,
709 void findSimplexTestEdges( _SolidData& data,
710 vector< vector<_LayerEdge*> >& edgesByGeom);
711 void computeGeomSize( _SolidData& data );
712 bool sortEdges( _SolidData& data,
713 vector< vector<_LayerEdge*> >& edgesByGeom);
714 void limitStepSizeByCurvature( _SolidData& data );
715 void limitStepSize( _SolidData& data,
716 const SMDS_MeshElement* face,
717 const _LayerEdge* maxCosinEdge );
718 void limitStepSize( _SolidData& data, const double minSize);
719 bool inflate(_SolidData& data);
720 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
721 bool smoothAnalyticEdge( _SolidData& data,
724 Handle(Geom_Surface)& surface,
725 const TopoDS_Face& F,
726 SMESH_MesherHelper& helper);
727 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
728 bool updateNormalsOfConvexFaces( _SolidData& data,
729 SMESH_MesherHelper& helper,
731 bool refine(_SolidData& data);
733 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
734 SMESH_MesherHelper& helper,
735 const SMESHDS_SubMesh* faceSubMesh );
736 void restoreNoShrink( _LayerEdge& edge ) const;
737 void fixBadFaces(const TopoDS_Face& F,
738 SMESH_MesherHelper& helper,
741 set<const SMDS_MeshNode*> * involvedNodes=NULL);
742 bool addBoundaryElements();
744 bool error( const string& text, int solidID=-1 );
745 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
748 void makeGroupOfLE();
751 SMESH_ComputeErrorPtr _error;
753 vector< _SolidData > _sdVec;
756 //--------------------------------------------------------------------------------
758 * \brief Shrinker of nodes on the EDGE
762 vector<double> _initU;
763 vector<double> _normPar;
764 vector<const SMDS_MeshNode*> _nodes;
765 const _LayerEdge* _edges[2];
768 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
769 void Compute(bool set3D, SMESH_MesherHelper& helper);
770 void RestoreParams();
771 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
773 //--------------------------------------------------------------------------------
775 * \brief Class of temporary mesh face.
776 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
777 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
779 struct _TmpMeshFace : public SMDS_MeshElement
781 vector<const SMDS_MeshNode* > _nn;
782 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
783 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
784 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
785 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
786 virtual vtkIdType GetVtkType() const { return -1; }
787 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
788 virtual SMDSAbs_GeometryType GetGeomType() const
789 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
790 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
791 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
793 //--------------------------------------------------------------------------------
795 * \brief Class of temporary mesh face storing _LayerEdge it's based on
797 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
799 _LayerEdge *_le1, *_le2;
800 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
801 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
803 _nn[0]=_le1->_nodes[0];
804 _nn[1]=_le1->_nodes.back();
805 _nn[2]=_le2->_nodes.back();
806 _nn[3]=_le2->_nodes[0];
809 //--------------------------------------------------------------------------------
811 * \brief Retriever of node coordinates either directly of from a surface by node UV.
812 * \warning Location of a surface is ignored
814 struct _NodeCoordHelper
816 SMESH_MesherHelper& _helper;
817 const TopoDS_Face& _face;
818 Handle(Geom_Surface) _surface;
819 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
821 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
822 : _helper( helper ), _face( F )
827 _surface = BRep_Tool::Surface( _face, loc );
829 if ( _surface.IsNull() )
830 _fun = & _NodeCoordHelper::direct;
832 _fun = & _NodeCoordHelper::byUV;
834 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
837 gp_XYZ direct(const SMDS_MeshNode* n) const
839 return SMESH_TNodeXYZ( n );
841 gp_XYZ byUV (const SMDS_MeshNode* n) const
843 gp_XY uv = _helper.GetNodeUV( _face, n );
844 return _surface->Value( uv.X(), uv.Y() ).XYZ();
848 } // namespace VISCOUS_3D
852 //================================================================================
853 // StdMeshers_ViscousLayers hypothesis
855 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
856 :SMESH_Hypothesis(hypId, studyId, gen),
857 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
859 _name = StdMeshers_ViscousLayers::GetHypType();
860 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
861 } // --------------------------------------------------------------------------------
862 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
864 if ( faceIds != _shapeIds )
865 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
866 if ( _isToIgnoreShapes != toIgnore )
867 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
868 } // --------------------------------------------------------------------------------
869 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
871 if ( thickness != _thickness )
872 _thickness = thickness, NotifySubMeshesHypothesisModification();
873 } // --------------------------------------------------------------------------------
874 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
876 if ( _nbLayers != nb )
877 _nbLayers = nb, NotifySubMeshesHypothesisModification();
878 } // --------------------------------------------------------------------------------
879 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
881 if ( _stretchFactor != factor )
882 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
883 } // --------------------------------------------------------------------------------
885 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
886 const TopoDS_Shape& theShape,
887 const bool toMakeN2NMap) const
889 using namespace VISCOUS_3D;
890 _ViscousBuilder bulder;
891 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
892 if ( err && !err->IsOK() )
893 return SMESH_ProxyMesh::Ptr();
895 vector<SMESH_ProxyMesh::Ptr> components;
896 TopExp_Explorer exp( theShape, TopAbs_SOLID );
897 for ( ; exp.More(); exp.Next() )
899 if ( _MeshOfSolid* pm =
900 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
902 if ( toMakeN2NMap && !pm->_n2nMapComputed )
903 if ( !bulder.MakeN2NMap( pm ))
904 return SMESH_ProxyMesh::Ptr();
905 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
906 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
908 if ( pm->_warning && !pm->_warning->IsOK() )
910 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
911 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
912 if ( !smError || smError->IsOK() )
913 smError = pm->_warning;
916 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
918 switch ( components.size() )
922 case 1: return components[0];
924 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
926 return SMESH_ProxyMesh::Ptr();
927 } // --------------------------------------------------------------------------------
928 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
930 save << " " << _nbLayers
932 << " " << _stretchFactor
933 << " " << _shapeIds.size();
934 for ( size_t i = 0; i < _shapeIds.size(); ++i )
935 save << " " << _shapeIds[i];
936 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
938 } // --------------------------------------------------------------------------------
939 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
941 int nbFaces, faceID, shapeToTreat;
942 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
943 while ( _shapeIds.size() < nbFaces && load >> faceID )
944 _shapeIds.push_back( faceID );
945 if ( load >> shapeToTreat )
946 _isToIgnoreShapes = !shapeToTreat;
948 _isToIgnoreShapes = true; // old behavior
950 } // --------------------------------------------------------------------------------
951 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
952 const TopoDS_Shape& theShape)
956 } // --------------------------------------------------------------------------------
957 SMESH_ComputeErrorPtr
958 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
959 const TopoDS_Shape& theShape,
960 SMESH_Hypothesis::Hypothesis_Status& theStatus)
962 VISCOUS_3D::_ViscousBuilder bulder;
963 SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
964 if ( err && !err->IsOK() )
965 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
967 theStatus = SMESH_Hypothesis::HYP_OK;
971 // --------------------------------------------------------------------------------
972 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
975 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
976 return IsToIgnoreShapes() ? !isIn : isIn;
978 // END StdMeshers_ViscousLayers hypothesis
979 //================================================================================
983 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
987 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
988 gp_Pnt p = BRep_Tool::Pnt( fromV );
989 double distF = p.SquareDistance( c->Value( f ));
990 double distL = p.SquareDistance( c->Value( l ));
991 c->D1(( distF < distL ? f : l), p, dir );
992 if ( distL < distF ) dir.Reverse();
995 //--------------------------------------------------------------------------------
996 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
997 SMESH_MesherHelper& helper)
1000 double f,l; gp_Pnt p;
1001 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1002 if ( c.IsNull() ) return gp_XYZ( 1e100, 1e100, 1e100 );
1003 double u = helper.GetNodeU( E, atNode );
1007 //--------------------------------------------------------------------------------
1008 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1009 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1011 //--------------------------------------------------------------------------------
1012 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1013 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1016 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1019 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1020 return getFaceDir( F, v, node, helper, ok );
1022 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1023 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1024 gp_Pnt p; gp_Vec du, dv, norm;
1025 surface->D1( uv.X(),uv.Y(), p, du,dv );
1028 double u = helper.GetNodeU( fromE, node, 0, &ok );
1030 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1031 if ( o == TopAbs_REVERSED )
1034 gp_Vec dir = norm ^ du;
1036 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1037 helper.IsClosedEdge( fromE ))
1039 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1040 else c->D1( f, p, dv );
1041 if ( o == TopAbs_REVERSED )
1043 gp_Vec dir2 = norm ^ dv;
1044 dir = dir.Normalized() + dir2.Normalized();
1048 //--------------------------------------------------------------------------------
1049 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1050 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1051 bool& ok, double* cosin)
1053 TopoDS_Face faceFrw = F;
1054 faceFrw.Orientation( TopAbs_FORWARD );
1055 double f,l; TopLoc_Location loc;
1056 TopoDS_Edge edges[2]; // sharing a vertex
1059 TopoDS_Vertex VV[2];
1060 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1061 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1063 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1064 if ( SMESH_Algo::isDegenerated( e )) continue;
1065 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1066 if ( VV[1].IsSame( fromV )) {
1067 nbEdges += edges[ 0 ].IsNull();
1070 else if ( VV[0].IsSame( fromV )) {
1071 nbEdges += edges[ 1 ].IsNull();
1076 gp_XYZ dir(0,0,0), edgeDir[2];
1079 // get dirs of edges going fromV
1081 for ( size_t i = 0; i < nbEdges && ok; ++i )
1083 edgeDir[i] = getEdgeDir( edges[i], fromV );
1084 double size2 = edgeDir[i].SquareModulus();
1085 if (( ok = size2 > numeric_limits<double>::min() ))
1086 edgeDir[i] /= sqrt( size2 );
1088 if ( !ok ) return dir;
1090 // get angle between the 2 edges
1092 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1093 if ( Abs( angle ) < 5 * M_PI/180 )
1095 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1099 dir = edgeDir[0] + edgeDir[1];
1104 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1105 *cosin = Cos( angle );
1108 else if ( nbEdges == 1 )
1110 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1111 if ( cosin ) *cosin = 1.;
1121 //================================================================================
1123 * \brief Finds concave VERTEXes of a FACE
1125 //================================================================================
1127 bool getConcaveVertices( const TopoDS_Face& F,
1128 SMESH_MesherHelper& helper,
1129 set< TGeomID >* vertices = 0)
1131 // check angles at VERTEXes
1133 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1134 for ( size_t iW = 0; iW < wires.size(); ++iW )
1136 const int nbEdges = wires[iW]->NbEdges();
1137 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1139 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1141 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1142 int iE2 = ( iE1 + 1 ) % nbEdges;
1143 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1144 iE2 = ( iE2 + 1 ) % nbEdges;
1145 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1146 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1147 wires[iW]->Edge( iE2 ), F, V );
1148 if ( angle < -5. * M_PI / 180. )
1152 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1156 return vertices ? !vertices->empty() : false;
1159 //================================================================================
1161 * \brief Returns true if a FACE is bound by a concave EDGE
1163 //================================================================================
1165 bool isConcave( const TopoDS_Face& F,
1166 SMESH_MesherHelper& helper,
1167 set< TGeomID >* vertices = 0 )
1169 bool isConcv = false;
1170 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1172 gp_Vec2d drv1, drv2;
1174 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1175 for ( ; eExp.More(); eExp.Next() )
1177 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1178 if ( SMESH_Algo::isDegenerated( E )) continue;
1179 // check if 2D curve is concave
1180 BRepAdaptor_Curve2d curve( E, F );
1181 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1182 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1183 curve.Intervals( intervals, GeomAbs_C2 );
1184 bool isConvex = true;
1185 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1187 double u1 = intervals( i );
1188 double u2 = intervals( i+1 );
1189 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1190 double cross = drv2 ^ drv1;
1191 if ( E.Orientation() == TopAbs_REVERSED )
1193 isConvex = ( cross > 0.1 ); //-1e-9 );
1197 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1206 // check angles at VERTEXes
1207 if ( getConcaveVertices( F, helper, vertices ))
1213 //================================================================================
1215 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1216 * \param [in] face - the mesh face to treat
1217 * \param [in] nodeOnEdge - a node on the EDGE
1218 * \param [out] faceSize - the computed distance
1219 * \return bool - true if faceSize computed
1221 //================================================================================
1223 bool getDistFromEdge( const SMDS_MeshElement* face,
1224 const SMDS_MeshNode* nodeOnEdge,
1227 faceSize = Precision::Infinite();
1230 int nbN = face->NbCornerNodes();
1231 int iOnE = face->GetNodeIndex( nodeOnEdge );
1232 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1233 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1234 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1235 face->GetNode( iNext[1] ) };
1236 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1237 double segLen = -1.;
1238 // look for two neighbor not in-FACE nodes of face
1239 for ( int i = 0; i < 2; ++i )
1241 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1242 nNext[i]->GetID() < nodeOnEdge->GetID() )
1244 // look for an in-FACE node
1245 for ( int iN = 0; iN < nbN; ++iN )
1247 if ( iN == iOnE || iN == iNext[i] )
1249 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1250 gp_XYZ v = pInFace - segEnd;
1253 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1254 segLen = segVec.Modulus();
1256 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1257 faceSize = Min( faceSize, distToSeg );
1266 //--------------------------------------------------------------------------------
1267 // DEBUG. Dump intermediate node positions into a python script
1268 // HOWTO use: run python commands written in a console to see
1269 // construction steps of viscous layers
1274 PyDump(SMESH_Mesh& m) {
1275 int tag = 3 + m.GetId();
1276 const char* fname = "/tmp/viscous.py";
1277 cout << "execfile('"<<fname<<"')"<<endl;
1278 py = new ofstream(fname);
1279 *py << "import SMESH" << endl
1280 << "from salome.smesh import smeshBuilder" << endl
1281 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1282 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1283 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1288 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1289 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1290 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1291 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1295 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1297 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1298 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1299 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1300 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1301 void _dumpFunction(const string& fun, int ln)
1302 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1303 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1304 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1305 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1306 void _dumpCmd(const string& txt, int ln)
1307 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1308 void dumpFunctionEnd()
1309 { if (py) *py<< " return"<< endl; }
1310 void dumpChangeNodes( const SMDS_MeshElement* f )
1311 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1312 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1313 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1314 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1316 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1317 #define dumpFunction(f) f
1319 #define dumpMoveComm(n,txt)
1320 #define dumpCmd(txt)
1321 #define dumpFunctionEnd()
1322 #define dumpChangeNodes(f)
1323 #define debugMsg( txt ) {}
1327 using namespace VISCOUS_3D;
1329 //================================================================================
1331 * \brief Constructor of _ViscousBuilder
1333 //================================================================================
1335 _ViscousBuilder::_ViscousBuilder()
1337 _error = SMESH_ComputeError::New(COMPERR_OK);
1341 //================================================================================
1343 * \brief Stores error description and returns false
1345 //================================================================================
1347 bool _ViscousBuilder::error(const string& text, int solidId )
1349 const string prefix = string("Viscous layers builder: ");
1350 _error->myName = COMPERR_ALGO_FAILED;
1351 _error->myComment = prefix + text;
1354 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1355 if ( !sm && !_sdVec.empty() )
1356 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1357 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1359 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1360 if ( smError && smError->myAlgo )
1361 _error->myAlgo = smError->myAlgo;
1363 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1365 // set KO to all solids
1366 for ( size_t i = 0; i < _sdVec.size(); ++i )
1368 if ( _sdVec[i]._index == solidId )
1370 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1371 if ( !sm->IsEmpty() )
1373 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1374 if ( !smError || smError->IsOK() )
1376 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1377 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1381 makeGroupOfLE(); // debug
1386 //================================================================================
1388 * \brief At study restoration, restore event listeners used to clear an inferior
1389 * dim sub-mesh modified by viscous layers
1391 //================================================================================
1393 void _ViscousBuilder::RestoreListeners()
1398 //================================================================================
1400 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1402 //================================================================================
1404 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1406 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1407 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1408 for ( ; fExp.More(); fExp.Next() )
1410 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1411 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1413 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1415 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1418 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1419 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1421 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1422 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1423 while( prxIt->more() )
1425 const SMDS_MeshElement* fSrc = srcIt->next();
1426 const SMDS_MeshElement* fPrx = prxIt->next();
1427 if ( fSrc->NbNodes() != fPrx->NbNodes())
1428 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1429 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1430 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1433 pm->_n2nMapComputed = true;
1437 //================================================================================
1439 * \brief Does its job
1441 //================================================================================
1443 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1444 const TopoDS_Shape& theShape)
1446 // TODO: set priority of solids during Gen::Compute()
1450 // check if proxy mesh already computed
1451 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1453 return error("No SOLID's in theShape"), _error;
1455 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1456 return SMESH_ComputeErrorPtr(); // everything already computed
1458 PyDump debugDump( theMesh );
1460 // TODO: ignore already computed SOLIDs
1461 if ( !findSolidsWithLayers())
1464 if ( !findFacesWithLayers() )
1467 for ( size_t i = 0; i < _sdVec.size(); ++i )
1469 if ( ! makeLayer(_sdVec[i]) )
1472 if ( _sdVec[i]._edges.size() == 0 )
1475 if ( ! inflate(_sdVec[i]) )
1478 if ( ! refine(_sdVec[i]) )
1484 addBoundaryElements();
1486 makeGroupOfLE(); // debug
1492 //================================================================================
1494 * \brief Check validity of hypotheses
1496 //================================================================================
1498 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1499 const TopoDS_Shape& shape )
1503 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1504 return SMESH_ComputeErrorPtr(); // everything already computed
1507 findSolidsWithLayers();
1508 bool ok = findFacesWithLayers();
1510 // remove _MeshOfSolid's of _SolidData's
1511 for ( size_t i = 0; i < _sdVec.size(); ++i )
1512 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1517 return SMESH_ComputeErrorPtr();
1520 //================================================================================
1522 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1524 //================================================================================
1526 bool _ViscousBuilder::findSolidsWithLayers()
1529 TopTools_IndexedMapOfShape allSolids;
1530 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1531 _sdVec.reserve( allSolids.Extent());
1533 SMESH_Gen* gen = _mesh->GetGen();
1534 SMESH_HypoFilter filter;
1535 for ( int i = 1; i <= allSolids.Extent(); ++i )
1537 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1538 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1539 if ( !algo ) continue;
1540 // TODO: check if algo is hidden
1541 const list <const SMESHDS_Hypothesis *> & allHyps =
1542 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1543 _SolidData* soData = 0;
1544 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1545 const StdMeshers_ViscousLayers* viscHyp = 0;
1546 for ( ; hyp != allHyps.end(); ++hyp )
1547 if ( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp ))
1549 TopoDS_Shape hypShape;
1550 filter.Init( filter.Is( viscHyp ));
1551 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1555 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1558 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1559 soData = & _sdVec.back();
1560 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1562 soData->_hyps.push_back( viscHyp );
1563 soData->_hypShapes.push_back( hypShape );
1566 if ( _sdVec.empty() )
1568 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1573 //================================================================================
1577 //================================================================================
1579 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1581 SMESH_MesherHelper helper( *_mesh );
1582 TopExp_Explorer exp;
1583 TopTools_IndexedMapOfShape solids;
1585 // collect all faces to ignore defined by hyp
1586 for ( size_t i = 0; i < _sdVec.size(); ++i )
1588 solids.Add( _sdVec[i]._solid );
1590 // get faces to ignore defined by each hyp
1591 typedef const StdMeshers_ViscousLayers* THyp;
1592 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1593 list< TFacesOfHyp > ignoreFacesOfHyps;
1594 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
1595 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1596 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1598 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1599 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1602 // fill _SolidData::_face2hyp and check compatibility of hypotheses
1603 const int nbHyps = _sdVec[i]._hyps.size();
1606 // check if two hypotheses define different parameters for the same FACE
1607 list< TFacesOfHyp >::iterator igFacesOfHyp;
1608 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1610 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1612 igFacesOfHyp = ignoreFacesOfHyps.begin();
1613 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1614 if ( ! igFacesOfHyp->first.count( faceID ))
1617 return error(SMESH_Comment("Several hypotheses define "
1618 "Viscous Layers on the face #") << faceID );
1619 hyp = igFacesOfHyp->second;
1622 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
1624 _sdVec[i]._ignoreFaceIds.insert( faceID );
1627 // check if two hypotheses define different number of viscous layers for
1628 // adjacent faces of a solid
1629 set< int > nbLayersSet;
1630 igFacesOfHyp = ignoreFacesOfHyps.begin();
1631 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1633 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
1635 if ( nbLayersSet.size() > 1 )
1637 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
1639 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
1640 THyp hyp1 = 0, hyp2 = 0;
1641 while( const TopoDS_Shape* face = fIt->next() )
1643 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
1644 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
1645 if ( f2h != _sdVec[i]._face2hyp.end() )
1647 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
1650 if ( hyp1 && hyp2 &&
1651 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
1653 return error("Two hypotheses define different number of "
1654 "viscous layers on adjacent faces");
1658 } // if ( nbHyps > 1 )
1661 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
1665 if ( onlyWith ) // is called to check hypotheses compatibility only
1668 // fill _SolidData::_reversedFaceIds
1669 for ( size_t i = 0; i < _sdVec.size(); ++i )
1671 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1672 for ( ; exp.More(); exp.Next() )
1674 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1675 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
1676 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
1677 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
1678 helper.IsReversedSubMesh( face ))
1680 _sdVec[i]._reversedFaceIds.insert( faceID );
1685 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1686 TopTools_IndexedMapOfShape shapes;
1687 for ( size_t i = 0; i < _sdVec.size(); ++i )
1690 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1691 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1693 const TopoDS_Shape& edge = shapes(iE);
1694 // find 2 faces sharing an edge
1696 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1697 while ( fIt->more())
1699 const TopoDS_Shape* f = fIt->next();
1700 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1701 FF[ int( !FF[0].IsNull()) ] = *f;
1703 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1704 // check presence of layers on them
1706 for ( int j = 0; j < 2; ++j )
1707 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1708 if ( ignore[0] == ignore[1] )
1709 continue; // nothing interesting
1710 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1711 // check presence of layers on fWOL within an adjacent SOLID
1712 bool collision = false;
1713 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1714 while ( const TopoDS_Shape* solid = sIt->next() )
1715 if ( !solid->IsSame( _sdVec[i]._solid ))
1717 int iSolid = solids.FindIndex( *solid );
1718 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1719 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1721 //_sdVec[i]._noShrinkShapes.insert( iFace );
1727 if ( !fWOL.IsNull())
1729 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1730 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1733 // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
1734 // on the edge but shrink won't be performed
1735 _sdVec[i]._noShrinkShapes.insert( edgeInd );
1740 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1741 // the algo of the SOLID sharing the FACE does not support it
1742 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1743 for ( size_t i = 0; i < _sdVec.size(); ++i )
1745 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1746 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1748 const TopoDS_Shape& fWOL = e2f->second;
1749 const TGeomID edgeID = e2f->first;
1750 bool notShrinkFace = false;
1751 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1752 while ( soIt->more() )
1754 const TopoDS_Shape* solid = soIt->next();
1755 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1756 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1757 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1758 notShrinkFace = true;
1760 for ( ; iSolid < _sdVec.size(); ++iSolid )
1762 if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
1763 if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
1764 notShrinkFace = false;
1768 if ( notShrinkFace )
1770 _sdVec[i]._noShrinkShapes.insert( edgeID );
1772 // add VERTEXes of the edge in _noShrinkShapes
1773 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
1774 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
1775 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
1777 // check if there is a collision with to-shrink-from EDGEs in iSolid
1778 if ( iSolid == _sdVec.size() )
1779 continue; // no VL in the solid
1781 TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
1782 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1784 const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
1785 const TGeomID eID = getMeshDS()->ShapeToIndex( E );
1786 if ( eID == edgeID ||
1787 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
1788 _sdVec[i]._noShrinkShapes.count( eID ))
1790 for ( int is1st = 0; is1st < 2; ++is1st )
1792 TopoDS_Vertex V = helper.IthVertex( is1st, E );
1793 if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
1795 // _sdVec[i]._noShrinkShapes.insert( eID );
1796 // V = helper.IthVertex( !is1st, E );
1797 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
1798 //iE = 0; // re-start the loop on EDGEs of fWOL
1799 return error("No way to make a conformal mesh with "
1800 "the given set of faces with layers", _sdVec[i]._index);
1806 } // while ( soIt->more() )
1807 } // loop on _sdVec[i]._shrinkShape2Shape
1808 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
1810 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1812 for ( size_t i = 0; i < _sdVec.size(); ++i )
1815 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1816 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1818 const TopoDS_Shape& vertex = shapes(iV);
1819 // find faces WOL sharing the vertex
1820 vector< TopoDS_Shape > facesWOL;
1821 int totalNbFaces = 0;
1822 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1823 while ( fIt->more())
1825 const TopoDS_Shape* f = fIt->next();
1826 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1829 const int fID = getMeshDS()->ShapeToIndex( *f );
1830 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
1831 !_sdVec[i]._noShrinkShapes.count( fID )*/)
1832 facesWOL.push_back( *f );
1835 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1836 continue; // no layers at this vertex or no WOL
1837 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1838 switch ( facesWOL.size() )
1842 helper.SetSubShape( facesWOL[0] );
1843 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1845 TopoDS_Shape seamEdge;
1846 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1847 while ( eIt->more() && seamEdge.IsNull() )
1849 const TopoDS_Shape* e = eIt->next();
1850 if ( helper.IsRealSeam( *e ) )
1853 if ( !seamEdge.IsNull() )
1855 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1859 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1864 // find an edge shared by 2 faces
1865 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1866 while ( eIt->more())
1868 const TopoDS_Shape* e = eIt->next();
1869 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1870 helper.IsSubShape( *e, facesWOL[1]))
1872 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1878 return error("Not yet supported case", _sdVec[i]._index);
1883 // add FACEs of other SOLIDs to _ignoreFaceIds
1884 for ( size_t i = 0; i < _sdVec.size(); ++i )
1887 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1889 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1891 if ( !shapes.Contains( exp.Current() ))
1892 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1899 //================================================================================
1901 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
1903 //================================================================================
1905 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
1906 const StdMeshers_ViscousLayers* hyp,
1907 const TopoDS_Shape& hypShape,
1908 set<TGeomID>& ignoreFaceIds)
1910 TopExp_Explorer exp;
1912 vector<TGeomID> ids = hyp->GetBndShapes();
1913 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1915 for ( size_t ii = 0; ii < ids.size(); ++ii )
1917 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1918 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1919 ignoreFaceIds.insert( ids[ii] );
1922 else // FACEs with layers are given
1924 exp.Init( solid, TopAbs_FACE );
1925 for ( ; exp.More(); exp.Next() )
1927 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1928 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1929 ignoreFaceIds.insert( faceInd );
1933 // ignore internal FACEs if inlets and outlets are specified
1934 if ( hyp->IsToIgnoreShapes() )
1936 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1937 TopExp::MapShapesAndAncestors( hypShape,
1938 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1940 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
1942 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1943 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1946 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1948 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
1953 //================================================================================
1955 * \brief Create the inner surface of the viscous layer and prepare data for infation
1957 //================================================================================
1959 bool _ViscousBuilder::makeLayer(_SolidData& data)
1961 // get all sub-shapes to make layers on
1962 set<TGeomID> subIds, faceIds;
1963 subIds = data._noShrinkShapes;
1964 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1965 for ( ; exp.More(); exp.Next() )
1967 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1968 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
1969 faceIds.insert( fSubM->GetId() );
1970 SMESH_subMeshIteratorPtr subIt = fSubM->getDependsOnIterator(/*includeSelf=*/true);
1971 while ( subIt->more() )
1972 subIds.insert( subIt->next()->GetId() );
1975 // make a map to find new nodes on sub-shapes shared with other SOLID
1976 map< TGeomID, TNode2Edge* >::iterator s2ne;
1977 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1978 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1980 TGeomID shapeInd = s2s->first;
1981 for ( size_t i = 0; i < _sdVec.size(); ++i )
1983 if ( _sdVec[i]._index == data._index ) continue;
1984 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1985 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1986 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1988 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1994 // Create temporary faces and _LayerEdge's
1996 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1998 data._stepSize = Precision::Infinite();
1999 data._stepSizeNodes[0] = 0;
2001 SMESH_MesherHelper helper( *_mesh );
2002 helper.SetSubShape( data._solid );
2003 helper.SetElementsOnShape( true );
2005 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2006 TNode2Edge::iterator n2e2;
2008 // collect _LayerEdge's of shapes they are based on
2009 const int nbShapes = getMeshDS()->MaxShapeIndex();
2010 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
2012 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2014 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
2015 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2017 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2018 SMESH_ProxyMesh::SubMesh* proxySub =
2019 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2021 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2022 while ( eIt->more() )
2024 const SMDS_MeshElement* face = eIt->next();
2025 double faceMaxCosin = -1;
2026 _LayerEdge* maxCosinEdge = 0;
2027 int nbDegenNodes = 0;
2029 newNodes.resize( face->NbCornerNodes() );
2030 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2032 const SMDS_MeshNode* n = face->GetNode( i );
2033 const int shapeID = n->getshapeId();
2034 const bool onDegenShap = helper.IsDegenShape( shapeID );
2035 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2040 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2041 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2042 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2043 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2053 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2054 if ( !(*n2e).second )
2057 _LayerEdge* edge = new _LayerEdge();
2058 edge->_nodes.push_back( n );
2060 edgesByGeom[ shapeID ].push_back( edge );
2061 const bool noShrink = data._noShrinkShapes.count( shapeID );
2063 SMESH_TNodeXYZ xyz( n );
2065 // set edge data or find already refined _LayerEdge and get data from it
2066 if (( !noShrink ) &&
2067 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2068 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2069 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2071 _LayerEdge* foundEdge = (*n2e2).second;
2072 gp_XYZ lastPos = edge->Copy( *foundEdge, helper );
2073 foundEdge->_pos.push_back( lastPos );
2074 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2075 const_cast< SMDS_MeshNode* >
2076 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2082 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2084 if ( !setEdgeData( *edge, subIds, helper, data ))
2087 dumpMove(edge->_nodes.back());
2089 if ( edge->_cosin > faceMaxCosin )
2091 faceMaxCosin = edge->_cosin;
2092 maxCosinEdge = edge;
2095 newNodes[ i ] = n2e->second->_nodes.back();
2098 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2100 if ( newNodes.size() - nbDegenNodes < 2 )
2103 // create a temporary face
2104 const SMDS_MeshElement* newFace =
2105 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
2106 proxySub->AddElement( newFace );
2108 // compute inflation step size by min size of element on a convex surface
2109 if ( faceMaxCosin > theMinSmoothCosin )
2110 limitStepSize( data, face, maxCosinEdge );
2112 } // loop on 2D elements on a FACE
2113 } // loop on FACEs of a SOLID
2115 data._epsilon = 1e-7;
2116 if ( data._stepSize < 1. )
2117 data._epsilon *= data._stepSize;
2119 // Put _LayerEdge's into the vector data._edges
2120 if ( !sortEdges( data, edgesByGeom ))
2123 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2124 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2126 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2127 TNode2Edge::iterator n2e;
2128 const SMDS_MeshNode* nn[2];
2129 for ( size_t i = 0; i < data._edges.size(); ++i )
2131 _LayerEdge* edge = data._edges[i];
2132 if ( edge->IsOnEdge() )
2134 // get neighbor nodes
2135 bool hasData = ( edge->_2neibors->_edges[0] );
2136 if ( hasData ) // _LayerEdge is a copy of another one
2138 nn[0] = edge->_2neibors->srcNode(0);
2139 nn[1] = edge->_2neibors->srcNode(1);
2141 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], data ))
2145 // set neighbor _LayerEdge's
2146 for ( int j = 0; j < 2; ++j )
2148 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2149 return error("_LayerEdge not found by src node", data._index);
2150 edge->_2neibors->_edges[j] = n2e->second;
2153 edge->SetDataByNeighbors( nn[0], nn[1], helper);
2156 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2158 _Simplex& s = edge->_simplices[j];
2159 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2160 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2163 // For an _LayerEdge on a degenerated EDGE, copy some data from
2164 // a corresponding _LayerEdge on a VERTEX
2165 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2166 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2168 // Generally we should not get here
2169 const TopoDS_Shape& E = getMeshDS()->IndexToShape( edge->_nodes[0]->getshapeId() );
2170 if ( E.ShapeType() != TopAbs_EDGE )
2172 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2173 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2174 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2176 const _LayerEdge* vEdge = n2e->second;
2177 edge->_normal = vEdge->_normal;
2178 edge->_lenFactor = vEdge->_lenFactor;
2179 edge->_cosin = vEdge->_cosin;
2183 // fix _LayerEdge::_2neibors on EDGEs to smooth
2184 map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2185 for ( ; e2c != data._edge2curve.end(); ++e2c )
2186 if ( !e2c->second.IsNull() )
2188 size_t iEdgeEnd; int iBeg, iEnd;
2189 if ( data.GetShapeEdges( e2c->first, iEdgeEnd, &iBeg, &iEnd ))
2190 data.Sort2NeiborsOnEdge( iBeg, iEnd );
2197 //================================================================================
2199 * \brief Compute inflation step size by min size of element on a convex surface
2201 //================================================================================
2203 void _ViscousBuilder::limitStepSize( _SolidData& data,
2204 const SMDS_MeshElement* face,
2205 const _LayerEdge* maxCosinEdge )
2208 double minSize = 10 * data._stepSize;
2209 const int nbNodes = face->NbCornerNodes();
2210 for ( int i = 0; i < nbNodes; ++i )
2212 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2213 const SMDS_MeshNode* curN = face->GetNode( i );
2214 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2215 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2217 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2218 if ( dist < minSize )
2219 minSize = dist, iN = i;
2222 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2223 if ( newStep < data._stepSize )
2225 data._stepSize = newStep;
2226 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2227 data._stepSizeNodes[0] = face->GetNode( iN );
2228 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2232 //================================================================================
2234 * \brief Compute inflation step size by min size of element on a convex surface
2236 //================================================================================
2238 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2240 if ( minSize < data._stepSize )
2242 data._stepSize = minSize;
2243 if ( data._stepSizeNodes[0] )
2246 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2247 data._stepSizeCoeff = data._stepSize / dist;
2252 //================================================================================
2254 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2256 //================================================================================
2258 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2260 const int nbTestPnt = 5; // on a FACE sub-shape
2262 BRepLProp_SLProps surfProp( 2, 1e-6 );
2263 SMESH_MesherHelper helper( *_mesh );
2265 data._convexFaces.clear();
2267 TopExp_Explorer face( data._solid, TopAbs_FACE );
2268 for ( ; face.More(); face.Next() )
2270 const TopoDS_Face& F = TopoDS::Face( face.Current() );
2271 SMESH_subMesh * sm = _mesh->GetSubMesh( F );
2272 const TGeomID faceID = sm->GetId();
2273 if ( data._ignoreFaceIds.count( faceID )) continue;
2275 BRepAdaptor_Surface surface( F, false );
2276 surfProp.SetSurface( surface );
2278 bool isTooCurved = false;
2281 _ConvexFace cnvFace;
2282 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2283 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2284 while ( smIt->more() )
2287 const TGeomID subID = sm->GetId();
2288 // find _LayerEdge's of a sub-shape
2290 if ( data.GetShapeEdges( subID, edgesEnd, &iBeg, &iEnd ))
2291 cnvFace._subIdToEdgeEnd.insert( make_pair( subID, edgesEnd ));
2294 // check concavity and curvature and limit data._stepSize
2295 const double minCurvature =
2296 1. / ( data._hypOnShape[ edgesEnd ].GetTotalThickness() * ( 1+theThickToIntersection ));
2297 int nbLEdges = iEnd - iBeg;
2298 int iStep = Max( 1, nbLEdges / nbTestPnt );
2299 for ( ; iBeg < iEnd; iBeg += iStep )
2301 gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
2302 surfProp.SetParameters( uv.X(), uv.Y() );
2303 if ( !surfProp.IsCurvatureDefined() )
2305 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2307 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2310 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2312 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2316 } // loop on sub-shapes of the FACE
2318 if ( !isTooCurved ) continue;
2320 _ConvexFace & convFace =
2321 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2324 convFace._normalsFixed = false;
2326 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2327 // prism distortion.
2328 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
2329 if ( id2end != convFace._subIdToEdgeEnd.end() )
2331 // there are _LayerEdge's on the FACE it-self;
2332 // select _LayerEdge's near EDGEs
2333 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2334 for ( ; iBeg < iEnd; ++iBeg )
2336 _LayerEdge* ledge = data._edges[ iBeg ];
2337 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2338 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2340 convFace._simplexTestEdges.push_back( ledge );
2347 // where there are no _LayerEdge's on a _ConvexFace,
2348 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2349 // so that collision of viscous internal faces is not detected by check of
2350 // intersection of _LayerEdge's with the viscous internal faces.
2352 set< const SMDS_MeshNode* > usedNodes;
2354 // look for _LayerEdge's with null _sWOL
2355 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
2356 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
2358 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2359 if ( iBeg >= iEnd || !data._edges[ iBeg ]->_sWOL.IsNull() )
2361 for ( ; iBeg < iEnd; ++iBeg )
2363 _LayerEdge* ledge = data._edges[ iBeg ];
2364 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2365 if ( !usedNodes.insert( srcNode ).second ) continue;
2367 _Simplex::GetSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
2368 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2370 usedNodes.insert( ledge->_simplices[i]._nPrev );
2371 usedNodes.insert( ledge->_simplices[i]._nNext );
2373 convFace._simplexTestEdges.push_back( ledge );
2377 } // loop on FACEs of data._solid
2380 //================================================================================
2382 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
2384 //================================================================================
2386 bool _ViscousBuilder::sortEdges( _SolidData& data,
2387 vector< vector<_LayerEdge*> >& edgesByGeom)
2389 // define allowed thickness
2390 computeGeomSize( data ); // compute data._geomSize
2392 data._maxThickness = 0;
2393 data._minThickness = 1e100;
2394 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2395 for ( ; hyp != data._hyps.end(); ++hyp )
2397 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2398 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2400 const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2402 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2403 // boundry inclined to the shape at a sharp angle
2405 list< TGeomID > shapesToSmooth;
2406 TopTools_MapOfShape edgesOfSmooFaces;
2408 SMESH_MesherHelper helper( *_mesh );
2411 for ( int isEdge = 0; isEdge < 2; ++isEdge ) // loop on [ FACEs, EDGEs ]
2413 const int dim = isEdge ? 1 : 2;
2415 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2417 vector<_LayerEdge*>& eS = edgesByGeom[iS];
2418 if ( eS.empty() ) continue;
2419 if ( eS[0]->_nodes[0]->GetPosition()->GetDim() != dim ) continue;
2421 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
2422 bool needSmooth = false;
2423 switch ( S.ShapeType() )
2427 const TopoDS_Edge& E = TopoDS::Edge( S );
2428 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2432 if ( !eS[0]->_sWOL.IsNull() && eS[0]->_sWOL.ShapeType() == TopAbs_FACE )
2433 F = TopoDS::Face( eS[0]->_sWOL );
2435 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
2437 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2438 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
2439 if ( eV.empty() ) continue;
2440 gp_Vec eDir = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
2441 double angle = eDir.Angle( eV[0]->_normal );
2442 double cosin = Cos( angle );
2443 double cosinAbs = Abs( cosin );
2444 if ( cosinAbs > theMinSmoothCosin )
2446 // always smooth analytic EDGEs
2447 needSmooth = ! data.CurveForSmooth( E, 0, eS.size(), F, helper, &eS ).IsNull();
2449 // compare tgtThick with the length of an end segment
2450 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2451 while ( eIt->more() && !needSmooth )
2453 const SMDS_MeshElement* endSeg = eIt->next();
2454 if ( endSeg->getshapeId() == iS )
2457 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2458 needSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2467 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
2469 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2470 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
2471 if ( eE.empty() ) continue;
2472 // TopLoc_Location loc;
2473 // Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( S ), loc );
2474 // bool isPlane = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2475 //if ( eE[0]->_sWOL.IsNull() )
2478 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2479 if ( eE[i]->_cosin > theMinSmoothCosin )
2481 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2482 while ( fIt->more() && !needSmooth )
2484 const SMDS_MeshElement* face = fIt->next();
2485 if ( getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2486 needSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2492 // const TopoDS_Face& F1 = TopoDS::Face( S );
2493 // const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
2494 // const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
2495 // for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2497 // gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
2498 // gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
2499 // double angle = dir1.Angle( );
2500 // double cosin = cos( angle );
2501 // needSmooth = ( cosin > theMinSmoothCosin );
2506 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More(); eExp.Next() )
2507 edgesOfSmooFaces.Add( eExp.Current() );
2518 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
2519 else shapesToSmooth.push_back ( iS );
2521 // preparation for smoothing
2522 if ( S.ShapeType() == TopAbs_FACE )
2524 data.PrepareEdgesToSmoothOnFace( & eS[0],
2525 & eS[0] + eS.size(),
2527 /*substituteSrcNodes=*/false);
2531 } // loop on edgesByGeom
2532 } // // loop on [ FACEs, EDGEs ]
2534 data._edges.reserve( data._n2eMap.size() );
2535 data._endEdgeOnShape.clear();
2537 // first we put _LayerEdge's on shapes to smooth
2538 data._nbShapesToSmooth = 0;
2539 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
2540 for ( ; gIt != shapesToSmooth.end(); ++gIt )
2542 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
2543 if ( eVec.empty() ) continue;
2544 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2545 data._endEdgeOnShape.push_back( data._edges.size() );
2546 data._nbShapesToSmooth++;
2550 // then the rest _LayerEdge's
2551 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2553 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
2554 if ( eVec.empty() ) continue;
2555 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2556 data._endEdgeOnShape.push_back( data._edges.size() );
2560 // compute average StdMeshers_ViscousLayers parameters for each shape
2562 data._hypOnShape.clear();
2563 if ( data._hyps.size() == 1 )
2565 data._hypOnShape.resize( data._endEdgeOnShape.size(), AverageHyp( data._hyps.back() ));
2569 data._hypOnShape.resize( data._endEdgeOnShape.size() );
2570 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
2571 for ( size_t i = 0; i < data._endEdgeOnShape.size(); ++i )
2573 int iEnd = data._endEdgeOnShape[i];
2574 _LayerEdge* LE = data._edges[ iEnd-1 ];
2575 TGeomID iShape = LE->_nodes[0]->getshapeId();
2576 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iShape );
2577 if ( S.ShapeType() == TopAbs_FACE )
2579 if (( f2hyp = data._face2hyp.find( iShape )) != data._face2hyp.end() )
2581 data._hypOnShape[ i ].Add( f2hyp->second );
2586 PShapeIteratorPtr fIt = SMESH_MesherHelper::GetAncestors( S, *_mesh, TopAbs_FACE );
2587 while ( const TopoDS_Shape* face = fIt->next() )
2589 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2590 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
2592 data._hypOnShape[ i ].Add( f2hyp->second );
2602 //================================================================================
2604 * \brief Set data of _LayerEdge needed for smoothing
2605 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
2607 //================================================================================
2609 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
2610 const set<TGeomID>& subIds,
2611 SMESH_MesherHelper& helper,
2614 SMESH_MeshEditor editor(_mesh);
2616 const SMDS_MeshNode* node = edge._nodes[0]; // source node
2617 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
2621 edge._curvature = 0;
2623 // --------------------------
2624 // Compute _normal and _cosin
2625 // --------------------------
2628 edge._normal.SetCoord(0,0,0);
2630 int totalNbFaces = 0;
2634 const TGeomID shapeInd = node->getshapeId();
2635 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
2636 const bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
2638 if ( onShrinkShape ) // one of faces the node is on has no layers
2640 TopoDS_Shape vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
2641 if ( s2s->second.ShapeType() == TopAbs_EDGE )
2643 // inflate from VERTEX along EDGE
2644 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
2646 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
2648 // inflate from VERTEX along FACE
2649 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
2650 node, helper, normOK, &edge._cosin);
2654 // inflate from EDGE along FACE
2655 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
2656 node, helper, normOK);
2659 else // layers are on all faces of SOLID the node is on
2661 // find indices of geom faces the node lies on
2662 set<TGeomID> faceIds;
2663 if ( posType == SMDS_TOP_FACE )
2665 faceIds.insert( node->getshapeId() );
2669 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2670 while ( fIt->more() )
2671 faceIds.insert( editor.FindShape(fIt->next()));
2674 set<TGeomID>::iterator id = faceIds.begin();
2676 std::pair< TGeomID, gp_XYZ > id2Norm[20];
2677 for ( ; id != faceIds.end(); ++id )
2679 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2680 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2682 F = TopoDS::Face( s );
2683 geomNorm = getFaceNormal( node, F, helper, normOK );
2684 if ( !normOK ) continue;
2686 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2688 id2Norm[ totalNbFaces ].first = *id;
2689 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
2691 edge._normal += geomNorm.XYZ();
2693 if ( totalNbFaces == 0 )
2694 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2696 if ( normOK && edge._normal.Modulus() < 1e-3 && totalNbFaces > 1 )
2698 // opposite normals, re-get normals at shifted positions (IPAL 52426)
2699 edge._normal.SetCoord( 0,0,0 );
2700 for ( int i = 0; i < totalNbFaces; ++i )
2702 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[i].first ));
2703 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2704 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2707 id2Norm[ i ].second = geomNorm.XYZ();
2708 edge._normal += id2Norm[ i ].second;
2712 if ( totalNbFaces < 3 )
2714 //edge._normal /= totalNbFaces;
2718 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
2724 edge._cosin = 0; break;
2726 case SMDS_TOP_EDGE: {
2727 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
2728 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2729 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2730 edge._cosin = Cos( angle );
2731 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2734 case SMDS_TOP_VERTEX: {
2735 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2736 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2737 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2738 edge._cosin = Cos( angle );
2739 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
2740 for ( int iF = totalNbFaces-2; iF >=0; --iF )
2742 F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[ iF ].first ));
2743 inFaceDir = getFaceDir( F, V, node, helper, normOK );
2745 double angle = inFaceDir.Angle( edge._normal );
2746 edge._cosin = Max( edge._cosin, Cos( angle ));
2749 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2753 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2755 } // case _sWOL.IsNull()
2757 double normSize = edge._normal.SquareModulus();
2758 if ( normSize < numeric_limits<double>::min() )
2759 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2761 edge._normal /= sqrt( normSize );
2763 // TODO: if ( !normOK ) then get normal by mesh faces
2765 // Set the rest data
2766 // --------------------
2767 if ( onShrinkShape )
2769 edge._sWOL = (*s2s).second;
2771 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2772 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2773 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2775 // set initial position which is parameters on _sWOL in this case
2776 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2778 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2779 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
2780 if ( edge._nodes.size() > 1 )
2781 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2785 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2786 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2787 if ( edge._nodes.size() > 1 )
2788 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2793 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2795 if ( posType == SMDS_TOP_FACE )
2797 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2801 // Set neighbour nodes for a _LayerEdge based on EDGE
2803 if ( posType == SMDS_TOP_EDGE /*||
2804 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2806 edge._2neibors = new _2NearEdges;
2807 // target node instead of source ones will be set later
2808 // if ( ! findNeiborsOnEdge( &edge,
2809 // edge._2neibors->_nodes[0],
2810 // edge._2neibors->_nodes[1],
2813 // edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2814 // edge._2neibors->_nodes[1],
2818 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2823 //================================================================================
2825 * \brief Return normal to a FACE at a node
2826 * \param [in] n - node
2827 * \param [in] face - FACE
2828 * \param [in] helper - helper
2829 * \param [out] isOK - true or false
2830 * \param [in] shiftInside - to find normal at a position shifted inside the face
2831 * \return gp_XYZ - normal
2833 //================================================================================
2835 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
2836 const TopoDS_Face& face,
2837 SMESH_MesherHelper& helper,
2844 // get a shifted position
2845 gp_Pnt p = SMESH_TNodeXYZ( node );
2846 gp_XYZ shift( 0,0,0 );
2847 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
2848 switch ( S.ShapeType() ) {
2851 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
2856 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
2864 p.Translate( shift * 1e-5 );
2866 TopLoc_Location loc;
2867 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
2869 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
2871 projector.Perform( p );
2872 if ( !projector.IsDone() || projector.NbPoints() < 1 )
2877 Quantity_Parameter U,V;
2878 projector.LowerDistanceParameters(U,V);
2883 uv = helper.GetNodeUV( face, node, 0, &isOK );
2889 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
2890 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
2891 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
2893 if ( pointKind == IMPOSSIBLE &&
2894 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
2896 // probably NormEstim() failed due to a too high tolerance
2897 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
2898 isOK = ( pointKind < IMPOSSIBLE );
2900 if ( pointKind < IMPOSSIBLE )
2902 if ( pointKind != REGULAR &&
2904 node->GetPosition()->GetDim() < 2 ) // FACE boundary
2906 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
2907 if ( normShift * normal.XYZ() < 0. )
2913 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
2915 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
2917 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2918 while ( fIt->more() )
2920 const SMDS_MeshElement* f = fIt->next();
2921 if ( f->getshapeId() == faceID )
2923 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
2926 TopoDS_Face ff = face;
2927 ff.Orientation( TopAbs_FORWARD );
2928 if ( helper.IsReversedSubMesh( ff ))
2935 return normal.XYZ();
2938 //================================================================================
2940 * \brief Return a normal at a node weighted with angles taken by FACEs
2941 * \param [in] n - the node
2942 * \param [in] fId2Normal - FACE ids and normals
2943 * \param [in] nbFaces - nb of FACEs meeting at the node
2944 * \return gp_XYZ - computed normal
2946 //================================================================================
2948 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
2949 std::pair< TGeomID, gp_XYZ > fId2Normal[],
2952 gp_XYZ resNorm(0,0,0);
2953 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2954 if ( V.ShapeType() != TopAbs_VERTEX )
2956 for ( int i = 0; i < nbFaces; ++i )
2957 resNorm += fId2Normal[i].second;
2961 // exclude equal normals
2962 int nbUniqNorms = nbFaces;
2963 for ( int i = 0; i < nbFaces; ++i )
2964 for ( int j = i+1; j < nbFaces; ++j )
2965 if ( fId2Normal[i].second.IsEqual( fId2Normal[j].second, 0.1 ))
2967 fId2Normal[i].second.SetCoord( 0,0,0 );
2971 //if ( nbUniqNorms < 3 )
2973 for ( int i = 0; i < nbFaces; ++i )
2974 resNorm += fId2Normal[i].second;
2979 for ( int i = 0; i < nbFaces; ++i )
2981 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2983 // look for two EDGEs shared by F and other FACEs within fId2Normal
2986 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2987 while ( const TopoDS_Shape* E = eIt->next() )
2989 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2991 bool isSharedEdge = false;
2992 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2994 if ( i == j ) continue;
2995 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2996 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2998 if ( !isSharedEdge )
3000 ee[ nbE ] = TopoDS::Edge( *E );
3001 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
3006 // get an angle between the two EDGEs
3008 if ( nbE < 1 ) continue;
3015 if ( !V.IsSame( SMESH_MesherHelper::IthVertex( 0, ee[ 1 ] )))
3016 std::swap( ee[0], ee[1] );
3018 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F, TopoDS::Vertex( V ));
3021 // compute a weighted normal
3022 double sumAngle = 0;
3023 for ( int i = 0; i < nbFaces; ++i )
3025 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
3026 sumAngle += angles[i];
3028 for ( int i = 0; i < nbFaces; ++i )
3029 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
3034 //================================================================================
3036 * \brief Find 2 neigbor nodes of a node on EDGE
3038 //================================================================================
3040 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
3041 const SMDS_MeshNode*& n1,
3042 const SMDS_MeshNode*& n2,
3045 const SMDS_MeshNode* node = edge->_nodes[0];
3046 const int shapeInd = node->getshapeId();
3047 SMESHDS_SubMesh* edgeSM = 0;
3048 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
3050 edgeSM = getMeshDS()->MeshElements( shapeInd );
3051 if ( !edgeSM || edgeSM->NbElements() == 0 )
3052 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3056 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3057 while ( eIt->more() && !n2 )
3059 const SMDS_MeshElement* e = eIt->next();
3060 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
3061 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3064 if (!edgeSM->Contains(e)) continue;
3068 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
3069 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
3071 ( iN++ ? n2 : n1 ) = nNeibor;
3074 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3078 //================================================================================
3080 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3082 //================================================================================
3084 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3085 const SMDS_MeshNode* n2,
3086 SMESH_MesherHelper& helper)
3088 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
3091 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
3092 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3093 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3097 double sumLen = vec1.Modulus() + vec2.Modulus();
3098 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3099 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3100 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3101 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3102 if ( _curvature ) delete _curvature;
3103 _curvature = _Curvature::New( avgNormProj, avgLen );
3104 // if ( _curvature )
3105 // debugMsg( _nodes[0]->GetID()
3106 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3107 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3108 // << _curvature->lenDelta(0) );
3112 if ( _sWOL.IsNull() )
3114 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
3115 TopoDS_Edge E = TopoDS::Edge( S );
3116 // if ( SMESH_Algo::isDegenerated( E ))
3118 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
3119 gp_XYZ plnNorm = dirE ^ _normal;
3120 double proj0 = plnNorm * vec1;
3121 double proj1 = plnNorm * vec2;
3122 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3124 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3125 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3130 //================================================================================
3132 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3133 * this and other _LayerEdge's are inflated along a FACE or an EDGE
3135 //================================================================================
3137 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
3139 _nodes = other._nodes;
3140 _normal = other._normal;
3142 _lenFactor = other._lenFactor;
3143 _cosin = other._cosin;
3144 _sWOL = other._sWOL;
3145 _2neibors = other._2neibors;
3146 _curvature = 0; std::swap( _curvature, other._curvature );
3147 _2neibors = 0; std::swap( _2neibors, other._2neibors );
3149 gp_XYZ lastPos( 0,0,0 );
3150 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3152 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
3153 _pos.push_back( gp_XYZ( u, 0, 0));
3155 u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
3160 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
3161 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3163 uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
3164 lastPos.SetX( uv.X() );
3165 lastPos.SetY( uv.Y() );
3170 //================================================================================
3172 * \brief Set _cosin and _lenFactor
3174 //================================================================================
3176 void _LayerEdge::SetCosin( double cosin )
3179 cosin = Abs( _cosin );
3180 _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ? 1./sqrt(1-cosin*cosin) : 1.0;
3183 //================================================================================
3185 * \brief Fills a vector<_Simplex >
3187 //================================================================================
3189 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
3190 vector<_Simplex>& simplices,
3191 const set<TGeomID>& ingnoreShapes,
3192 const _SolidData* dataToCheckOri,
3196 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3197 while ( fIt->more() )
3199 const SMDS_MeshElement* f = fIt->next();
3200 const TGeomID shapeInd = f->getshapeId();
3201 if ( ingnoreShapes.count( shapeInd )) continue;
3202 const int nbNodes = f->NbCornerNodes();
3203 const int srcInd = f->GetNodeIndex( node );
3204 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
3205 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
3206 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
3207 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
3208 std::swap( nPrev, nNext );
3209 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
3213 SortSimplices( simplices );
3216 //================================================================================
3218 * \brief Set neighbor simplices side by side
3220 //================================================================================
3222 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
3224 vector<_Simplex> sortedSimplices( simplices.size() );
3225 sortedSimplices[0] = simplices[0];
3227 for ( size_t i = 1; i < simplices.size(); ++i )
3229 for ( size_t j = 1; j < simplices.size(); ++j )
3230 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
3232 sortedSimplices[i] = simplices[j];
3237 if ( nbFound == simplices.size() - 1 )
3238 simplices.swap( sortedSimplices );
3241 //================================================================================
3243 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
3245 //================================================================================
3247 void _ViscousBuilder::makeGroupOfLE()
3250 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3252 if ( _sdVec[i]._edges.empty() ) continue;
3254 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
3255 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
3257 _LayerEdge* le = _sdVec[i]._edges[j];
3258 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
3259 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
3260 << ", " << le->_nodes[iN]->GetID() <<"])");
3264 dumpFunction( SMESH_Comment("makeNormals") << i );
3265 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
3267 _LayerEdge& edge = *_sdVec[i]._edges[j];
3268 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
3269 nXYZ += edge._normal * _sdVec[i]._stepSize;
3270 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
3271 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
3275 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
3276 dumpCmd( "faceId1 = mesh.NbElements()" );
3277 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
3278 for ( ; fExp.More(); fExp.Next() )
3280 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
3282 if ( sm->NbElements() == 0 ) continue;
3283 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3284 while ( fIt->more())
3286 const SMDS_MeshElement* e = fIt->next();
3287 SMESH_Comment cmd("mesh.AddFace([");
3288 for ( int j=0; j < e->NbCornerNodes(); ++j )
3289 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
3294 dumpCmd( "faceId2 = mesh.NbElements()" );
3295 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
3296 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
3297 << "'%s-%s' % (faceId1+1, faceId2))");
3303 //================================================================================
3305 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
3307 //================================================================================
3309 void _ViscousBuilder::computeGeomSize( _SolidData& data )
3311 data._geomSize = Precision::Infinite();
3312 double intersecDist;
3313 auto_ptr<SMESH_ElementSearcher> searcher
3314 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3315 data._proxyMesh->GetFaces( data._solid )) );
3317 TNode2Edge::iterator n2e = data._n2eMap.begin(), n2eEnd = data._n2eMap.end();
3318 for ( ; n2e != n2eEnd; ++n2e )
3320 _LayerEdge* edge = n2e->second;
3321 if ( edge->IsOnEdge() ) continue;
3322 edge->FindIntersection( *searcher, intersecDist, data._epsilon );
3323 if ( data._geomSize > intersecDist && intersecDist > 0 )
3324 data._geomSize = intersecDist;
3328 //================================================================================
3330 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
3332 //================================================================================
3334 bool _ViscousBuilder::inflate(_SolidData& data)
3336 SMESH_MesherHelper helper( *_mesh );
3338 // Limit inflation step size by geometry size found by itersecting
3339 // normals of _LayerEdge's with mesh faces
3340 if ( data._stepSize > 0.3 * data._geomSize )
3341 limitStepSize( data, 0.3 * data._geomSize );
3343 const double tgtThick = data._maxThickness;
3344 if ( data._stepSize > data._minThickness )
3345 limitStepSize( data, data._minThickness );
3347 if ( data._stepSize < 1. )
3348 data._epsilon = data._stepSize * 1e-7;
3350 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
3352 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
3354 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
3355 int nbSteps = 0, nbRepeats = 0;
3357 while ( avgThick < 0.99 )
3359 // new target length
3360 curThick += data._stepSize;
3361 if ( curThick > tgtThick )
3363 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
3367 // Elongate _LayerEdge's
3368 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
3369 for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3371 const double shapeCurThick = Min( curThick, data._hypOnShape[ iS ].GetTotalThickness() );
3372 for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
3374 data._edges[iBeg]->SetNewLength( shapeCurThick, helper );
3379 if ( !updateNormals( data, helper, nbSteps ))
3382 // Improve and check quality
3383 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
3387 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
3388 debugMsg("NOT INVALIDATED STEP!");
3389 return error("Smoothing failed", data._index);
3391 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
3392 for ( size_t i = 0; i < data._edges.size(); ++i )
3394 data._edges[i]->InvalidateStep( nbSteps+1 );
3398 break; // no more inflating possible
3402 // Evaluate achieved thickness
3404 for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3406 const double shapeTgtThick = data._hypOnShape[ iS ].GetTotalThickness();
3407 for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
3409 avgThick += Min( 1., data._edges[iBeg]->_len / shapeTgtThick );
3412 avgThick /= data._edges.size();
3413 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
3415 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
3417 debugMsg( "-- Stop inflation since "
3418 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
3419 << tgtThick * avgThick << " ) * " << safeFactor );
3423 limitStepSize( data, 0.25 * distToIntersection );
3424 if ( data._stepSizeNodes[0] )
3425 data._stepSize = data._stepSizeCoeff *
3426 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3428 } // while ( avgThick < 0.99 )
3431 return error("failed at the very first inflation step", data._index);
3433 if ( avgThick < 0.99 )
3435 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
3437 data._proxyMesh->_warning.reset
3438 ( new SMESH_ComputeError (COMPERR_WARNING,
3439 SMESH_Comment("Thickness ") << tgtThick <<
3440 " of viscous layers not reached,"
3441 " average reached thickness is " << avgThick*tgtThick));
3445 // Restore position of src nodes moved by infaltion on _noShrinkShapes
3446 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
3447 for ( iEnd = iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3450 iEnd = data._endEdgeOnShape[ iS ];
3451 if ( data._edges[ iBeg ]->_nodes.size() == 1 )
3452 for ( ; iBeg < iEnd; ++iBeg )
3454 restoreNoShrink( *data._edges[ iBeg ] );
3462 //================================================================================
3464 * \brief Improve quality of layer inner surface and check intersection
3466 //================================================================================
3468 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
3470 double & distToIntersection)
3472 if ( data._nbShapesToSmooth == 0 )
3473 return true; // no shapes needing smoothing
3475 bool moved, improved;
3477 SMESH_MesherHelper helper(*_mesh);
3478 Handle(Geom_Surface) surface;
3482 for ( int iS = 0; iS < data._nbShapesToSmooth; ++iS )
3485 iEnd = data._endEdgeOnShape[ iS ];
3487 // need to smooth this shape?
3488 bool toSmooth = ( data._hyps.front() == data._hyps.back() );
3489 for ( int i = iBeg; i < iEnd && !toSmooth; ++i )
3490 toSmooth = ( data._edges[ iBeg ]->NbSteps() >= nbSteps+1 );
3493 if ( iS+1 == data._nbShapesToSmooth )
3494 data._nbShapesToSmooth--;
3495 continue; // target length reached some steps before
3499 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
3500 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
3502 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
3503 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
3504 helper.SetSubShape( F );
3505 surface = BRep_Tool::Surface( F );
3510 F.Nullify(); surface.Nullify();
3512 const TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
3514 // perform smoothing
3516 if ( data._edges[ iBeg ]->IsOnEdge() )
3518 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
3520 // try a simple solution on an analytic EDGE
3521 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
3527 for ( int i = iBeg; i < iEnd; ++i )
3529 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
3531 dumpCmd( SMESH_Comment("# end step ")<<step);
3533 while ( moved && step++ < 5 );
3541 const bool isConcaveFace = data._concaveFaces.count( sInd );
3543 int step = 0, stepLimit = 5, badNb = 0; moved = true;
3544 while (( ++step <= stepLimit && moved ) || improved )
3546 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
3547 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
3548 int oldBadNb = badNb;
3552 for ( int i = iBeg; i < iEnd; ++i ) // iterate forward
3553 moved |= data._edges[i]->Smooth( badNb, step, isConcaveFace );
3555 for ( int i = iEnd-1; i >= iBeg; --i ) // iterate backward
3556 moved |= data._edges[i]->Smooth( badNb, step, isConcaveFace );
3557 improved = ( badNb < oldBadNb );
3559 // issue 22576 -- no bad faces but still there are intersections to fix
3560 // if ( improved && badNb == 0 )
3561 // stepLimit = step + 3;
3569 for ( int i = iBeg; i < iEnd; ++i )
3571 _LayerEdge* edge = data._edges[i];
3572 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3573 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3574 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
3576 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3577 << " "<< edge->_simplices[j]._nPrev->GetID()
3578 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
3586 } // loop on shapes to smooth
3588 // Check orientation of simplices of _ConvexFace::_simplexTestEdges
3589 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3590 for ( ; id2face != data._convexFaces.end(); ++id2face )
3592 _ConvexFace & convFace = (*id2face).second;
3593 if ( !convFace._simplexTestEdges.empty() &&
3594 convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
3595 continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
3597 if ( !convFace.CheckPrisms() )
3601 // Check if the last segments of _LayerEdge intersects 2D elements;
3602 // checked elements are either temporary faces or faces on surfaces w/o the layers
3604 auto_ptr<SMESH_ElementSearcher> searcher
3605 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3606 data._proxyMesh->GetFaces( data._solid )) );
3608 distToIntersection = Precision::Infinite();
3610 const SMDS_MeshElement* intFace = 0;
3611 const SMDS_MeshElement* closestFace = 0;
3613 for ( size_t i = 0; i < data._edges.size(); ++i )
3615 if ( !data._edges[i]->_sWOL.IsNull() )
3617 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
3619 if ( distToIntersection > dist )
3621 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
3622 // lying on this _ConvexFace
3623 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
3624 if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
3627 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
3628 // ( avoid limiting the thickness on the case of issue 22576)
3629 if ( intFace->getshapeId() == data._edges[i]->_nodes[0]->getshapeId() )
3632 distToIntersection = dist;
3634 closestFace = intFace;
3640 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
3641 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
3642 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
3643 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3644 << ") distance = " << distToIntersection<< endl;
3651 //================================================================================
3653 * \brief Return a curve of the EDGE to be used for smoothing and arrange
3654 * _LayerEdge's to be in a consequent order
3656 //================================================================================
3658 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
3661 const TopoDS_Face& F,
3662 SMESH_MesherHelper& helper,
3663 vector<_LayerEdge* >* edges)
3665 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
3667 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
3669 if ( i2curve == _edge2curve.end() )
3672 _edges.swap( *edges );
3674 // sort _LayerEdge's by position on the EDGE
3675 SortOnEdge( E, iFrom, iTo, helper );
3677 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
3679 TopLoc_Location loc; double f,l;
3681 Handle(Geom_Line) line;
3682 Handle(Geom_Circle) circle;
3683 bool isLine, isCirc;
3684 if ( F.IsNull() ) // 3D case
3686 // check if the EDGE is a line
3687 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
3688 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
3689 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
3691 line = Handle(Geom_Line)::DownCast( curve );
3692 circle = Handle(Geom_Circle)::DownCast( curve );
3693 isLine = (!line.IsNull());
3694 isCirc = (!circle.IsNull());
3696 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
3699 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3700 while ( nIt->more() )
3701 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
3702 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
3705 if ( iTo-iFrom > 1 ) {
3706 p0 = SMESH_TNodeXYZ( _edges[iFrom]->_nodes[0] );
3707 p1 = SMESH_TNodeXYZ( _edges[iFrom+1]->_nodes[0] );
3710 p0 = curve->Value( f );
3711 p1 = curve->Value( l );
3713 const double lineTol = 1e-2 * p0.Distance( p1 );
3714 for ( int i = 0; i < 3 && !isLine; ++i )
3715 isLine = ( size.Coord( i+1 ) <= lineTol );
3718 line = new Geom_Line( gp::OX() ); // only type does matter
3720 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3727 // check if the EDGE is a line
3728 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
3729 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
3730 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
3732 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
3733 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
3734 isLine = (!line2d.IsNull());
3735 isCirc = (!circle2d.IsNull());
3737 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
3740 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3741 while ( nIt->more() )
3742 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
3743 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
3745 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
3746 for ( int i = 0; i < 2 && !isLine; ++i )
3747 isLine = ( size.Coord( i+1 ) <= lineTol );
3749 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3755 line = new Geom_Line( gp::OX() ); // only type does matter
3759 gp_Pnt2d p = circle2d->Location();
3760 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
3761 circle = new Geom_Circle( ax, 1.); // only center position does matter
3766 _edges.swap( *edges );
3768 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
3776 return i2curve->second;
3779 //================================================================================
3781 * \brief Sort _LayerEdge's by a parameter on a given EDGE
3783 //================================================================================
3785 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
3788 SMESH_MesherHelper& helper)
3790 map< double, _LayerEdge* > u2edge;
3791 for ( int i = iFrom; i < iTo; ++i )
3792 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
3794 ASSERT( u2edge.size() == iTo - iFrom );
3795 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
3796 for ( int i = iFrom; i < iTo; ++i, ++u2e )
3797 _edges[i] = u2e->second;
3799 Sort2NeiborsOnEdge( iFrom, iTo );
3802 //================================================================================
3804 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
3806 //================================================================================
3808 void _SolidData::Sort2NeiborsOnEdge( const int iFrom, const int iTo)
3810 for ( int i = iFrom; i < iTo-1; ++i )
3811 if ( _edges[i]->_2neibors->tgtNode(1) != _edges[i+1]->_nodes.back() )
3812 _edges[i]->_2neibors->reverse();
3813 if ( iTo - iFrom > 1 &&
3814 _edges[iTo-1]->_2neibors->tgtNode(0) != _edges[iTo-2]->_nodes.back() )
3815 _edges[iTo-1]->_2neibors->reverse();
3818 //================================================================================
3820 * \brief Return index corresponding to the shape in _endEdgeOnShape
3822 //================================================================================
3824 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
3829 int beg = 0, end = 0;
3830 for ( iEdgesEnd = 0; iEdgesEnd < _endEdgeOnShape.size(); ++iEdgesEnd )
3832 end = _endEdgeOnShape[ iEdgesEnd ];
3833 TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
3834 if ( sID == shapeID )
3836 if ( iBeg ) *iBeg = beg;
3837 if ( iEnd ) *iEnd = end;
3845 //================================================================================
3847 * \brief Prepare data of the _LayerEdge for smoothing on FACE
3849 //================================================================================
3851 void _SolidData::PrepareEdgesToSmoothOnFace( _LayerEdge** edgeBeg,
3852 _LayerEdge** edgeEnd,
3853 const TopoDS_Face& face,
3854 bool substituteSrcNodes )
3856 set< TGeomID > vertices;
3857 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
3858 if ( isConcave( face, helper, &vertices ))
3859 _concaveFaces.insert( (*edgeBeg)->_nodes[0]->getshapeId() );
3861 for ( _LayerEdge** edge = edgeBeg; edge != edgeEnd; ++edge )
3862 (*edge)->_smooFunction = 0;
3864 for ( ; edgeBeg != edgeEnd; ++edgeBeg )
3866 _LayerEdge* edge = *edgeBeg;
3867 _Simplex::GetSimplices
3868 ( edge->_nodes[0], edge->_simplices, _ignoreFaceIds, this, /*sort=*/true );
3870 edge->ChooseSmooFunction( vertices, _n2eMap );
3872 double avgNormProj = 0, avgLen = 0;
3873 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3875 _Simplex& s = edge->_simplices[i];
3877 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
3878 avgNormProj += edge->_normal * vec;
3879 avgLen += vec.Modulus();
3880 if ( substituteSrcNodes )
3882 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
3883 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
3886 avgNormProj /= edge->_simplices.size();
3887 avgLen /= edge->_simplices.size();
3888 edge->_curvature = _Curvature::New( avgNormProj, avgLen );
3892 //================================================================================
3894 * \brief Add faces for smoothing
3896 //================================================================================
3898 void _SolidData::AddShapesToSmooth( const set< TGeomID >& faceIDs )
3900 // convert faceIDs to indices in _endEdgeOnShape
3901 set< size_t > iEnds;
3903 set< TGeomID >::const_iterator fId = faceIDs.begin();
3904 for ( ; fId != faceIDs.end(); ++fId )
3905 if ( GetShapeEdges( *fId, end ) && end >= _nbShapesToSmooth )
3906 iEnds.insert( end );
3908 set< size_t >::iterator endsIt = iEnds.begin();
3910 // "add" by move of _nbShapesToSmooth
3911 int nbFacesToAdd = iEnds.size();
3912 while ( endsIt != iEnds.end() && *endsIt == _nbShapesToSmooth )
3915 ++_nbShapesToSmooth;
3918 if ( endsIt == iEnds.end() )
3921 // Move _LayerEdge's on FACEs just after _nbShapesToSmooth
3923 vector< _LayerEdge* > nonSmoothLE, smoothLE;
3924 size_t lastSmooth = *iEnds.rbegin();
3926 for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
3928 bool toSmooth = iEnds.count(i);
3929 vector< _LayerEdge* > & edgesVec = toSmooth ? smoothLE : nonSmoothLE;
3930 iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
3931 iEnd = _endEdgeOnShape[ i ];
3932 edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd );
3934 // preparation for smoothing on FACE
3935 if ( toSmooth && _edges[iBeg]->_nodes[0]->GetPosition()->GetDim() == 2 )
3937 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( _edges[iBeg]->_nodes[0],
3938 _proxyMesh->GetMeshDS() );
3939 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
3941 PrepareEdgesToSmoothOnFace( &_edges[ iBeg ],
3944 /*substituteSrcNodes=*/true );
3949 iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
3950 std::copy( smoothLE.begin(), smoothLE.end(), &_edges[ iBeg ] );
3951 std::copy( nonSmoothLE.begin(), nonSmoothLE.end(), &_edges[ iBeg + smoothLE.size()]);
3953 // update _endEdgeOnShape
3954 for ( size_t i = _nbShapesToSmooth; i < _endEdgeOnShape.size(); ++i )
3956 TGeomID curShape = _edges[ iBeg ]->_nodes[0]->getshapeId();
3957 while ( ++iBeg < _edges.size() &&
3958 curShape == _edges[ iBeg ]->_nodes[0]->getshapeId() );
3960 _endEdgeOnShape[ i ] = iBeg;
3963 _nbShapesToSmooth += nbFacesToAdd;
3966 //================================================================================
3968 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
3970 //================================================================================
3972 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
3975 Handle(Geom_Surface)& surface,
3976 const TopoDS_Face& F,
3977 SMESH_MesherHelper& helper)
3979 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
3980 helper.GetMeshDS());
3981 TopoDS_Edge E = TopoDS::Edge( S );
3983 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, F, helper );
3984 if ( curve.IsNull() ) return false;
3986 // compute a relative length of segments
3987 vector< double > len( iTo-iFrom+1 );
3989 double curLen, prevLen = len[0] = 1.0;
3990 for ( int i = iFrom; i < iTo; ++i )
3992 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
3993 len[i-iFrom+1] = len[i-iFrom] + curLen;
3998 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
4000 if ( F.IsNull() ) // 3D
4002 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->tgtNode(0));
4003 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->tgtNode(1));
4004 for ( int i = iFrom; i < iTo; ++i )
4006 double r = len[i-iFrom] / len.back();
4007 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
4008 data._edges[i]->_pos.back() = newPos;
4009 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4010 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4011 dumpMove( tgtNode );
4016 // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
4017 // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
4018 gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
4019 gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
4020 if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
4021 data._edges[iTo-1]->_2neibors->tgtNode(1) ) // closed edge
4023 int iPeriodic = helper.GetPeriodicIndex();
4024 if ( iPeriodic == 1 || iPeriodic == 2 )
4026 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
4027 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
4028 std::swap( uv0, uv1 );
4031 const gp_XY rangeUV = uv1 - uv0;
4032 for ( int i = iFrom; i < iTo; ++i )
4034 double r = len[i-iFrom] / len.back();
4035 gp_XY newUV = uv0 + r * rangeUV;
4036 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4038 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4039 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4040 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4041 dumpMove( tgtNode );
4043 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4044 pos->SetUParameter( newUV.X() );
4045 pos->SetVParameter( newUV.Y() );
4051 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
4053 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
4054 gp_Pnt center3D = circle->Location();
4056 if ( F.IsNull() ) // 3D
4058 if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
4059 data._edges[iTo-1]->_2neibors->tgtNode(1) )
4060 return true; // closed EDGE - nothing to do
4062 return false; // TODO ???
4066 const gp_XY center( center3D.X(), center3D.Y() );
4068 gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
4069 gp_XY uvM = data._edges[iFrom]->LastUV( F );
4070 gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
4071 // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
4072 // gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
4073 // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
4074 gp_Vec2d vec0( center, uv0 );
4075 gp_Vec2d vecM( center, uvM );
4076 gp_Vec2d vec1( center, uv1 );
4077 double uLast = vec0.Angle( vec1 ); // -PI - +PI
4078 double uMidl = vec0.Angle( vecM );
4079 if ( uLast * uMidl <= 0. )
4080 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
4081 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
4083 gp_Ax2d axis( center, vec0 );
4084 gp_Circ2d circ( axis, radius );
4085 for ( int i = iFrom; i < iTo; ++i )
4087 double newU = uLast * len[i-iFrom] / len.back();
4088 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
4089 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4091 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4092 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4093 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4094 dumpMove( tgtNode );
4096 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4097 pos->SetUParameter( newUV.X() );
4098 pos->SetVParameter( newUV.Y() );
4107 //================================================================================
4109 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
4110 * _LayerEdge's on neighbor EDGE's
4112 //================================================================================
4114 bool _ViscousBuilder::updateNormals( _SolidData& data,
4115 SMESH_MesherHelper& helper,
4119 return updateNormalsOfConvexFaces( data, helper, stepNb );
4121 // make temporary quadrangles got by extrusion of
4122 // mesh edges along _LayerEdge._normal's
4124 vector< const SMDS_MeshElement* > tmpFaces;
4126 set< SMESH_TLink > extrudedLinks; // contains target nodes
4127 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
4129 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
4130 for ( size_t i = 0; i < data._edges.size(); ++i )
4132 _LayerEdge* edge = data._edges[i];
4133 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
4134 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
4135 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
4137 const SMDS_MeshNode* tgt2 = edge->_2neibors->tgtNode(j);
4138 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
4139 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
4140 if ( !link_isnew.second )
4142 extrudedLinks.erase( link_isnew.first );
4143 continue; // already extruded and will no more encounter
4145 // a _LayerEdge containg tgt2
4146 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
4148 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
4149 tmpFaces.push_back( f );
4151 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
4152 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
4153 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
4158 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
4159 // Perform two loops on _LayerEdge on EDGE's:
4160 // 1) to find and fix intersection
4161 // 2) to check that no new intersection appears as result of 1)
4163 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
4165 auto_ptr<SMESH_ElementSearcher> searcher
4166 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
4168 // 1) Find intersections
4170 const SMDS_MeshElement* face;
4171 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
4172 TLEdge2LEdgeSet edge2CloseEdge;
4174 const double eps = data._epsilon * data._epsilon;
4175 for ( size_t i = 0; i < data._edges.size(); ++i )
4177 _LayerEdge* edge = data._edges[i];
4178 if (( !edge->IsOnEdge() ) &&
4179 ( edge->_sWOL.IsNull() || edge->_sWOL.ShapeType() != TopAbs_FACE ))
4181 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
4183 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
4184 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
4185 ee.insert( f->_le1 );
4186 ee.insert( f->_le2 );
4187 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
4188 edge2CloseEdge[ f->_le1 ].insert( edge );
4189 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
4190 edge2CloseEdge[ f->_le2 ].insert( edge );
4194 // Set _LayerEdge._normal
4196 if ( !edge2CloseEdge.empty() )
4198 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
4200 set< TGeomID > shapesToSmooth;
4202 // vector to store new _normal and _cosin for each edge in edge2CloseEdge
4203 vector< pair< _LayerEdge*, _LayerEdge > > edge2newEdge( edge2CloseEdge.size() );
4205 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
4206 for ( size_t iE = 0; e2ee != edge2CloseEdge.end(); ++e2ee, ++iE )
4208 _LayerEdge* edge1 = e2ee->first;
4209 _LayerEdge* edge2 = 0;
4210 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
4212 edge2newEdge[ iE ].first = NULL;
4214 // find EDGEs the edges reside
4215 // TopoDS_Edge E1, E2;
4216 // TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4217 // if ( S.ShapeType() != TopAbs_EDGE )
4218 // continue; // TODO: find EDGE by VERTEX
4219 // E1 = TopoDS::Edge( S );
4220 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
4221 for ( ; !edge2 && eIt != ee.end(); ++eIt )
4223 if ( edge1->_sWOL == (*eIt)->_sWOL )
4226 if ( !edge2 ) continue;
4228 edge2newEdge[ iE ].first = edge1;
4229 _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4230 // while ( E2.IsNull() && eIt != ee.end())
4232 // _LayerEdge* e2 = *eIt++;
4233 // TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
4234 // if ( S.ShapeType() == TopAbs_EDGE )
4235 // E2 = TopoDS::Edge( S ), edge2 = e2;
4237 // if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
4239 // find 3 FACEs sharing 2 EDGEs
4241 // TopoDS_Face FF1[2], FF2[2];
4242 // PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
4243 // while ( fIt->more() && FF1[1].IsNull() )
4245 // const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4246 // if ( helper.IsSubShape( *F, data._solid))
4247 // FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
4249 // fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
4250 // while ( fIt->more() && FF2[1].IsNull())
4252 // const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4253 // if ( helper.IsSubShape( *F, data._solid))
4254 // FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
4256 // // exclude a FACE common to E1 and E2 (put it to FFn[1] )
4257 // if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
4258 // std::swap( FF1[0], FF1[1] );
4259 // if ( FF2[0].IsSame( FF1[0]) )
4260 // std::swap( FF2[0], FF2[1] );
4261 // if ( FF1[0].IsNull() || FF2[0].IsNull() )
4264 // get a new normal for edge1
4266 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
4267 // if ( edge1->_cosin < 0 )
4268 // dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
4269 // if ( edge2->_cosin < 0 )
4270 // dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
4272 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
4273 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4274 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4275 newEdge._normal = ( wgt1 * dir1 + wgt2 * dir2 ).XYZ();
4276 newEdge._normal.Normalize();
4278 // cout << edge1->_nodes[0]->GetID() << " "
4279 // << edge2->_nodes[0]->GetID() << " NORM: "
4280 // << newEdge._normal.X() << ", " << newEdge._normal.Y() << ", " << newEdge._normal.Z() << endl;
4283 if ( cos1 < theMinSmoothCosin )
4285 newEdge._cosin = edge2->_cosin;
4287 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
4289 // gp_Vec dirInFace;
4290 // if ( edge1->_cosin < 0 )
4291 // dirInFace = dir1;
4293 // dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
4294 // double angle = dirInFace.Angle( edge1->_normal ); // [0,PI]
4295 // edge1->SetCosin( Cos( angle ));
4296 //newEdge._cosin = 0; // ???????????
4297 newEdge._cosin = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
4301 newEdge._cosin = edge1->_cosin;
4304 // find shapes that need smoothing due to change of _normal
4305 if ( edge1->_cosin < theMinSmoothCosin &&
4306 newEdge._cosin > theMinSmoothCosin )
4308 if ( edge1->_sWOL.IsNull() )
4310 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
4311 while ( fIt->more() )
4312 shapesToSmooth.insert( fIt->next()->getshapeId() );
4313 //limitStepSize( data, fIt->next(), edge1->_cosin ); // too late
4315 else // edge1 inflates along a FACE
4317 TopoDS_Shape V = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4318 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
4319 while ( const TopoDS_Shape* E = eIt->next() )
4321 if ( !helper.IsSubShape( *E, /*FACE=*/edge1->_sWOL ))
4323 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
4324 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
4325 if ( angle < M_PI / 2 )
4326 shapesToSmooth.insert( getMeshDS()->ShapeToIndex( *E ));
4332 data.AddShapesToSmooth( shapesToSmooth );
4334 // Update data of edges depending on a new _normal
4336 for ( size_t iE = 0; iE < edge2newEdge.size(); ++iE )
4338 _LayerEdge* edge1 = edge2newEdge[ iE ].first;
4339 _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4340 if ( !edge1 ) continue;
4342 edge1->_normal = newEdge._normal;
4343 edge1->SetCosin( newEdge._cosin );
4344 edge1->InvalidateStep( 1 );
4346 edge1->SetNewLength( data._stepSize, helper );
4347 if ( edge1->IsOnEdge() )
4349 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
4350 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
4351 edge1->SetDataByNeighbors( n1, n2, helper );
4354 // Update normals and other dependent data of not intersecting _LayerEdge's
4355 // neighboring the intersecting ones
4357 if ( !edge1->_2neibors )
4359 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
4361 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
4362 if ( edge2CloseEdge.count ( neighbor ))
4363 continue; // j-th neighbor is also intersected
4364 _LayerEdge* prevEdge = edge1;
4365 const int nbSteps = 10;
4366 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
4368 if ( !neighbor->_2neibors )
4369 break; // neighbor is on VERTEX
4371 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
4372 if ( nextEdge == prevEdge )
4373 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
4374 double r = double(step-1)/nbSteps;
4375 if ( !nextEdge->_2neibors )
4378 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
4379 newNorm.Normalize();
4381 neighbor->_normal = newNorm;
4382 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
4383 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
4385 neighbor->InvalidateStep( 1 );
4387 neighbor->SetNewLength( data._stepSize, helper );
4389 // goto the next neighbor
4390 prevEdge = neighbor;
4391 neighbor = nextEdge;
4397 // 2) Check absence of intersections
4400 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
4406 //================================================================================
4408 * \brief Modify normals of _LayerEdge's on _ConvexFace's
4410 //================================================================================
4412 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
4413 SMESH_MesherHelper& helper,
4416 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
4419 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
4420 for ( ; id2face != data._convexFaces.end(); ++id2face )
4422 _ConvexFace & convFace = (*id2face).second;
4423 if ( convFace._normalsFixed )
4424 continue; // already fixed
4425 if ( convFace.CheckPrisms() )
4426 continue; // nothing to fix
4428 convFace._normalsFixed = true;
4430 BRepAdaptor_Surface surface ( convFace._face, false );
4431 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
4433 // check if the convex FACE is of spherical shape
4435 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
4440 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
4441 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4443 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4445 if ( meshDS->IndexToShape( id2end->first ).ShapeType() == TopAbs_VERTEX )
4447 _LayerEdge* ledge = data._edges[ iBeg ];
4448 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4449 centersBox.Add( center );
4451 for ( ; iBeg < iEnd; ++iBeg )
4452 nodesBox.Add( SMESH_TNodeXYZ( data._edges[ iBeg ]->_nodes[0] ));
4454 if ( centersBox.IsVoid() )
4456 debugMsg( "Error: centersBox.IsVoid()" );
4459 const bool isSpherical =
4460 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4462 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
4463 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
4467 // set _LayerEdge::_normal as average of all normals
4469 // WARNING: different density of nodes on EDGEs is not taken into account that
4470 // can lead to an improper new normal
4472 gp_XYZ avgNormal( 0,0,0 );
4474 id2end = convFace._subIdToEdgeEnd.begin();
4475 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4477 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4478 // set data of _CentralCurveOnEdge
4479 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
4480 if ( S.ShapeType() == TopAbs_EDGE )
4482 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
4483 ceCurve.SetShapes( TopoDS::Edge(S), convFace, data, helper );
4484 if ( !data._edges[ iBeg ]->_sWOL.IsNull() )
4485 ceCurve._adjFace.Nullify();
4487 ceCurve._ledges.insert( ceCurve._ledges.end(),
4488 &data._edges[ iBeg ], &data._edges[ iEnd ]);
4490 // summarize normals
4491 for ( ; iBeg < iEnd; ++iBeg )
4492 avgNormal += data._edges[ iBeg ]->_normal;
4494 double normSize = avgNormal.SquareModulus();
4495 if ( normSize < 1e-200 )
4497 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
4500 avgNormal /= Sqrt( normSize );
4502 // compute new _LayerEdge::_cosin on EDGEs
4503 double avgCosin = 0;
4506 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4508 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
4509 if ( ceCurve._adjFace.IsNull() )
4511 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
4513 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
4514 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4517 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
4518 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
4519 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
4525 avgCosin /= nbCosin;
4527 // set _LayerEdge::_normal = avgNormal
4528 id2end = convFace._subIdToEdgeEnd.begin();
4529 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4531 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4532 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
4533 if ( S.ShapeType() != TopAbs_EDGE )
4534 for ( int i = iBeg; i < iEnd; ++i )
4535 data._edges[ i ]->_cosin = avgCosin;
4537 for ( ; iBeg < iEnd; ++iBeg )
4538 data._edges[ iBeg ]->_normal = avgNormal;
4541 else // if ( isSpherical )
4543 // We suppose that centers of curvature at all points of the FACE
4544 // lie on some curve, let's call it "central curve". For all _LayerEdge's
4545 // having a common center of curvature we define the same new normal
4546 // as a sum of normals of _LayerEdge's on EDGEs among them.
4548 // get all centers of curvature for each EDGE
4550 helper.SetSubShape( convFace._face );
4551 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
4553 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
4554 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
4556 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
4558 // set adjacent FACE
4559 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
4561 // get _LayerEdge's of the EDGE
4562 TGeomID edgeID = meshDS->ShapeToIndex( edge );
4563 id2end = convFace._subIdToEdgeEnd.find( edgeID );
4564 if ( id2end == convFace._subIdToEdgeEnd.end() )
4566 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
4567 for ( int iV = 0; iV < 2; ++iV )
4569 TopoDS_Vertex v = helper.IthVertex( iV, edge );
4570 TGeomID vID = meshDS->ShapeToIndex( v );
4571 int end = convFace._subIdToEdgeEnd[ vID ];
4572 int iBeg = end > 0 ? data._endEdgeOnShape[ end-1 ] : 0;
4573 vertexLEdges[ iV ] = data._edges[ iBeg ];
4575 edgeLEdge = &vertexLEdges[0];
4576 edgeLEdgeEnd = edgeLEdge + 2;
4578 centerCurves[ iE ]._adjFace.Nullify();
4582 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4583 if ( id2end->second >= data._nbShapesToSmooth )
4584 data.SortOnEdge( edge, iBeg, iEnd, helper );
4585 edgeLEdge = &data._edges[ iBeg ];
4586 edgeLEdgeEnd = edgeLEdge + iEnd - iBeg;
4587 vertexLEdges[0] = data._edges[ iBeg ]->_2neibors->_edges[0];
4588 vertexLEdges[1] = data._edges[ iEnd-1 ]->_2neibors->_edges[1];
4590 if ( ! data._edges[ iBeg ]->_sWOL.IsNull() )
4591 centerCurves[ iE ]._adjFace.Nullify();
4594 // Get curvature centers
4598 if ( edgeLEdge[0]->IsOnEdge() &&
4599 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
4601 centerCurves[ iE ].Append( center, vertexLEdges[0] );
4602 centersBox.Add( center );
4604 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
4605 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
4606 { // EDGE or VERTEXes
4607 centerCurves[ iE ].Append( center, *edgeLEdge );
4608 centersBox.Add( center );
4610 if ( edgeLEdge[-1]->IsOnEdge() &&
4611 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
4613 centerCurves[ iE ].Append( center, vertexLEdges[1] );
4614 centersBox.Add( center );
4616 centerCurves[ iE ]._isDegenerated =
4617 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4619 } // loop on EDGES of convFace._face to set up data of centerCurves
4621 // Compute new normals for _LayerEdge's on EDGEs
4623 double avgCosin = 0;
4626 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
4628 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
4629 if ( ceCurve._isDegenerated )
4631 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
4632 vector< gp_XYZ > & newNormals = ceCurve._normals;
4633 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
4636 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
4639 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
4641 if ( isOK && !ceCurve._adjFace.IsNull() )
4643 // compute new _LayerEdge::_cosin
4644 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
4645 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4648 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
4649 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
4650 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
4656 // set new normals to _LayerEdge's of NOT degenerated central curves
4657 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4659 if ( centerCurves[ iE ]._isDegenerated )
4661 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4662 centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
4664 // set new normals to _LayerEdge's of degenerated central curves
4665 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4667 if ( !centerCurves[ iE ]._isDegenerated ||
4668 centerCurves[ iE ]._ledges.size() < 3 )
4670 // new normal is an average of new normals at VERTEXes that
4671 // was computed on non-degenerated _CentralCurveOnEdge's
4672 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
4673 centerCurves[ iE ]._ledges.back ()->_normal );
4674 double sz = newNorm.Modulus();
4678 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
4679 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
4680 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
4682 centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
4683 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
4687 // Find new normals for _LayerEdge's based on FACE
4690 avgCosin /= nbCosin;
4691 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
4692 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
4693 if ( id2end != convFace._subIdToEdgeEnd.end() )
4697 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4698 for ( ; iBeg < iEnd; ++iBeg )
4700 _LayerEdge* ledge = data._edges[ iBeg ];
4701 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4703 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
4705 iE = iE % centerCurves.size();
4706 if ( centerCurves[ iE ]._isDegenerated )
4708 newNorm.SetCoord( 0,0,0 );
4709 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
4711 ledge->_normal = newNorm;
4712 ledge->_cosin = avgCosin;
4719 } // not a quasi-spherical FACE
4721 // Update _LayerEdge's data according to a new normal
4723 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
4724 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
4726 id2end = convFace._subIdToEdgeEnd.begin();
4727 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4729 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4730 for ( ; iBeg < iEnd; ++iBeg )
4732 _LayerEdge* & ledge = data._edges[ iBeg ];
4733 double len = ledge->_len;
4734 ledge->InvalidateStep( stepNb + 1, /*restoreLength=*/true );
4735 ledge->SetCosin( ledge->_cosin );
4736 ledge->SetNewLength( len, helper );
4739 } // loop on sub-shapes of convFace._face
4741 // Find FACEs adjacent to convFace._face that got necessity to smooth
4742 // as a result of normals modification
4744 set< TGeomID > adjFacesToSmooth;
4745 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4747 if ( centerCurves[ iE ]._adjFace.IsNull() ||
4748 centerCurves[ iE ]._adjFaceToSmooth )
4750 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4752 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
4754 adjFacesToSmooth.insert( meshDS->ShapeToIndex( centerCurves[ iE ]._adjFace ));
4759 data.AddShapesToSmooth( adjFacesToSmooth );
4764 } // loop on data._convexFaces
4769 //================================================================================
4771 * \brief Finds a center of curvature of a surface at a _LayerEdge
4773 //================================================================================
4775 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
4776 BRepLProp_SLProps& surfProp,
4777 SMESH_MesherHelper& helper,
4778 gp_Pnt & center ) const
4780 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
4781 surfProp.SetParameters( uv.X(), uv.Y() );
4782 if ( !surfProp.IsCurvatureDefined() )
4785 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
4786 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
4787 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
4788 if ( surfCurvatureMin > surfCurvatureMax )
4789 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
4791 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
4796 //================================================================================
4798 * \brief Check that prisms are not distorted
4800 //================================================================================
4802 bool _ConvexFace::CheckPrisms() const
4805 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
4807 const _LayerEdge* edge = _simplexTestEdges[i];
4808 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
4809 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4810 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
4812 debugMsg( "Bad simplex of _simplexTestEdges ("
4813 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
4814 << " "<< edge->_simplices[j]._nPrev->GetID()
4815 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4822 //================================================================================
4824 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
4825 * stored in this _CentralCurveOnEdge.
4826 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
4827 * \param [in,out] newNormal - current normal at this point, to be redefined
4828 * \return bool - true if succeeded.
4830 //================================================================================
4832 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
4834 if ( this->_isDegenerated )
4837 // find two centers the given one lies between
4839 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
4841 double sl2 = 1.001 * _segLength2[ i ];
4843 double d1 = center.SquareDistance( _curvaCenters[ i ]);
4847 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
4848 if ( d2 > sl2 || d2 + d1 < 1e-100 )
4853 double r = d1 / ( d1 + d2 );
4854 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
4855 ( r ) * _ledges[ i+1 ]->_normal );
4859 double sz = newNormal.Modulus();
4868 //================================================================================
4870 * \brief Set shape members
4872 //================================================================================
4874 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
4875 const _ConvexFace& convFace,
4876 const _SolidData& data,
4877 SMESH_MesherHelper& helper)
4881 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
4882 while ( const TopoDS_Shape* F = fIt->next())
4883 if ( !convFace._face.IsSame( *F ))
4885 _adjFace = TopoDS::Face( *F );
4886 _adjFaceToSmooth = false;
4887 // _adjFace already in a smoothing queue ?
4889 TGeomID adjFaceID = helper.GetMeshDS()->ShapeToIndex( *F );
4890 if ( data.GetShapeEdges( adjFaceID, end ))
4891 _adjFaceToSmooth = ( end < data._nbShapesToSmooth );
4896 //================================================================================
4898 * \brief Looks for intersection of it's last segment with faces
4899 * \param distance - returns shortest distance from the last node to intersection
4901 //================================================================================
4903 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
4905 const double& epsilon,
4906 const SMDS_MeshElement** face)
4908 vector< const SMDS_MeshElement* > suspectFaces;
4910 gp_Ax1 lastSegment = LastSegment(segLen);
4911 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
4913 bool segmentIntersected = false;
4914 distance = Precision::Infinite();
4915 int iFace = -1; // intersected face
4916 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
4918 const SMDS_MeshElement* face = suspectFaces[j];
4919 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
4920 face->GetNodeIndex( _nodes[0] ) >= 0 )
4921 continue; // face sharing _LayerEdge node
4922 const int nbNodes = face->NbCornerNodes();
4923 bool intFound = false;
4925 SMDS_MeshElement::iterator nIt = face->begin_nodes();
4928 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
4932 const SMDS_MeshNode* tria[3];
4935 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
4938 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
4944 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
4945 segmentIntersected = true;
4946 if ( distance > dist )
4947 distance = dist, iFace = j;
4950 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
4952 if ( segmentIntersected )
4955 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
4956 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
4957 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
4958 << ", intersection with face ("
4959 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4960 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
4961 << ") distance = " << distance - segLen<< endl;
4967 return segmentIntersected;
4970 //================================================================================
4972 * \brief Returns size and direction of the last segment
4974 //================================================================================
4976 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
4978 // find two non-coincident positions
4979 gp_XYZ orig = _pos.back();
4981 int iPrev = _pos.size() - 2;
4982 const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
4983 while ( iPrev >= 0 )
4985 dir = orig - _pos[iPrev];
4986 if ( dir.SquareModulus() > tol*tol )
4996 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
4997 segDir.SetDirection( _normal );
5002 gp_Pnt pPrev = _pos[ iPrev ];
5003 if ( !_sWOL.IsNull() )
5005 TopLoc_Location loc;
5006 if ( _sWOL.ShapeType() == TopAbs_EDGE )
5009 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
5010 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
5014 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
5015 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
5017 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
5019 segDir.SetLocation( pPrev );
5020 segDir.SetDirection( dir );
5021 segLen = dir.Modulus();
5027 //================================================================================
5029 * \brief Return the last position of the target node on a FACE.
5030 * \param [in] F - the FACE this _LayerEdge is inflated along
5031 * \return gp_XY - result UV
5033 //================================================================================
5035 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F ) const
5037 if ( F.IsSame( _sWOL )) // F is my FACE
5038 return gp_XY( _pos.back().X(), _pos.back().Y() );
5040 if ( _sWOL.IsNull() || _sWOL.ShapeType() != TopAbs_EDGE ) // wrong call
5041 return gp_XY( 1e100, 1e100 );
5043 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
5044 double f, l, u = _pos.back().X();
5045 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(_sWOL), F, f,l);
5046 if ( !C2d.IsNull() && f <= u && u <= l )
5047 return C2d->Value( u ).XY();
5049 return gp_XY( 1e100, 1e100 );
5052 //================================================================================
5054 * \brief Test intersection of the last segment with a given triangle
5055 * using Moller-Trumbore algorithm
5056 * Intersection is detected if distance to intersection is less than _LayerEdge._len
5058 //================================================================================
5060 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
5061 const SMDS_MeshNode* n0,
5062 const SMDS_MeshNode* n1,
5063 const SMDS_MeshNode* n2,
5065 const double& EPSILON) const
5067 //const double EPSILON = 1e-6;
5069 const gp_Pnt& orig = lastSegment.Location();
5070 const gp_Dir& dir = lastSegment.Direction();
5072 SMESH_TNodeXYZ vert0( n0 );
5073 SMESH_TNodeXYZ vert1( n1 );
5074 SMESH_TNodeXYZ vert2( n2 );
5076 /* calculate distance from vert0 to ray origin */
5077 gp_XYZ tvec = orig.XYZ() - vert0;
5079 //if ( tvec * dir > EPSILON )
5080 // intersected face is at back side of the temporary face this _LayerEdge belongs to
5083 gp_XYZ edge1 = vert1 - vert0;
5084 gp_XYZ edge2 = vert2 - vert0;
5086 /* begin calculating determinant - also used to calculate U parameter */
5087 gp_XYZ pvec = dir.XYZ() ^ edge2;
5089 /* if determinant is near zero, ray lies in plane of triangle */
5090 double det = edge1 * pvec;
5092 if (det > -EPSILON && det < EPSILON)
5095 /* calculate U parameter and test bounds */
5096 double u = ( tvec * pvec ) / det;
5097 //if (u < 0.0 || u > 1.0)
5098 if (u < -EPSILON || u > 1.0 + EPSILON)
5101 /* prepare to test V parameter */
5102 gp_XYZ qvec = tvec ^ edge1;
5104 /* calculate V parameter and test bounds */
5105 double v = (dir.XYZ() * qvec) / det;
5106 //if ( v < 0.0 || u + v > 1.0 )
5107 if ( v < -EPSILON || u + v > 1.0 + EPSILON)
5110 /* calculate t, ray intersects triangle */
5111 t = (edge2 * qvec) / det;
5117 //================================================================================
5119 * \brief Perform smooth of _LayerEdge's based on EDGE's
5120 * \retval bool - true if node has been moved
5122 //================================================================================
5124 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
5125 const TopoDS_Face& F,
5126 SMESH_MesherHelper& helper)
5128 ASSERT( IsOnEdge() );
5130 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
5131 SMESH_TNodeXYZ oldPos( tgtNode );
5132 double dist01, distNewOld;
5134 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
5135 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
5136 dist01 = p0.Distance( _2neibors->tgtNode(1) );
5138 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
5139 double lenDelta = 0;
5142 //lenDelta = _curvature->lenDelta( _len );
5143 lenDelta = _curvature->lenDeltaByDist( dist01 );
5144 newPos.ChangeCoord() += _normal * lenDelta;
5147 distNewOld = newPos.Distance( oldPos );
5151 if ( _2neibors->_plnNorm )
5153 // put newPos on the plane defined by source node and _plnNorm
5154 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
5155 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
5156 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
5158 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5159 _pos.back() = newPos.XYZ();
5163 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5164 gp_XY uv( Precision::Infinite(), 0 );
5165 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
5166 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5168 newPos = surface->Value( uv.X(), uv.Y() );
5169 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5172 // commented for IPAL0052478
5173 // if ( _curvature && lenDelta < 0 )
5175 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
5176 // _len -= prevPos.Distance( oldPos );
5177 // _len += prevPos.Distance( newPos );
5179 bool moved = distNewOld > dist01/50;
5181 dumpMove( tgtNode ); // debug
5186 //================================================================================
5188 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
5189 * \retval bool - true if _tgtNode has been moved
5191 //================================================================================
5193 bool _LayerEdge::Smooth(int& badNb, const int step, const bool isConcaveFace )
5196 if ( _simplices.size() < 2 )
5197 return moved; // _LayerEdge inflated along EDGE or FACE
5199 const gp_XYZ& curPos ( _pos.back() );
5200 const gp_XYZ& prevPos( _pos[ _pos.size()-2 ]);
5202 // quality metrics (orientation) of tetras around _tgtNode
5204 double vol, minVolBefore = 1e100;
5205 for ( size_t i = 0; i < _simplices.size(); ++i )
5207 nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos, vol );
5208 minVolBefore = Min( minVolBefore, vol );
5210 int nbBad = _simplices.size() - nbOkBefore;
5212 // compute new position for the last _pos using different _funs
5213 gp_XYZ newPos, bestNewPos;
5214 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
5217 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
5218 else if ( _funs[ iFun ] == _smooFunction )
5219 continue; // _smooFunction again
5220 else if ( step > 0 )
5221 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
5223 break; // let "easy" functions improve elements around distorted ones
5227 double delta = _curvature->lenDelta( _len );
5229 newPos += _normal * delta;
5232 double segLen = _normal * ( newPos - prevPos );
5233 if ( segLen + delta > 0 )
5234 newPos += _normal * delta;
5236 // double segLenChange = _normal * ( curPos - newPos );
5237 // newPos += 0.5 * _normal * segLenChange;
5241 double minVolAfter = 1e100;
5242 for ( size_t i = 0; i < _simplices.size(); ++i )
5244 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos, vol );
5245 minVolAfter = Min( minVolAfter, vol );
5248 if ( nbOkAfter < nbOkBefore )
5250 if (( isConcaveFace ) &&
5251 ( nbOkAfter == nbOkBefore ) &&
5252 //( iFun > -1 || nbOkAfter < _simplices.size() ) &&
5253 ( minVolAfter <= minVolBefore ))
5256 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
5258 // commented for IPAL0052478
5259 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
5260 // _len += prevPos.Distance(newPos);
5262 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
5263 _pos.back() = newPos;
5265 dumpMoveComm( n, _funNames[ iFun < 0 ? smooFunID() : iFun ]);
5267 nbBad = _simplices.size() - nbOkAfter;
5271 //_smooFunction = _funs[ iFun ];
5272 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
5273 // << "\t nbBad: " << _simplices.size() - nbOkAfter
5274 // << " minVol: " << minVolAfter
5275 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
5277 minVolBefore = minVolAfter;
5278 nbOkBefore = nbOkAfter;
5279 continue; // look for a better function
5284 } // loop on smoothing functions
5290 //================================================================================
5292 * \brief Chooses a smoothing technic giving a position most close to an initial one.
5293 * For a correct result, _simplices must contain nodes lying on geometry.
5295 //================================================================================
5297 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
5298 const TNode2Edge& n2eMap)
5300 if ( _smooFunction ) return;
5302 // use smoothNefPolygon() near concaveVertices
5303 if ( !concaveVertices.empty() )
5305 for ( size_t i = 0; i < _simplices.size(); ++i )
5307 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
5309 _smooFunction = _funs[ FUN_NEFPOLY ];
5311 // set FUN_CENTROIDAL to neighbor edges
5312 TNode2Edge::const_iterator n2e;
5313 for ( i = 0; i < _simplices.size(); ++i )
5315 if (( _simplices[i]._nPrev->GetPosition()->GetDim() == 2 ) &&
5316 (( n2e = n2eMap.find( _simplices[i]._nPrev )) != n2eMap.end() ))
5318 n2e->second->_smooFunction = _funs[ FUN_CENTROIDAL ];
5326 // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
5327 // where the nodes are smoothed too far along a sphere thus creating
5328 // inverted _simplices
5329 double dist[theNbSmooFuns];
5330 //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
5331 double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
5333 double minDist = Precision::Infinite();
5334 gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
5335 for ( int i = 0; i < FUN_NEFPOLY; ++i )
5337 gp_Pnt newP = (this->*_funs[i])();
5338 dist[i] = p.SquareDistance( newP );
5339 if ( dist[i]*coef[i] < minDist )
5341 _smooFunction = _funs[i];
5342 minDist = dist[i]*coef[i];
5348 _smooFunction = _funs[ FUN_LAPLACIAN ];
5351 // for ( size_t i = 0; i < _simplices.size(); ++i )
5352 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
5353 // if ( minDim == 0 )
5354 // _smooFunction = _funs[ FUN_CENTROIDAL ];
5355 // else if ( minDim == 1 )
5356 // _smooFunction = _funs[ FUN_CENTROIDAL ];
5360 // for ( int i = 0; i < FUN_NB; ++i )
5362 // //cout << dist[i] << " ";
5363 // if ( _smooFunction == _funs[i] ) {
5365 // //debugMsg( fNames[i] );
5369 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
5372 //================================================================================
5374 * \brief Returns a name of _SmooFunction
5376 //================================================================================
5378 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
5381 fun = _smooFunction;
5382 for ( int i = 0; i < theNbSmooFuns; ++i )
5383 if ( fun == _funs[i] )
5386 return theNbSmooFuns;
5389 //================================================================================
5391 * \brief Computes a new node position using Laplacian smoothing
5393 //================================================================================
5395 gp_XYZ _LayerEdge::smoothLaplacian()
5397 gp_XYZ newPos (0,0,0);
5398 for ( size_t i = 0; i < _simplices.size(); ++i )
5399 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5400 newPos /= _simplices.size();
5405 //================================================================================
5407 * \brief Computes a new node position using angular-based smoothing
5409 //================================================================================
5411 gp_XYZ _LayerEdge::smoothAngular()
5413 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1);
5414 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
5415 vector< gp_XYZ > points; points. reserve( _simplices.size() );
5417 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5419 for ( size_t i = 0; i < _simplices.size(); ++i )
5421 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5422 edgeDir.push_back( p - pPrev );
5423 edgeSize.push_back( edgeDir.back().Magnitude() );
5424 //double edgeSize = edgeDir.back().Magnitude();
5425 if ( edgeSize.back() < numeric_limits<double>::min() )
5428 edgeSize.pop_back();
5432 edgeDir.back() /= edgeSize.back();
5433 points.push_back( p );
5438 edgeDir.push_back ( edgeDir[0] );
5439 edgeSize.push_back( edgeSize[0] );
5440 pN /= points.size();
5442 gp_XYZ newPos(0,0,0);
5443 //gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5445 for ( size_t i = 0; i < points.size(); ++i )
5447 gp_Vec toN( pN - points[i]);
5448 double toNLen = toN.Magnitude();
5449 if ( toNLen < numeric_limits<double>::min() )
5454 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
5455 double bisecLen = bisec.SquareMagnitude();
5456 if ( bisecLen < numeric_limits<double>::min() )
5458 gp_Vec norm = edgeDir[i] ^ toN;
5459 bisec = norm ^ edgeDir[i];
5460 bisecLen = bisec.SquareMagnitude();
5462 bisecLen = Sqrt( bisecLen );
5467 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
5468 sumSize += bisecLen;
5470 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
5471 sumSize += ( edgeSize[i] + edgeSize[i+1] );
5480 //================================================================================
5482 * \brief Computes a new node position using weigthed node positions
5484 //================================================================================
5486 gp_XYZ _LayerEdge::smoothLengthWeighted()
5488 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
5489 vector< gp_XYZ > points; points. reserve( _simplices.size() );
5491 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5492 for ( size_t i = 0; i < _simplices.size(); ++i )
5494 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5495 edgeSize.push_back( ( p - pPrev ).Modulus() );
5496 if ( edgeSize.back() < numeric_limits<double>::min() )
5498 edgeSize.pop_back();
5502 points.push_back( p );
5506 edgeSize.push_back( edgeSize[0] );
5508 gp_XYZ newPos(0,0,0);
5510 for ( size_t i = 0; i < points.size(); ++i )
5512 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
5513 sumSize += edgeSize[i] + edgeSize[i+1];
5519 //================================================================================
5521 * \brief Computes a new node position using angular-based smoothing
5523 //================================================================================
5525 gp_XYZ _LayerEdge::smoothCentroidal()
5527 gp_XYZ newPos(0,0,0);
5528 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5530 for ( size_t i = 0; i < _simplices.size(); ++i )
5532 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5533 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
5534 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
5535 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
5538 newPos += gc * size;
5545 //================================================================================
5547 * \brief Computes a new node position located inside a Nef polygon
5549 //================================================================================
5551 gp_XYZ _LayerEdge::smoothNefPolygon()
5553 gp_XYZ newPos(0,0,0);
5555 // get a plane to seach a solution on
5557 vector< gp_XYZ > vecs( _simplices.size() + 1 );
5559 const double tol = numeric_limits<double>::min();
5560 gp_XYZ center(0,0,0);
5561 for ( i = 0; i < _simplices.size(); ++i )
5563 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
5564 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
5565 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5567 vecs.back() = vecs[0];
5568 center /= _simplices.size();
5570 gp_XYZ zAxis(0,0,0);
5571 for ( i = 0; i < _simplices.size(); ++i )
5572 zAxis += vecs[i] ^ vecs[i+1];
5575 for ( i = 0; i < _simplices.size(); ++i )
5578 if ( yAxis.SquareModulus() > tol )
5581 gp_XYZ xAxis = yAxis ^ zAxis;
5582 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
5583 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
5584 // p0.Distance( _simplices[2]._nPrev ));
5585 // gp_XYZ center = smoothLaplacian();
5586 // gp_XYZ xAxis, yAxis, zAxis;
5587 // for ( i = 0; i < _simplices.size(); ++i )
5589 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5590 // if ( xAxis.SquareModulus() > tol*tol )
5593 // for ( i = 1; i < _simplices.size(); ++i )
5595 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5596 // zAxis = xAxis ^ yAxis;
5597 // if ( zAxis.SquareModulus() > tol*tol )
5600 // if ( i == _simplices.size() ) return newPos;
5602 yAxis = zAxis ^ xAxis;
5603 xAxis /= xAxis.Modulus();
5604 yAxis /= yAxis.Modulus();
5606 // get half-planes of _simplices
5608 vector< _halfPlane > halfPlns( _simplices.size() );
5610 for ( size_t i = 0; i < _simplices.size(); ++i )
5612 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5613 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
5614 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
5615 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
5616 gp_XY vec12 = p2 - p1;
5617 double dist12 = vec12.Modulus();
5621 halfPlns[ nbHP ]._pos = p1;
5622 halfPlns[ nbHP ]._dir = vec12;
5623 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
5627 // intersect boundaries of half-planes, define state of intersection points
5628 // in relation to all half-planes and calculate internal point of a 2D polygon
5631 gp_XY newPos2D (0,0);
5633 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
5634 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
5635 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
5637 vector< vector< TIntPntState > > allIntPnts( nbHP );
5638 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
5640 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
5641 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
5643 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
5644 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
5647 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
5649 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5651 if ( iHP1 == iHP2 ) continue;
5653 TIntPntState & ips1 = intPnts1[ iHP2 ];
5654 if ( ips1.second == UNDEF )
5656 // find an intersection point of boundaries of iHP1 and iHP2
5658 if ( iHP2 == iPrev ) // intersection with neighbors is known
5659 ips1.first = halfPlns[ iHP1 ]._pos;
5660 else if ( iHP2 == iNext )
5661 ips1.first = halfPlns[ iHP2 ]._pos;
5662 else if ( !halfPlns[ iHP1 ].FindInterestion( halfPlns[ iHP2 ], ips1.first ))
5663 ips1.second = NO_INT;
5665 // classify the found intersection point
5666 if ( ips1.second != NO_INT )
5668 ips1.second = NOT_OUT;
5669 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
5670 if ( i != iHP1 && i != iHP2 &&
5671 halfPlns[ i ].IsOut( ips1.first, tol ))
5672 ips1.second = IS_OUT;
5674 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
5675 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
5676 TIntPntState & ips2 = intPnts2[ iHP1 ];
5679 if ( ips1.second == NOT_OUT )
5682 segEnds[ bool(segEnds[0]) ] = & ips1.first;
5686 // find a NOT_OUT segment of boundary which is located between
5687 // two NOT_OUT int points
5690 continue; // no such a segment
5694 // sort points along the boundary
5695 map< double, TIntPntState* > ipsByParam;
5696 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5698 TIntPntState & ips1 = intPnts1[ iHP2 ];
5699 if ( ips1.second != NO_INT )
5701 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
5702 double param = op * halfPlns[ iHP1 ]._dir;
5703 ipsByParam.insert( make_pair( param, & ips1 ));
5706 // look for two neighboring NOT_OUT points
5708 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
5709 for ( ; u2ips != ipsByParam.end(); ++u2ips )
5711 TIntPntState & ips1 = *(u2ips->second);
5712 if ( ips1.second == NOT_OUT )
5713 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
5714 else if ( nbNotOut >= 2 )
5721 if ( nbNotOut >= 2 )
5723 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
5726 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
5733 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
5743 //================================================================================
5745 * \brief Add a new segment to _LayerEdge during inflation
5747 //================================================================================
5749 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
5751 if ( _len - len > -1e-6 )
5753 //_pos.push_back( _pos.back() );
5757 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
5758 SMESH_TNodeXYZ oldXYZ( n );
5759 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
5760 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
5762 _pos.push_back( nXYZ );
5764 if ( !_sWOL.IsNull() )
5767 if ( _sWOL.ShapeType() == TopAbs_EDGE )
5769 double u = Precision::Infinite(); // to force projection w/o distance check
5770 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
5771 _pos.back().SetCoord( u, 0, 0 );
5772 if ( _nodes.size() > 1 )
5774 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
5775 pos->SetUParameter( u );
5780 gp_XY uv( Precision::Infinite(), 0 );
5781 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
5782 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5783 if ( _nodes.size() > 1 )
5785 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
5786 pos->SetUParameter( uv.X() );
5787 pos->SetVParameter( uv.Y() );
5790 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
5792 dumpMove( n ); //debug
5795 //================================================================================
5797 * \brief Remove last inflation step
5799 //================================================================================
5801 void _LayerEdge::InvalidateStep( int curStep, bool restoreLength )
5803 if ( _pos.size() > curStep )
5805 if ( restoreLength )
5806 _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
5808 _pos.resize( curStep );
5809 gp_Pnt nXYZ = _pos.back();
5810 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
5811 if ( !_sWOL.IsNull() )
5813 TopLoc_Location loc;
5814 if ( _sWOL.ShapeType() == TopAbs_EDGE )
5816 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
5817 pos->SetUParameter( nXYZ.X() );
5819 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
5820 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
5824 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
5825 pos->SetUParameter( nXYZ.X() );
5826 pos->SetVParameter( nXYZ.Y() );
5827 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
5828 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
5831 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
5836 //================================================================================
5838 * \brief Create layers of prisms
5840 //================================================================================
5842 bool _ViscousBuilder::refine(_SolidData& data)
5844 SMESH_MesherHelper helper( *_mesh );
5845 helper.SetSubShape( data._solid );
5846 helper.SetElementsOnShape(false);
5848 Handle(Geom_Curve) curve;
5849 Handle(Geom_Surface) surface;
5850 TopoDS_Edge geomEdge;
5851 TopoDS_Face geomFace;
5852 TopoDS_Shape prevSWOL;
5853 TopLoc_Location loc;
5857 TGeomID prevBaseId = -1;
5858 TNode2Edge* n2eMap = 0;
5859 TNode2Edge::iterator n2e;
5861 // Create intermediate nodes on each _LayerEdge
5863 int iS = 0, iEnd = data._endEdgeOnShape[ iS ];
5865 for ( size_t i = 0; i < data._edges.size(); ++i )
5867 _LayerEdge& edge = *data._edges[i];
5869 if ( edge._nodes.size() < 2 )
5870 continue; // on _noShrinkShapes
5872 // get parameters of layers for the edge
5874 iEnd = data._endEdgeOnShape[ ++iS ];
5875 const AverageHyp& hyp = data._hypOnShape[ iS ];
5877 // get accumulated length of segments
5878 vector< double > segLen( edge._pos.size() );
5880 for ( size_t j = 1; j < edge._pos.size(); ++j )
5881 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
5883 // allocate memory for new nodes if it is not yet refined
5884 const SMDS_MeshNode* tgtNode = edge._nodes.back();
5885 if ( edge._nodes.size() == 2 )
5887 edge._nodes.resize( hyp.GetNumberLayers() + 1, 0 );
5889 edge._nodes.back() = tgtNode;
5891 // get data of a shrink shape
5892 if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
5894 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
5897 geomEdge = TopoDS::Edge( edge._sWOL );
5898 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
5902 geomFace = TopoDS::Face( edge._sWOL );
5903 surface = BRep_Tool::Surface( geomFace, loc );
5905 prevSWOL = edge._sWOL;
5907 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
5908 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
5909 if ( baseShapeId != prevBaseId )
5911 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
5912 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
5913 prevBaseId = baseShapeId;
5915 _LayerEdge* edgeOnSameNode = 0;
5916 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
5918 edgeOnSameNode = n2e->second;
5919 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
5920 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
5923 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
5924 epos->SetUParameter( otherTgtPos.X() );
5928 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
5929 fpos->SetUParameter( otherTgtPos.X() );
5930 fpos->SetVParameter( otherTgtPos.Y() );
5933 // calculate height of the first layer
5935 const double T = segLen.back(); //data._hyp.GetTotalThickness();
5936 const double f = hyp.GetStretchFactor();
5937 const int N = hyp.GetNumberLayers();
5938 const double fPowN = pow( f, N );
5939 if ( fPowN - 1 <= numeric_limits<double>::min() )
5942 h0 = T * ( f - 1 )/( fPowN - 1 );
5944 const double zeroLen = std::numeric_limits<double>::min();
5946 // create intermediate nodes
5947 double hSum = 0, hi = h0/f;
5949 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
5951 // compute an intermediate position
5954 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
5956 int iPrevSeg = iSeg-1;
5957 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
5959 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
5960 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
5962 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
5963 if ( !edge._sWOL.IsNull() )
5965 // compute XYZ by parameters <pos>
5970 pos = curve->Value( u ).Transformed(loc);
5974 uv.SetCoord( pos.X(), pos.Y() );
5976 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
5979 // create or update the node
5982 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
5983 if ( !edge._sWOL.IsNull() )
5986 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
5988 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
5992 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
5997 if ( !edge._sWOL.IsNull() )
5999 // make average pos from new and current parameters
6002 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
6003 pos = curve->Value( u ).Transformed(loc);
6005 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
6006 epos->SetUParameter( u );
6010 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
6011 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
6013 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
6014 fpos->SetUParameter( uv.X() );
6015 fpos->SetVParameter( uv.Y() );
6018 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
6020 } // loop on edge._nodes
6022 if ( !edge._sWOL.IsNull() ) // prepare for shrink()
6025 edge._pos.back().SetCoord( u, 0,0);
6027 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
6029 if ( edgeOnSameNode )
6030 edgeOnSameNode->_pos.back() = edge._pos.back();
6033 } // loop on data._edges to create nodes
6035 if ( !getMeshDS()->IsEmbeddedMode() )
6036 // Log node movement
6037 for ( size_t i = 0; i < data._edges.size(); ++i )
6039 _LayerEdge& edge = *data._edges[i];
6040 SMESH_TNodeXYZ p ( edge._nodes.back() );
6041 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
6046 helper.SetElementsOnShape(true);
6048 vector< vector<const SMDS_MeshNode*>* > nnVec;
6049 set< vector<const SMDS_MeshNode*>* > nnSet;
6050 set< int > degenEdgeInd;
6051 vector<const SMDS_MeshElement*> degenVols;
6053 TopExp_Explorer exp( data._solid, TopAbs_FACE );
6054 for ( ; exp.More(); exp.Next() )
6056 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
6057 if ( data._ignoreFaceIds.count( faceID ))
6059 const bool isReversedFace = data._reversedFaceIds.count( faceID );
6060 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
6061 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
6062 while ( fIt->more() )
6064 const SMDS_MeshElement* face = fIt->next();
6065 const int nbNodes = face->NbCornerNodes();
6066 nnVec.resize( nbNodes );
6068 degenEdgeInd.clear();
6070 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
6071 for ( int iN = 0; iN < nbNodes; ++iN )
6073 const SMDS_MeshNode* n = nIt->next();
6074 const int i = isReversedFace ? nbNodes-1-iN : iN;
6075 nnVec[ i ] = & data._n2eMap[ n ]->_nodes;
6076 if ( nnVec[ i ]->size() < 2 )
6077 degenEdgeInd.insert( iN );
6079 nbZ = nnVec[ i ]->size();
6081 if ( helper.HasDegeneratedEdges() )
6082 nnSet.insert( nnVec[ i ]);
6086 if ( 0 < nnSet.size() && nnSet.size() < 3 )
6092 switch ( degenEdgeInd.size() )
6096 for ( int iZ = 1; iZ < nbZ; ++iZ )
6097 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6098 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
6103 int i2 = *degenEdgeInd.begin();
6104 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
6105 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
6106 for ( int iZ = 1; iZ < nbZ; ++iZ )
6107 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
6108 (*nnVec[i1])[iZ], (*nnVec[i0])[iZ], (*nnVec[i2])[0]);
6113 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
6114 for ( int iZ = 1; iZ < nbZ; ++iZ )
6115 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6123 switch ( degenEdgeInd.size() )
6127 for ( int iZ = 1; iZ < nbZ; ++iZ )
6128 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
6129 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
6130 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
6131 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
6136 int i2 = *degenEdgeInd.begin();
6137 int i3 = *degenEdgeInd.rbegin();
6138 bool ok = ( i3 - i2 == 1 );
6139 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
6140 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
6141 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
6142 for ( int iZ = 1; iZ < nbZ; ++iZ )
6144 const SMDS_MeshElement* vol =
6145 helper.AddVolume( (*nnVec[i3])[0], (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
6146 (*nnVec[i2])[0], (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
6148 degenVols.push_back( vol );
6152 case 3: // degen HEX
6154 const SMDS_MeshNode* nn[8];
6155 for ( int iZ = 1; iZ < nbZ; ++iZ )
6157 const SMDS_MeshElement* vol =
6158 helper.AddVolume( nnVec[0]->size() > 1 ? (*nnVec[0])[iZ-1] : (*nnVec[0])[0],
6159 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ-1] : (*nnVec[1])[0],
6160 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ-1] : (*nnVec[2])[0],
6161 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ-1] : (*nnVec[3])[0],
6162 nnVec[0]->size() > 1 ? (*nnVec[0])[iZ] : (*nnVec[0])[0],
6163 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ] : (*nnVec[1])[0],
6164 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ] : (*nnVec[2])[0],
6165 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ] : (*nnVec[3])[0]);
6166 degenVols.push_back( vol );
6174 return error("Not supported type of element", data._index);
6176 } // switch ( nbNodes )
6177 } // while ( fIt->more() )
6180 if ( !degenVols.empty() )
6182 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
6183 if ( !err || err->IsOK() )
6185 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
6186 "Degenerated volumes created" ));
6187 err->myBadElements.insert( err->myBadElements.end(),
6188 degenVols.begin(),degenVols.end() );
6195 //================================================================================
6197 * \brief Shrink 2D mesh on faces to let space for inflated layers
6199 //================================================================================
6201 bool _ViscousBuilder::shrink()
6203 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
6204 // inflated along FACE or EDGE)
6205 map< TGeomID, _SolidData* > f2sdMap;
6206 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
6208 _SolidData& data = _sdVec[i];
6209 TopTools_MapOfShape FFMap;
6210 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
6211 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
6212 if ( s2s->second.ShapeType() == TopAbs_FACE )
6214 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
6216 if ( FFMap.Add( (*s2s).second ))
6217 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
6218 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
6219 // by StdMeshers_QuadToTriaAdaptor
6220 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
6222 SMESH_ProxyMesh::SubMesh* proxySub =
6223 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
6224 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6225 while ( fIt->more() )
6226 proxySub->AddElement( fIt->next() );
6227 // as a result 3D algo will use elements from proxySub and not from smDS
6232 SMESH_MesherHelper helper( *_mesh );
6233 helper.ToFixNodeParameters( true );
6236 map< TGeomID, _Shrinker1D > e2shrMap;
6237 vector< _LayerEdge* > lEdges;
6239 // loop on FACES to srink mesh on
6240 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
6241 for ( ; f2sd != f2sdMap.end(); ++f2sd )
6243 _SolidData& data = *f2sd->second;
6244 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
6245 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
6246 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
6248 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
6250 helper.SetSubShape(F);
6252 // ===========================
6253 // Prepare data for shrinking
6254 // ===========================
6256 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
6257 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
6258 vector < const SMDS_MeshNode* > smoothNodes;
6260 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
6261 while ( nIt->more() )
6263 const SMDS_MeshNode* n = nIt->next();
6264 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
6265 smoothNodes.push_back( n );
6268 // Find out face orientation
6270 const set<TGeomID> ignoreShapes;
6272 if ( !smoothNodes.empty() )
6274 vector<_Simplex> simplices;
6275 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
6276 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
6277 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
6278 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
6279 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
6283 // Find _LayerEdge's inflated along F
6286 set< TGeomID > subIDs;
6287 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false);
6288 while ( subIt->more() )
6289 subIDs.insert( subIt->next()->GetId() );
6292 for ( int iS = 0; iS < data._endEdgeOnShape.size() && !subIDs.empty(); ++iS )
6295 iEnd = data._endEdgeOnShape[ iS ];
6296 TGeomID shapeID = data._edges[ iBeg ]->_nodes[0]->getshapeId();
6297 set< TGeomID >::iterator idIt = subIDs.find( shapeID );
6298 if ( idIt == subIDs.end() ||
6299 data._edges[ iBeg ]->_sWOL.IsNull() ) continue;
6300 subIDs.erase( idIt );
6302 if ( !data._noShrinkShapes.count( shapeID ))
6303 for ( ; iBeg < iEnd; ++iBeg )
6305 lEdges.push_back( data._edges[ iBeg ] );
6306 prepareEdgeToShrink( *data._edges[ iBeg ], F, helper, smDS );
6311 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
6312 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6313 while ( fIt->more() )
6314 if ( const SMDS_MeshElement* f = fIt->next() )
6315 dumpChangeNodes( f );
6318 // Replace source nodes by target nodes in mesh faces to shrink
6319 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
6320 const SMDS_MeshNode* nodes[20];
6321 for ( size_t i = 0; i < lEdges.size(); ++i )
6323 _LayerEdge& edge = *lEdges[i];
6324 const SMDS_MeshNode* srcNode = edge._nodes[0];
6325 const SMDS_MeshNode* tgtNode = edge._nodes.back();
6326 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
6327 while ( fIt->more() )
6329 const SMDS_MeshElement* f = fIt->next();
6330 if ( !smDS->Contains( f ))
6332 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
6333 for ( int iN = 0; nIt->more(); ++iN )
6335 const SMDS_MeshNode* n = nIt->next();
6336 nodes[iN] = ( n == srcNode ? tgtNode : n );
6338 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
6339 dumpChangeNodes( f );
6344 // find out if a FACE is concave
6345 const bool isConcaveFace = isConcave( F, helper );
6347 // Create _SmoothNode's on face F
6348 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
6350 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
6351 const bool sortSimplices = isConcaveFace;
6352 for ( size_t i = 0; i < smoothNodes.size(); ++i )
6354 const SMDS_MeshNode* n = smoothNodes[i];
6355 nodesToSmooth[ i ]._node = n;
6356 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
6357 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
6358 // fix up incorrect uv of nodes on the FACE
6359 helper.GetNodeUV( F, n, 0, &isOkUV);
6364 //if ( nodesToSmooth.empty() ) continue;
6366 // Find EDGE's to shrink and set simpices to LayerEdge's
6367 set< _Shrinker1D* > eShri1D;
6369 for ( size_t i = 0; i < lEdges.size(); ++i )
6371 _LayerEdge* edge = lEdges[i];
6372 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
6374 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
6375 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
6376 eShri1D.insert( & srinker );
6377 srinker.AddEdge( edge, helper );
6378 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
6379 // restore params of nodes on EGDE if the EDGE has been already
6380 // srinked while srinking another FACE
6381 srinker.RestoreParams();
6383 _Simplex::GetSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
6387 bool toFixTria = false; // to improve quality of trias by diagonal swap
6388 if ( isConcaveFace )
6390 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
6391 if ( hasTria != hasQuad ) {
6392 toFixTria = hasTria;
6395 set<int> nbNodesSet;
6396 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6397 while ( fIt->more() && nbNodesSet.size() < 2 )
6398 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
6399 toFixTria = ( *nbNodesSet.begin() == 3 );
6403 // ==================
6404 // Perform shrinking
6405 // ==================
6407 bool shrinked = true;
6408 int badNb, shriStep=0, smooStep=0;
6409 _SmoothNode::SmoothType smoothType
6410 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
6414 // Move boundary nodes (actually just set new UV)
6415 // -----------------------------------------------
6416 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
6418 for ( size_t i = 0; i < lEdges.size(); ++i )
6420 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
6424 // Move nodes on EDGE's
6425 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
6426 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
6427 for ( ; shr != eShri1D.end(); ++shr )
6428 (*shr)->Compute( /*set3D=*/false, helper );
6431 // -----------------
6432 int nbNoImpSteps = 0;
6435 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
6437 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6439 int oldBadNb = badNb;
6442 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6444 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6445 smoothType, /*set3D=*/isConcaveFace);
6447 if ( badNb < oldBadNb )
6455 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
6456 if ( shriStep > 200 )
6457 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
6459 // Fix narrow triangles by swapping diagonals
6460 // ---------------------------------------
6463 set<const SMDS_MeshNode*> usedNodes;
6464 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
6466 // update working data
6467 set<const SMDS_MeshNode*>::iterator n;
6468 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
6470 n = usedNodes.find( nodesToSmooth[ i ]._node );
6471 if ( n != usedNodes.end())
6473 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
6474 nodesToSmooth[ i ]._simplices,
6476 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
6477 usedNodes.erase( n );
6480 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
6482 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
6483 if ( n != usedNodes.end())
6485 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
6486 lEdges[i]->_simplices,
6488 usedNodes.erase( n );
6492 // TODO: check effect of this additional smooth
6493 // additional laplacian smooth to increase allowed shrink step
6494 // for ( int st = 1; st; --st )
6496 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6497 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6499 // nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6500 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
6503 } // while ( shrinked )
6505 // No wrongly shaped faces remain; final smooth. Set node XYZ.
6506 bool isStructuredFixed = false;
6507 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
6508 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
6509 if ( !isStructuredFixed )
6511 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
6512 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
6514 for ( int st = 3; st; --st )
6517 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
6518 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
6519 case 3: smoothType = _SmoothNode::ANGULAR; break;
6521 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6522 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6524 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6525 smoothType,/*set3D=*/st==1 );
6530 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
6531 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
6533 if ( !getMeshDS()->IsEmbeddedMode() )
6534 // Log node movement
6535 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6537 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
6538 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
6541 } // loop on FACES to srink mesh on
6544 // Replace source nodes by target nodes in shrinked mesh edges
6546 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
6547 for ( ; e2shr != e2shrMap.end(); ++e2shr )
6548 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
6553 //================================================================================
6555 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
6557 //================================================================================
6559 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
6560 const TopoDS_Face& F,
6561 SMESH_MesherHelper& helper,
6562 const SMESHDS_SubMesh* faceSubMesh)
6564 const SMDS_MeshNode* srcNode = edge._nodes[0];
6565 const SMDS_MeshNode* tgtNode = edge._nodes.back();
6567 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
6569 gp_XY srcUV( edge._pos[0].X(), edge._pos[0].Y() );//helper.GetNodeUV( F, srcNode );
6570 gp_XY tgtUV = edge.LastUV( F ); //helper.GetNodeUV( F, tgtNode );
6571 gp_Vec2d uvDir( srcUV, tgtUV );
6572 double uvLen = uvDir.Magnitude();
6574 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
6577 edge._pos.resize(1);
6578 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
6580 // set UV of source node to target node
6581 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
6582 pos->SetUParameter( srcUV.X() );
6583 pos->SetVParameter( srcUV.Y() );
6585 else // _sWOL is TopAbs_EDGE
6587 const TopoDS_Edge& E = TopoDS::Edge( edge._sWOL );
6588 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
6589 if ( !edgeSM || edgeSM->NbElements() == 0 )
6590 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6592 const SMDS_MeshNode* n2 = 0;
6593 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
6594 while ( eIt->more() && !n2 )
6596 const SMDS_MeshElement* e = eIt->next();
6597 if ( !edgeSM->Contains(e)) continue;
6598 n2 = e->GetNode( 0 );
6599 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
6602 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6604 double uSrc = helper.GetNodeU( E, srcNode, n2 );
6605 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
6606 double u2 = helper.GetNodeU( E, n2, srcNode );
6610 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
6612 // tgtNode is located so that it does not make faces with wrong orientation
6615 edge._pos.resize(1);
6616 edge._pos[0].SetCoord( U_TGT, uTgt );
6617 edge._pos[0].SetCoord( U_SRC, uSrc );
6618 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
6620 edge._simplices.resize( 1 );
6621 edge._simplices[0]._nPrev = n2;
6623 // set U of source node to the target node
6624 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
6625 pos->SetUParameter( uSrc );
6630 //================================================================================
6632 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
6634 //================================================================================
6636 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
6638 if ( edge._nodes.size() == 1 )
6643 const SMDS_MeshNode* srcNode = edge._nodes[0];
6644 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
6645 if ( S.IsNull() ) return;
6649 switch ( S.ShapeType() )
6654 TopLoc_Location loc;
6655 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
6656 if ( curve.IsNull() ) return;
6657 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
6658 p = curve->Value( ePos->GetUParameter() );
6663 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
6668 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
6669 dumpMove( srcNode );
6673 //================================================================================
6675 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
6677 //================================================================================
6679 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
6680 SMESH_MesherHelper& helper,
6683 set<const SMDS_MeshNode*> * involvedNodes)
6685 SMESH::Controls::AspectRatio qualifier;
6686 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
6687 const double maxAspectRatio = is2D ? 4. : 2;
6688 _NodeCoordHelper xyz( F, helper, is2D );
6690 // find bad triangles
6692 vector< const SMDS_MeshElement* > badTrias;
6693 vector< double > badAspects;
6694 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
6695 SMDS_ElemIteratorPtr fIt = sm->GetElements();
6696 while ( fIt->more() )
6698 const SMDS_MeshElement * f = fIt->next();
6699 if ( f->NbCornerNodes() != 3 ) continue;
6700 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
6701 double aspect = qualifier.GetValue( points );
6702 if ( aspect > maxAspectRatio )
6704 badTrias.push_back( f );
6705 badAspects.push_back( aspect );
6710 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
6711 SMDS_ElemIteratorPtr fIt = sm->GetElements();
6712 while ( fIt->more() )
6714 const SMDS_MeshElement * f = fIt->next();
6715 if ( f->NbCornerNodes() == 3 )
6716 dumpChangeNodes( f );
6720 if ( badTrias.empty() )
6723 // find couples of faces to swap diagonal
6725 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
6726 vector< T2Trias > triaCouples;
6728 TIDSortedElemSet involvedFaces, emptySet;
6729 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
6732 double aspRatio [3];
6735 if ( !involvedFaces.insert( badTrias[iTia] ).second )
6737 for ( int iP = 0; iP < 3; ++iP )
6738 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
6740 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
6741 int bestCouple = -1;
6742 for ( int iSide = 0; iSide < 3; ++iSide )
6744 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
6745 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
6746 trias [iSide].first = badTrias[iTia];
6747 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
6749 if (( ! trias[iSide].second ) ||
6750 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
6751 ( ! sm->Contains( trias[iSide].second )))
6754 // aspect ratio of an adjacent tria
6755 for ( int iP = 0; iP < 3; ++iP )
6756 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
6757 double aspectInit = qualifier.GetValue( points2 );
6759 // arrange nodes as after diag-swaping
6760 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
6761 i3 = helper.WrapIndex( i1-1, 3 );
6763 i3 = helper.WrapIndex( i1+1, 3 );
6765 points1( 1+ iSide ) = points2( 1+ i3 );
6766 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
6768 // aspect ratio after diag-swaping
6769 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
6770 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
6773 // prevent inversion of a triangle
6774 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
6775 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
6776 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
6779 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
6783 if ( bestCouple >= 0 )
6785 triaCouples.push_back( trias[bestCouple] );
6786 involvedFaces.insert ( trias[bestCouple].second );
6790 involvedFaces.erase( badTrias[iTia] );
6793 if ( triaCouples.empty() )
6798 SMESH_MeshEditor editor( helper.GetMesh() );
6799 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
6800 for ( size_t i = 0; i < triaCouples.size(); ++i )
6802 dumpChangeNodes( triaCouples[i].first );
6803 dumpChangeNodes( triaCouples[i].second );
6804 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
6807 if ( involvedNodes )
6808 for ( size_t i = 0; i < triaCouples.size(); ++i )
6810 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
6811 triaCouples[i].first->end_nodes() );
6812 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
6813 triaCouples[i].second->end_nodes() );
6816 // just for debug dump resulting triangles
6817 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
6818 for ( size_t i = 0; i < triaCouples.size(); ++i )
6820 dumpChangeNodes( triaCouples[i].first );
6821 dumpChangeNodes( triaCouples[i].second );
6825 //================================================================================
6827 * \brief Move target node to it's final position on the FACE during shrinking
6829 //================================================================================
6831 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
6832 const TopoDS_Face& F,
6833 SMESH_MesherHelper& helper )
6836 return false; // already at the target position
6838 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
6840 if ( _sWOL.ShapeType() == TopAbs_FACE )
6842 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
6843 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
6844 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
6845 const double uvLen = tgtUV.Distance( curUV );
6846 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
6848 // Select shrinking step such that not to make faces with wrong orientation.
6849 double stepSize = 1e100;
6850 for ( size_t i = 0; i < _simplices.size(); ++i )
6852 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
6853 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
6854 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
6855 gp_XY dirN = uvN2 - uvN1;
6856 double det = uvDir.Crossed( dirN );
6857 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
6858 gp_XY dirN2Cur = curUV - uvN1;
6859 double step = dirN.Crossed( dirN2Cur ) / det;
6861 stepSize = Min( step, stepSize );
6864 if ( uvLen <= stepSize )
6869 else if ( stepSize > 0 )
6871 newUV = curUV + uvDir.XY() * stepSize * kSafe;
6877 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
6878 pos->SetUParameter( newUV.X() );
6879 pos->SetVParameter( newUV.Y() );
6882 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
6883 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6884 dumpMove( tgtNode );
6887 else // _sWOL is TopAbs_EDGE
6889 const TopoDS_Edge& E = TopoDS::Edge( _sWOL );
6890 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
6891 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
6893 const double u2 = helper.GetNodeU( E, n2, tgtNode );
6894 const double uSrc = _pos[0].Coord( U_SRC );
6895 const double lenTgt = _pos[0].Coord( LEN_TGT );
6897 double newU = _pos[0].Coord( U_TGT );
6898 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
6904 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
6906 tgtPos->SetUParameter( newU );
6908 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
6909 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
6910 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6911 dumpMove( tgtNode );
6917 //================================================================================
6919 * \brief Perform smooth on the FACE
6920 * \retval bool - true if the node has been moved
6922 //================================================================================
6924 bool _SmoothNode::Smooth(int& badNb,
6925 Handle(Geom_Surface)& surface,
6926 SMESH_MesherHelper& helper,
6927 const double refSign,
6931 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
6933 // get uv of surrounding nodes
6934 vector<gp_XY> uv( _simplices.size() );
6935 for ( size_t i = 0; i < _simplices.size(); ++i )
6936 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
6938 // compute new UV for the node
6940 if ( how == TFI && _simplices.size() == 4 )
6943 for ( size_t i = 0; i < _simplices.size(); ++i )
6944 if ( _simplices[i]._nOpp )
6945 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
6947 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
6949 newPos = helper.calcTFI ( 0.5, 0.5,
6950 corners[0], corners[1], corners[2], corners[3],
6951 uv[1], uv[2], uv[3], uv[0] );
6953 else if ( how == ANGULAR )
6955 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
6957 else if ( how == CENTROIDAL && _simplices.size() > 3 )
6959 // average centers of diagonals wieghted with their reciprocal lengths
6960 if ( _simplices.size() == 4 )
6962 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
6963 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
6964 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
6968 double sumWeight = 0;
6969 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
6970 for ( int i = 0; i < nb; ++i )
6973 int iTo = i + _simplices.size() - 1;
6974 for ( int j = iFrom; j < iTo; ++j )
6976 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
6977 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
6979 newPos += w * ( uv[i]+uv[i2] );
6982 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
6988 for ( size_t i = 0; i < _simplices.size(); ++i )
6990 newPos /= _simplices.size();
6993 // count quality metrics (orientation) of triangles around the node
6995 gp_XY tgtUV = helper.GetNodeUV( face, _node );
6996 for ( size_t i = 0; i < _simplices.size(); ++i )
6997 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
7000 for ( size_t i = 0; i < _simplices.size(); ++i )
7001 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
7003 if ( nbOkAfter < nbOkBefore )
7005 badNb += _simplices.size() - nbOkBefore;
7009 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
7010 pos->SetUParameter( newPos.X() );
7011 pos->SetVParameter( newPos.Y() );
7018 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
7019 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
7023 badNb += _simplices.size() - nbOkAfter;
7024 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
7027 //================================================================================
7029 * \brief Computes new UV using angle based smoothing technic
7031 //================================================================================
7033 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
7034 const gp_XY& uvToFix,
7035 const double refSign)
7037 uv.push_back( uv.front() );
7039 vector< gp_XY > edgeDir ( uv.size() );
7040 vector< double > edgeSize( uv.size() );
7041 for ( size_t i = 1; i < edgeDir.size(); ++i )
7043 edgeDir [i-1] = uv[i] - uv[i-1];
7044 edgeSize[i-1] = edgeDir[i-1].Modulus();
7045 if ( edgeSize[i-1] < numeric_limits<double>::min() )
7046 edgeDir[i-1].SetX( 100 );
7048 edgeDir[i-1] /= edgeSize[i-1] * refSign;
7050 edgeDir.back() = edgeDir.front();
7051 edgeSize.back() = edgeSize.front();
7056 for ( size_t i = 1; i < edgeDir.size(); ++i )
7058 if ( edgeDir[i-1].X() > 1. ) continue;
7060 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
7061 if ( i == edgeDir.size() ) break;
7063 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
7064 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
7065 gp_XY bisec = norm1 + norm2;
7066 double bisecSize = bisec.Modulus();
7067 if ( bisecSize < numeric_limits<double>::min() )
7069 bisec = -edgeDir[i1] + edgeDir[i];
7070 bisecSize = bisec.Modulus();
7074 gp_XY dirToN = uvToFix - p;
7075 double distToN = dirToN.Modulus();
7076 if ( bisec * dirToN < 0 )
7079 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
7081 sumSize += edgeSize[i1] + edgeSize[i];
7083 newPos /= /*nbEdges * */sumSize;
7087 //================================================================================
7089 * \brief Delete _SolidData
7091 //================================================================================
7093 _SolidData::~_SolidData()
7095 for ( size_t i = 0; i < _edges.size(); ++i )
7097 if ( _edges[i] && _edges[i]->_2neibors )
7098 delete _edges[i]->_2neibors;
7103 //================================================================================
7105 * \brief Add a _LayerEdge inflated along the EDGE
7107 //================================================================================
7109 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
7112 if ( _nodes.empty() )
7114 _edges[0] = _edges[1] = 0;
7118 if ( e == _edges[0] || e == _edges[1] )
7120 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
7121 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7122 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
7123 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7126 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
7128 BRep_Tool::Range( E, f,l );
7129 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
7130 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
7134 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
7135 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
7137 if ( _nodes.empty() )
7139 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
7140 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
7142 TopLoc_Location loc;
7143 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
7144 GeomAdaptor_Curve aCurve(C, f,l);
7145 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
7147 int nbExpectNodes = eSubMesh->NbNodes();
7148 _initU .reserve( nbExpectNodes );
7149 _normPar.reserve( nbExpectNodes );
7150 _nodes .reserve( nbExpectNodes );
7151 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
7152 while ( nIt->more() )
7154 const SMDS_MeshNode* node = nIt->next();
7155 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
7156 node == tgtNode0 || node == tgtNode1 )
7157 continue; // refinement nodes
7158 _nodes.push_back( node );
7159 _initU.push_back( helper.GetNodeU( E, node ));
7160 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
7161 _normPar.push_back( len / totLen );
7166 // remove target node of the _LayerEdge from _nodes
7168 for ( size_t i = 0; i < _nodes.size(); ++i )
7169 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
7170 _nodes[i] = 0, nbFound++;
7171 if ( nbFound == _nodes.size() )
7176 //================================================================================
7178 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
7180 //================================================================================
7182 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
7184 if ( _done || _nodes.empty())
7186 const _LayerEdge* e = _edges[0];
7187 if ( !e ) e = _edges[1];
7190 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
7191 ( !_edges[1] || _edges[1]->_pos.empty() ));
7193 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
7195 if ( set3D || _done )
7197 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
7198 GeomAdaptor_Curve aCurve(C, f,l);
7201 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
7203 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
7204 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
7206 for ( size_t i = 0; i < _nodes.size(); ++i )
7208 if ( !_nodes[i] ) continue;
7209 double len = totLen * _normPar[i];
7210 GCPnts_AbscissaPoint discret( aCurve, len, f );
7211 if ( !discret.IsDone() )
7212 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
7213 double u = discret.Parameter();
7214 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7215 pos->SetUParameter( u );
7216 gp_Pnt p = C->Value( u );
7217 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
7222 BRep_Tool::Range( E, f,l );
7224 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
7226 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
7228 for ( size_t i = 0; i < _nodes.size(); ++i )
7230 if ( !_nodes[i] ) continue;
7231 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
7232 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7233 pos->SetUParameter( u );
7238 //================================================================================
7240 * \brief Restore initial parameters of nodes on EDGE
7242 //================================================================================
7244 void _Shrinker1D::RestoreParams()
7247 for ( size_t i = 0; i < _nodes.size(); ++i )
7249 if ( !_nodes[i] ) continue;
7250 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7251 pos->SetUParameter( _initU[i] );
7256 //================================================================================
7258 * \brief Replace source nodes by target nodes in shrinked mesh edges
7260 //================================================================================
7262 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
7264 const SMDS_MeshNode* nodes[3];
7265 for ( int i = 0; i < 2; ++i )
7267 if ( !_edges[i] ) continue;
7269 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
7270 if ( !eSubMesh ) return;
7271 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
7272 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
7273 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
7274 while ( eIt->more() )
7276 const SMDS_MeshElement* e = eIt->next();
7277 if ( !eSubMesh->Contains( e ))
7279 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7280 for ( int iN = 0; iN < e->NbNodes(); ++iN )
7282 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
7283 nodes[iN] = ( n == srcNode ? tgtNode : n );
7285 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
7290 //================================================================================
7292 * \brief Creates 2D and 1D elements on boundaries of new prisms
7294 //================================================================================
7296 bool _ViscousBuilder::addBoundaryElements()
7298 SMESH_MesherHelper helper( *_mesh );
7300 vector< const SMDS_MeshNode* > faceNodes;
7302 for ( size_t i = 0; i < _sdVec.size(); ++i )
7304 _SolidData& data = _sdVec[i];
7305 TopTools_IndexedMapOfShape geomEdges;
7306 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
7307 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
7309 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
7310 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
7313 // Get _LayerEdge's based on E
7315 map< double, const SMDS_MeshNode* > u2nodes;
7316 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
7319 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
7320 TNode2Edge & n2eMap = data._n2eMap;
7321 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
7323 //check if 2D elements are needed on E
7324 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
7325 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
7326 ledges.push_back( n2e->second );
7328 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
7329 continue; // no layers on E
7330 ledges.push_back( n2eMap[ u2n->second ]);
7332 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
7333 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
7334 int nbSharedPyram = 0;
7335 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
7336 while ( vIt->more() )
7338 const SMDS_MeshElement* v = vIt->next();
7339 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
7341 if ( nbSharedPyram > 1 )
7342 continue; // not free border of the pyramid
7345 faceNodes.push_back( ledges[0]->_nodes[0] );
7346 faceNodes.push_back( ledges[1]->_nodes[0] );
7347 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
7348 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
7350 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
7351 continue; // faces already created
7353 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
7354 ledges.push_back( n2eMap[ u2n->second ]);
7356 // Find out orientation and type of face to create
7358 bool reverse = false, isOnFace;
7360 map< TGeomID, TopoDS_Shape >::iterator e2f =
7361 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
7363 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
7365 F = e2f->second.Oriented( TopAbs_FORWARD );
7366 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
7367 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
7368 reverse = !reverse, F.Reverse();
7369 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
7374 // find FACE with layers sharing E
7375 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
7376 while ( fIt->more() && F.IsNull() )
7378 const TopoDS_Shape* pF = fIt->next();
7379 if ( helper.IsSubShape( *pF, data._solid) &&
7380 !data._ignoreFaceIds.count( e2f->first ))
7384 // Find the sub-mesh to add new faces
7385 SMESHDS_SubMesh* sm = 0;
7387 sm = getMeshDS()->MeshElements( F );
7389 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
7391 return error("error in addBoundaryElements()", data._index);
7394 const int dj1 = reverse ? 0 : 1;
7395 const int dj2 = reverse ? 1 : 0;
7396 for ( size_t j = 1; j < ledges.size(); ++j )
7398 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
7399 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
7400 if ( nn1.size() == nn2.size() )
7403 for ( size_t z = 1; z < nn1.size(); ++z )
7404 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7406 for ( size_t z = 1; z < nn1.size(); ++z )
7407 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7409 else if ( nn1.size() == 1 )
7412 for ( size_t z = 1; z < nn2.size(); ++z )
7413 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
7415 for ( size_t z = 1; z < nn2.size(); ++z )
7416 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
7421 for ( size_t z = 1; z < nn1.size(); ++z )
7422 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
7424 for ( size_t z = 1; z < nn1.size(); ++z )
7425 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
7430 for ( int isFirst = 0; isFirst < 2; ++isFirst )
7432 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
7433 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
7435 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
7436 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
7438 helper.SetSubShape( edge->_sWOL );
7439 helper.SetElementsOnShape( true );
7440 for ( size_t z = 1; z < nn.size(); ++z )
7441 helper.AddEdge( nn[z-1], nn[z] );