1 // Copyright (C) 2007-2021 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 "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_Quadrangle_2D.hxx"
53 #include "StdMeshers_ViscousLayers2D.hxx"
55 #include <Adaptor3d_HSurface.hxx>
56 #include <BRepAdaptor_Curve.hxx>
57 #include <BRepAdaptor_Curve2d.hxx>
58 #include <BRepAdaptor_Surface.hxx>
59 #include <BRepLProp_SLProps.hxx>
60 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_B2d.hxx>
63 #include <Bnd_B3d.hxx>
65 #include <GCPnts_AbscissaPoint.hxx>
66 #include <GCPnts_TangentialDeflection.hxx>
67 #include <Geom2d_Circle.hxx>
68 #include <Geom2d_Line.hxx>
69 #include <Geom2d_TrimmedCurve.hxx>
70 #include <GeomAdaptor_Curve.hxx>
71 #include <GeomLib.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Line.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Precision.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <Standard_Failure.hxx>
79 #include <TColStd_Array1OfReal.hxx>
81 #include <TopExp_Explorer.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListOfShape.hxx>
84 #include <TopTools_MapIteratorOfMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
87 #include <TopoDS_Edge.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Vertex.hxx>
91 #include <gp_Cone.hxx>
92 #include <gp_Sphere.hxx>
101 #include <unordered_map>
107 //#define __NOT_INVALIDATE_BAD_SMOOTH
108 //#define __NODES_AT_POS
111 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
112 #define BLOCK_INFLATION // of individual _LayerEdge's
113 #define OLD_NEF_POLYGON
117 //================================================================================
122 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
124 const double theMinSmoothCosin = 0.1;
125 const double theSmoothThickToElemSizeRatio = 0.6;
126 const double theMinSmoothTriaAngle = 30;
127 const double theMinSmoothQuadAngle = 45;
129 // what part of thickness is allowed till intersection
130 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
131 const double theThickToIntersection = 1.5;
133 bool needSmoothing( double cosin, double tgtThick, double elemSize )
135 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
137 double getSmoothingThickness( double cosin, double elemSize )
139 return theSmoothThickToElemSizeRatio * elemSize / cosin;
143 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
144 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
146 struct _MeshOfSolid : public SMESH_ProxyMesh,
147 public SMESH_subMeshEventListenerData
149 bool _n2nMapComputed;
150 SMESH_ComputeErrorPtr _warning;
152 _MeshOfSolid( SMESH_Mesh* mesh)
153 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
155 SMESH_ProxyMesh::setMesh( *mesh );
158 // returns submesh for a geom face
159 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
161 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
162 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
164 void setNode2Node(const SMDS_MeshNode* srcNode,
165 const SMDS_MeshNode* proxyNode,
166 const SMESH_ProxyMesh::SubMesh* subMesh)
168 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
171 //--------------------------------------------------------------------------------
173 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
174 * It is used to clear an inferior dim sub-meshes modified by viscous layers
176 class _ShrinkShapeListener : SMESH_subMeshEventListener
178 _ShrinkShapeListener()
179 : SMESH_subMeshEventListener(/*isDeletable=*/false,
180 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
182 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
183 virtual void ProcessEvent(const int event,
185 SMESH_subMesh* solidSM,
186 SMESH_subMeshEventListenerData* data,
187 const SMESH_Hypothesis* hyp)
189 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
191 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
195 //--------------------------------------------------------------------------------
197 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
198 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
199 * delete the data as soon as it has been used
201 class _ViscousListener : SMESH_subMeshEventListener
204 SMESH_subMeshEventListener(/*isDeletable=*/false,
205 "StdMeshers_ViscousLayers::_ViscousListener") {}
206 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
208 virtual void ProcessEvent(const int event,
210 SMESH_subMesh* subMesh,
211 SMESH_subMeshEventListenerData* /*data*/,
212 const SMESH_Hypothesis* /*hyp*/)
214 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
215 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
216 SMESH_subMesh::SUBMESH_COMPUTED != event ))
218 // delete SMESH_ProxyMesh containing temporary faces
219 subMesh->DeleteEventListener( this );
222 // Finds or creates proxy mesh of the solid
223 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
224 const TopoDS_Shape& solid,
227 if ( !mesh ) return 0;
228 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
229 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
230 if ( !data && toCreate )
232 data = new _MeshOfSolid(mesh);
233 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
234 sm->SetEventListener( Get(), data, sm );
238 // Removes proxy mesh of the solid
239 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
241 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
245 //================================================================================
247 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
248 * the main shape when sub-mesh of the main shape is cleared,
249 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
252 //================================================================================
254 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
256 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
257 SMESH_subMeshEventListenerData* data =
258 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
261 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
262 data->mySubMeshes.end())
263 data->mySubMeshes.push_back( sub );
267 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
268 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
272 //--------------------------------------------------------------------------------
274 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
275 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
276 * The class is used to check validity of face or volumes around a smoothed node;
277 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
281 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
282 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
283 _Simplex(const SMDS_MeshNode* nPrev=0,
284 const SMDS_MeshNode* nNext=0,
285 const SMDS_MeshNode* nOpp=0)
286 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
287 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
289 const double M[3][3] =
290 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
291 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
292 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
293 vol = ( + M[0][0] * M[1][1] * M[2][2]
294 + M[0][1] * M[1][2] * M[2][0]
295 + M[0][2] * M[1][0] * M[2][1]
296 - M[0][0] * M[1][2] * M[2][1]
297 - M[0][1] * M[1][0] * M[2][2]
298 - M[0][2] * M[1][1] * M[2][0]);
301 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
303 SMESH_TNodeXYZ pSrc( nSrc );
304 return IsForward( &pSrc, &pTgt, vol );
306 bool IsForward(const gp_XY& tgtUV,
307 const SMDS_MeshNode* smoothedNode,
308 const TopoDS_Face& face,
309 SMESH_MesherHelper& helper,
310 const double refSign) const
312 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
313 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
314 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
316 return d*refSign > 1e-100;
318 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
320 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
321 if ( !_nOpp ) // triangle
323 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
324 double tp2 = tp.SquareMagnitude();
325 double pn2 = pn.SquareMagnitude();
326 double nt2 = nt.SquareMagnitude();
328 if ( tp2 < pn2 && tp2 < nt2 )
329 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
330 else if ( pn2 < nt2 )
331 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
333 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
335 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
336 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
337 return minAngle < theMaxCos2;
341 SMESH_TNodeXYZ pOpp( _nOpp );
342 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
343 double tp2 = tp.SquareMagnitude();
344 double po2 = po.SquareMagnitude();
345 double on2 = on.SquareMagnitude();
346 double nt2 = nt.SquareMagnitude();
347 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
348 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
349 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
350 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
352 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
353 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
354 return minAngle < theMaxCos2;
357 bool IsNeighbour(const _Simplex& other) const
359 return _nPrev == other._nNext || _nNext == other._nPrev;
361 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
362 static void GetSimplices( const SMDS_MeshNode* node,
363 vector<_Simplex>& simplices,
364 const set<TGeomID>& ingnoreShapes,
365 const _SolidData* dataToCheckOri = 0,
366 const bool toSort = false);
367 static void SortSimplices(vector<_Simplex>& simplices);
369 //--------------------------------------------------------------------------------
371 * Structure used to take into account surface curvature while smoothing
376 double _k; // factor to correct node smoothed position
377 double _h2lenRatio; // avgNormProj / (2*avgDist)
378 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
380 static _Curvature* New( double avgNormProj, double avgDist );
381 double lenDelta(double len) const { return _k * ( _r + len ); }
382 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
384 //--------------------------------------------------------------------------------
388 struct _EdgesOnShape;
391 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
393 //--------------------------------------------------------------------------------
395 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
396 * and a node of the most internal layer (_nodes.back())
400 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
402 vector< const SMDS_MeshNode*> _nodes;
404 gp_XYZ _normal; // to boundary of solid
405 vector<gp_XYZ> _pos; // points computed during inflation
406 double _len; // length achieved with the last inflation step
407 double _maxLen; // maximal possible length
408 double _cosin; // of angle (_normal ^ surface)
409 double _minAngle; // of _simplices
410 double _lenFactor; // to compute _len taking _cosin into account
413 // simplices connected to the source node (_nodes[0]);
414 // used for smoothing and quality check of _LayerEdge's based on the FACE
415 vector<_Simplex> _simplices;
416 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
417 PSmooFun _smooFunction; // smoothing function
418 _Curvature* _curvature;
419 // data for smoothing of _LayerEdge's based on the EDGE
420 _2NearEdges* _2neibors;
422 enum EFlags { TO_SMOOTH = 0x0000001,
423 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
424 SMOOTHED = 0x0000004, // set by _LayerEdge::Smooth()
425 DIFFICULT = 0x0000008, // near concave VERTEX
426 ON_CONCAVE_FACE = 0x0000010,
427 BLOCKED = 0x0000020, // not to inflate any more
428 INTERSECTED = 0x0000040, // close intersection with a face found
429 NORMAL_UPDATED = 0x0000080,
430 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
431 MARKED = 0x0000200, // local usage
432 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
433 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
434 SMOOTHED_C1 = 0x0001000, // is on _eosC1
435 DISTORTED = 0x0002000, // was bad before smoothing
436 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
437 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
438 UNUSED_FLAG = 0x0100000 // to add user flags after
440 bool Is ( int flag ) const { return _flags & flag; }
441 void Set ( int flag ) { _flags |= flag; }
442 void Unset( int flag ) { _flags &= ~flag; }
443 std::string DumpFlags() const; // debug
445 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
446 bool SetNewLength2d( Handle(Geom_Surface)& surface,
447 const TopoDS_Face& F,
449 SMESH_MesherHelper& helper );
450 bool UpdatePositionOnSWOL( SMDS_MeshNode* n,
453 SMESH_MesherHelper& helper );
454 void SetDataByNeighbors( const SMDS_MeshNode* n1,
455 const SMDS_MeshNode* n2,
456 const _EdgesOnShape& eos,
457 SMESH_MesherHelper& helper);
458 void Block( _SolidData& data );
459 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
460 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
461 const TNode2Edge& n2eMap);
462 void SmoothPos( const vector< double >& segLen, const double tol );
463 int GetSmoothedPos( const double tol );
464 int Smooth(const int step, const bool isConcaveFace, bool findBest);
465 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
466 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
467 void SmoothWoCheck();
468 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
469 const TopoDS_Face& F,
470 SMESH_MesherHelper& helper);
471 void MoveNearConcaVer( const _EdgesOnShape* eov,
472 const _EdgesOnShape* eos,
474 vector< _LayerEdge* > & badSmooEdges);
475 bool FindIntersection( SMESH_ElementSearcher& searcher,
477 const double& epsilon,
479 const SMDS_MeshElement** face = 0);
480 bool SegTriaInter( const gp_Ax1& lastSegment,
485 const double& epsilon) const;
486 bool SegTriaInter( const gp_Ax1& lastSegment,
487 const SMDS_MeshNode* n0,
488 const SMDS_MeshNode* n1,
489 const SMDS_MeshNode* n2,
491 const double& epsilon) const
492 { return SegTriaInter( lastSegment,
493 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
496 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
497 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
498 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
499 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
500 bool IsOnEdge() const { return _2neibors; }
501 bool IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
502 int BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
503 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
504 double SetCosin( double cosin );
505 void SetNormal( const gp_XYZ& n ) { _normal = n; }
506 void SetMaxLen( double l ) { _maxLen = l; }
507 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
508 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
509 void SetSmooLen( double len ) { // set _len at which smoothing is needed
510 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
512 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
514 gp_XYZ smoothLaplacian();
515 gp_XYZ smoothAngular();
516 gp_XYZ smoothLengthWeighted();
517 gp_XYZ smoothCentroidal();
518 gp_XYZ smoothNefPolygon();
520 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
521 static const int theNbSmooFuns = FUN_NB;
522 static PSmooFun _funs[theNbSmooFuns];
523 static const char* _funNames[theNbSmooFuns+1];
524 int smooFunID( PSmooFun fun=0) const;
526 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
527 &_LayerEdge::smoothLengthWeighted,
528 &_LayerEdge::smoothCentroidal,
529 &_LayerEdge::smoothNefPolygon,
530 &_LayerEdge::smoothAngular };
531 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
539 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
541 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
542 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
545 //--------------------------------------------------------------------------------
547 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
551 gp_XY _pos, _dir, _inNorm;
552 bool IsOut( const gp_XY p, const double tol ) const
554 return _inNorm * ( p - _pos ) < -tol;
556 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
558 //const double eps = 1e-10;
559 double D = _dir.Crossed( hp._dir );
560 if ( fabs(D) < std::numeric_limits<double>::min())
562 gp_XY vec21 = _pos - hp._pos;
563 double u = hp._dir.Crossed( vec21 ) / D;
564 intPnt = _pos + _dir * u;
568 //--------------------------------------------------------------------------------
570 * Structure used to smooth a _LayerEdge based on an EDGE.
574 double _wgt [2]; // weights of _nodes
575 _LayerEdge* _edges[2];
577 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
580 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
581 ~_2NearEdges(){ delete _plnNorm; }
582 const SMDS_MeshNode* tgtNode(bool is2nd) {
583 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
585 const SMDS_MeshNode* srcNode(bool is2nd) {
586 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
589 std::swap( _wgt [0], _wgt [1] );
590 std::swap( _edges[0], _edges[1] );
592 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
593 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
595 bool include( const _LayerEdge* e ) {
596 return ( _edges[0] == e || _edges[1] == e );
601 //--------------------------------------------------------------------------------
603 * \brief Layers parameters got by averaging several hypotheses
607 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
608 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
612 void Add( const StdMeshers_ViscousLayers* hyp )
617 _nbLayers = hyp->GetNumberLayers();
618 //_thickness += hyp->GetTotalThickness();
619 _thickness = Max( _thickness, hyp->GetTotalThickness() );
620 _stretchFactor += hyp->GetStretchFactor();
621 _method = hyp->GetMethod();
622 if ( _groupName.empty() )
623 _groupName = hyp->GetGroupName();
626 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
627 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
628 int GetNumberLayers() const { return _nbLayers; }
629 int GetMethod() const { return _method; }
630 bool ToCreateGroup() const { return !_groupName.empty(); }
631 const std::string& GetGroupName() const { return _groupName; }
633 double Get1stLayerThickness( double realThickness = 0.) const
635 const double T = ( realThickness > 0 ) ? realThickness : GetTotalThickness();
636 const double f = GetStretchFactor();
637 const int N = GetNumberLayers();
638 const double fPowN = pow( f, N );
640 if ( fPowN - 1 <= numeric_limits<double>::min() )
643 h0 = T * ( f - 1 )/( fPowN - 1 );
647 bool UseSurfaceNormal() const
648 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
649 bool ToSmooth() const
650 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
651 bool IsOffsetMethod() const
652 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
654 bool operator==( const AverageHyp& other ) const
656 return ( _nbLayers == other._nbLayers &&
657 _method == other._method &&
658 Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
659 Equals( GetStretchFactor(), other.GetStretchFactor() ));
661 static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
664 int _nbLayers, _nbHyps, _method;
665 double _thickness, _stretchFactor;
666 std::string _groupName;
669 //--------------------------------------------------------------------------------
671 * \brief _LayerEdge's on a shape and other shape data
675 vector< _LayerEdge* > _edges;
679 SMESH_subMesh * _subMesh;
680 // face or edge w/o layer along or near which _edges are inflated
682 bool _isRegularSWOL; // w/o singularities
683 // averaged StdMeshers_ViscousLayers parameters
686 _Smoother1D* _edgeSmoother;
687 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
688 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
690 typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
691 TFace2NormMap _faceNormals; // if _shape is FACE
692 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
694 Handle(ShapeAnalysis_Surface) _offsetSurf;
695 _LayerEdge* _edgeForOffset;
697 _Mapper2D* _mapper2D;
699 _SolidData* _data; // parent SOLID
701 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
702 size_t size() const { return _edges.size(); }
703 TopAbs_ShapeEnum ShapeType() const
704 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
705 TopAbs_ShapeEnum SWOLType() const
706 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
707 bool HasC1( const _EdgesOnShape* other ) const
708 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
709 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
710 _SolidData& GetData() const { return *_data; }
711 char ShapeTypeLetter() const
712 { switch ( ShapeType() ) { case TopAbs_FACE: return 'F'; case TopAbs_EDGE: return 'E';
713 case TopAbs_VERTEX: return 'V'; default: return 'S'; }}
715 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0), _mapper2D(0) {}
719 //--------------------------------------------------------------------------------
721 * \brief Convex FACE whose radius of curvature is less than the thickness of
722 * layers. It is used to detect distortion of prisms based on a convex
723 * FACE and to update normals to enable further increasing the thickness
729 // edges whose _simplices are used to detect prism distortion
730 vector< _LayerEdge* > _simplexTestEdges;
732 // map a sub-shape to _SolidData::_edgesOnShape
733 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
737 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
739 double GetMaxCurvature( _SolidData& data,
741 BRepLProp_SLProps& surfProp,
742 SMESH_MesherHelper& helper);
744 bool GetCenterOfCurvature( _LayerEdge* ledge,
745 BRepLProp_SLProps& surfProp,
746 SMESH_MesherHelper& helper,
747 gp_Pnt & center ) const;
748 bool CheckPrisms() const;
751 //--------------------------------------------------------------------------------
753 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
754 * at inflation up to the full thickness. A detected collision
755 * is fixed in updateNormals()
757 struct _CollisionEdges
760 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
761 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
762 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
765 //--------------------------------------------------------------------------------
767 * \brief Data of a SOLID
771 typedef const StdMeshers_ViscousLayers* THyp;
773 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
774 TGeomID _index; // SOLID id
775 _MeshOfSolid* _proxyMesh;
778 list< TopoDS_Shape > _hypShapes;
779 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
780 set< TGeomID > _reversedFaceIds;
781 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
783 double _stepSize, _stepSizeCoeff, _geomSize;
784 const SMDS_MeshNode* _stepSizeNodes[2];
786 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
788 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
789 map< TGeomID, TNode2Edge* > _s2neMap;
790 // _LayerEdge's with underlying shapes
791 vector< _EdgesOnShape > _edgesOnShape;
793 // key: an ID of shape (EDGE or VERTEX) shared by a FACE with
794 // layers and a FACE w/o layers
795 // value: the shape (FACE or EDGE) to shrink mesh on.
796 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
797 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
799 // Convex FACEs whose radius of curvature is less than the thickness of layers
800 map< TGeomID, _ConvexFace > _convexFaces;
802 // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
803 // the adjacent SOLID
804 set< TGeomID > _noShrinkShapes;
806 int _nbShapesToSmooth;
808 vector< _CollisionEdges > _collisionEdges;
809 set< TGeomID > _concaveFaces;
811 double _maxThickness; // of all _hyps
812 double _minThickness; // of all _hyps
814 double _epsilon; // precision for SegTriaInter()
816 SMESH_MesherHelper* _helper;
818 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
820 :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
821 ~_SolidData() { delete _helper; _helper = 0; }
823 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
824 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
826 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
827 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
828 return id2face == _convexFaces.end() ? 0 : & id2face->second;
830 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
831 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
832 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
833 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
835 SMESH_MesherHelper& GetHelper() const { return *_helper; }
837 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
838 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
839 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
840 _edgesOnShape[i]._edges[j]->Unset( flag );
842 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
843 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
845 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
847 //--------------------------------------------------------------------------------
849 * \brief Offset plane used in getNormalByOffset()
855 int _faceIndexNext[2];
856 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
859 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
861 void ComputeIntersectionLine( _OffsetPlane& pln,
862 const TopoDS_Edge& E,
863 const TopoDS_Vertex& V );
864 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
865 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
867 //--------------------------------------------------------------------------------
869 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
871 struct _CentralCurveOnEdge
874 vector< gp_Pnt > _curvaCenters;
875 vector< _LayerEdge* > _ledges;
876 vector< gp_XYZ > _normals; // new normal for each of _ledges
877 vector< double > _segLength2;
880 TopoDS_Face _adjFace;
881 bool _adjFaceToSmooth;
883 void Append( const gp_Pnt& center, _LayerEdge* ledge )
885 if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
887 if ( _curvaCenters.size() > 0 )
888 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
889 _curvaCenters.push_back( center );
890 _ledges.push_back( ledge );
891 _normals.push_back( ledge->_normal );
893 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
894 void SetShapes( const TopoDS_Edge& edge,
895 const _ConvexFace& convFace,
897 SMESH_MesherHelper& helper);
899 //--------------------------------------------------------------------------------
901 * \brief Data of node on a shrinked FACE
905 const SMDS_MeshNode* _node;
906 vector<_Simplex> _simplices; // for quality check
908 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
910 bool Smooth(int& badNb,
911 Handle(Geom_Surface)& surface,
912 SMESH_MesherHelper& helper,
913 const double refSign,
917 gp_XY computeAngularPos(vector<gp_XY>& uv,
918 const gp_XY& uvToFix,
919 const double refSign );
923 //--------------------------------------------------------------------------------
925 * \brief Builder of viscous layers
927 class _ViscousBuilder
932 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
933 const TopoDS_Shape& shape);
934 // check validity of hypotheses
935 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
936 const TopoDS_Shape& shape );
938 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
939 void RestoreListeners();
941 // computes SMESH_ProxyMesh::SubMesh::_n2n;
942 bool MakeN2NMap( _MeshOfSolid* pm );
946 bool findSolidsWithLayers(const bool checkFaceMesh=true);
947 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
948 bool findFacesWithLayers(const bool onlyWith=false);
949 void findPeriodicFaces();
950 void getIgnoreFaces(const TopoDS_Shape& solid,
951 const StdMeshers_ViscousLayers* hyp,
952 const TopoDS_Shape& hypShape,
953 set<TGeomID>& ignoreFaces);
954 int makeEdgesOnShape();
955 bool makeLayer(_SolidData& data);
956 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
957 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
958 SMESH_MesherHelper& helper, _SolidData& data);
959 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
960 const TopoDS_Face& face,
961 SMESH_MesherHelper& helper,
963 bool shiftInside=false);
964 bool getFaceNormalAtSingularity(const gp_XY& uv,
965 const TopoDS_Face& face,
966 SMESH_MesherHelper& helper,
968 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
969 gp_XYZ getNormalByOffset( _LayerEdge* edge,
970 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
972 bool lastNoOffset = false);
973 bool findNeiborsOnEdge(const _LayerEdge* edge,
974 const SMDS_MeshNode*& n1,
975 const SMDS_MeshNode*& n2,
978 void findSimplexTestEdges( _SolidData& data,
979 vector< vector<_LayerEdge*> >& edgesByGeom);
980 void computeGeomSize( _SolidData& data );
981 bool findShapesToSmooth( _SolidData& data);
982 void limitStepSizeByCurvature( _SolidData& data );
983 void limitStepSize( _SolidData& data,
984 const SMDS_MeshElement* face,
985 const _LayerEdge* maxCosinEdge );
986 void limitStepSize( _SolidData& data, const double minSize);
987 bool inflate(_SolidData& data);
988 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
989 int invalidateBadSmooth( _SolidData& data,
990 SMESH_MesherHelper& helper,
991 vector< _LayerEdge* >& badSmooEdges,
992 vector< _EdgesOnShape* >& eosC1,
994 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
995 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
996 vector< _EdgesOnShape* >& eosC1,
997 int smooStep=0, int moveAll=false );
998 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
999 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
1001 SMESH_MesherHelper& helper );
1002 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
1003 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
1004 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
1005 const bool isSmoothable );
1006 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
1007 bool updateNormalsOfConvexFaces( _SolidData& data,
1008 SMESH_MesherHelper& helper,
1010 void updateNormalsOfC1Vertices( _SolidData& data );
1011 bool updateNormalsOfSmoothed( _SolidData& data,
1012 SMESH_MesherHelper& helper,
1014 const double stepSize );
1015 bool isNewNormalOk( _SolidData& data,
1017 const gp_XYZ& newNormal);
1018 bool refine(_SolidData& data);
1019 bool shrink(_SolidData& data);
1020 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
1021 SMESH_MesherHelper& helper,
1022 const SMESHDS_SubMesh* faceSubMesh );
1023 void restoreNoShrink( _LayerEdge& edge ) const;
1024 void fixBadFaces(const TopoDS_Face& F,
1025 SMESH_MesherHelper& helper,
1028 set<const SMDS_MeshNode*> * involvedNodes=NULL);
1029 bool addBoundaryElements(_SolidData& data);
1031 bool error( const string& text, int solidID=-1 );
1032 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1035 void makeGroupOfLE();
1038 SMESH_ComputeErrorPtr _error;
1040 vector< _SolidData > _sdVec;
1041 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1042 TopTools_MapOfShape _shrunkFaces;
1043 std::unique_ptr<Periodicity> _periodicity;
1048 //--------------------------------------------------------------------------------
1050 * \brief Shrinker of nodes on the EDGE
1054 TopoDS_Edge _geomEdge;
1055 vector<double> _initU;
1056 vector<double> _normPar;
1057 vector<const SMDS_MeshNode*> _nodes;
1058 const _LayerEdge* _edges[2];
1061 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1062 void Compute(bool set3D, SMESH_MesherHelper& helper);
1063 void RestoreParams();
1064 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1065 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1066 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1067 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1068 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1069 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1071 //--------------------------------------------------------------------------------
1073 * \brief Smoother of _LayerEdge's on EDGE.
1077 struct OffPnt // point of the offsetted EDGE
1079 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1080 double _len; // length reached at previous inflation step
1081 double _param; // on EDGE
1082 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1083 gp_XYZ _edgeDir;// EDGE tangent at _param
1084 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1086 vector< OffPnt > _offPoints;
1087 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1088 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1089 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1090 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1091 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1092 _EdgesOnShape& _eos;
1093 double _curveLen; // length of the EDGE
1094 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1096 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1098 SMESH_MesherHelper& helper);
1100 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1101 _EdgesOnShape& eos )
1102 : _anaCurve( curveForSmooth ), _eos( eos )
1105 bool Perform(_SolidData& data,
1106 Handle(ShapeAnalysis_Surface)& surface,
1107 const TopoDS_Face& F,
1108 SMESH_MesherHelper& helper );
1110 void prepare(_SolidData& data );
1112 void findEdgesToSmooth();
1114 bool isToSmooth( int iE );
1116 bool smoothAnalyticEdge( _SolidData& data,
1117 Handle(ShapeAnalysis_Surface)& surface,
1118 const TopoDS_Face& F,
1119 SMESH_MesherHelper& helper);
1120 bool smoothComplexEdge( _SolidData& data,
1121 Handle(ShapeAnalysis_Surface)& surface,
1122 const TopoDS_Face& F,
1123 SMESH_MesherHelper& helper);
1124 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1125 const gp_XYZ& edgeDir);
1126 _LayerEdge* getLEdgeOnV( bool is2nd )
1128 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1130 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1132 void offPointsToPython() const; // debug
1135 //--------------------------------------------------------------------------------
1137 * \brief Compute positions of nodes of 2D structured mesh using TFI
1141 FaceQuadStruct _quadPoints;
1143 UVPtStruct& uvPnt( size_t i, size_t j ) { return _quadPoints.UVPt( i, j ); }
1146 _Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap );
1147 bool ComputeNodePositions();
1150 //--------------------------------------------------------------------------------
1152 * \brief Class of temporary mesh face.
1153 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1154 * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1156 struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1158 const SMDS_MeshElement* _srcFace;
1160 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1163 const SMDS_MeshElement* srcFace=0 ):
1164 SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1165 virtual SMDSAbs_EntityType GetEntityType() const
1166 { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1167 virtual SMDSAbs_GeometryType GetGeomType() const
1168 { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1170 //--------------------------------------------------------------------------------
1172 * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1174 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1176 _LayerEdge *_le1, *_le2;
1177 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1178 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1180 myNodes[0]=_le1->_nodes[0];
1181 myNodes[1]=_le1->_nodes.back();
1182 myNodes[2]=_le2->_nodes.back();
1183 myNodes[3]=_le2->_nodes[0];
1185 const SMDS_MeshNode* n( size_t i ) const
1187 return myNodes[ i ];
1189 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1191 SMESH_TNodeXYZ p0s( myNodes[0] );
1192 SMESH_TNodeXYZ p0t( myNodes[1] );
1193 SMESH_TNodeXYZ p1t( myNodes[2] );
1194 SMESH_TNodeXYZ p1s( myNodes[3] );
1195 gp_XYZ v0 = p0t - p0s;
1196 gp_XYZ v1 = p1t - p1s;
1197 gp_XYZ v01 = p1s - p0s;
1198 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1203 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1205 myNodes[0]=le1->_nodes[0];
1206 myNodes[1]=le1->_nodes.back();
1207 myNodes[2]=le2->_nodes.back();
1208 myNodes[3]=le2->_nodes[0];
1212 //--------------------------------------------------------------------------------
1214 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1215 * \warning Location of a surface is ignored
1217 struct _NodeCoordHelper
1219 SMESH_MesherHelper& _helper;
1220 const TopoDS_Face& _face;
1221 Handle(Geom_Surface) _surface;
1222 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1224 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1225 : _helper( helper ), _face( F )
1229 TopLoc_Location loc;
1230 _surface = BRep_Tool::Surface( _face, loc );
1232 if ( _surface.IsNull() )
1233 _fun = & _NodeCoordHelper::direct;
1235 _fun = & _NodeCoordHelper::byUV;
1237 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1240 gp_XYZ direct(const SMDS_MeshNode* n) const
1242 return SMESH_TNodeXYZ( n );
1244 gp_XYZ byUV (const SMDS_MeshNode* n) const
1246 gp_XY uv = _helper.GetNodeUV( _face, n );
1247 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1251 //================================================================================
1253 * \brief Check angle between vectors
1255 //================================================================================
1257 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1259 double dot = v1 * v2; // cos * |v1| * |v2|
1260 double l1 = v1.SquareMagnitude();
1261 double l2 = v2.SquareMagnitude();
1262 return (( dot * cos >= 0 ) &&
1263 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1268 ObjectPool< _LayerEdge > _edgePool;
1269 ObjectPool< _Curvature > _curvaturePool;
1270 ObjectPool< _2NearEdges > _nearEdgesPool;
1272 static _Factory* & me()
1274 static _Factory* theFactory = 0;
1279 _Factory() { me() = this; }
1280 ~_Factory() { me() = 0; }
1282 static _LayerEdge* NewLayerEdge() { return me()->_edgePool.getNew(); }
1283 static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1284 static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1287 } // namespace VISCOUS_3D
1291 //================================================================================
1292 // StdMeshers_ViscousLayers hypothesis
1294 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1295 :SMESH_Hypothesis(hypId, gen),
1296 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1297 _method( SURF_OFFSET_SMOOTH ),
1300 _name = StdMeshers_ViscousLayers::GetHypType();
1301 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1302 } // --------------------------------------------------------------------------------
1303 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1305 if ( faceIds != _shapeIds )
1306 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1307 if ( _isToIgnoreShapes != toIgnore )
1308 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1309 } // --------------------------------------------------------------------------------
1310 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1312 if ( thickness != _thickness )
1313 _thickness = thickness, NotifySubMeshesHypothesisModification();
1314 } // --------------------------------------------------------------------------------
1315 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1317 if ( _nbLayers != nb )
1318 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1319 } // --------------------------------------------------------------------------------
1320 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1322 if ( _stretchFactor != factor )
1323 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1324 } // --------------------------------------------------------------------------------
1325 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1327 if ( _method != method )
1328 _method = method, NotifySubMeshesHypothesisModification();
1329 } // --------------------------------------------------------------------------------
1330 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1332 if ( _groupName != name )
1335 if ( !_groupName.empty() )
1336 NotifySubMeshesHypothesisModification();
1338 } // --------------------------------------------------------------------------------
1339 SMESH_ProxyMesh::Ptr
1340 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1341 const TopoDS_Shape& theShape,
1342 const bool toMakeN2NMap) const
1344 using namespace VISCOUS_3D;
1345 _ViscousBuilder builder;
1346 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1347 if ( err && !err->IsOK() )
1348 return SMESH_ProxyMesh::Ptr();
1350 vector<SMESH_ProxyMesh::Ptr> components;
1351 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1352 for ( ; exp.More(); exp.Next() )
1354 if ( _MeshOfSolid* pm =
1355 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1357 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1358 if ( !builder.MakeN2NMap( pm ))
1359 return SMESH_ProxyMesh::Ptr();
1360 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1361 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1363 if ( pm->_warning && !pm->_warning->IsOK() )
1365 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1366 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1367 if ( !smError || smError->IsOK() )
1368 smError = pm->_warning;
1371 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1373 switch ( components.size() )
1377 case 1: return components[0];
1379 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1381 return SMESH_ProxyMesh::Ptr();
1382 } // --------------------------------------------------------------------------------
1383 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1385 save << " " << _nbLayers
1386 << " " << _thickness
1387 << " " << _stretchFactor
1388 << " " << _shapeIds.size();
1389 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1390 save << " " << _shapeIds[i];
1391 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1392 save << " " << _method;
1393 save << " " << _groupName.size();
1394 if ( !_groupName.empty() )
1395 save << " " << _groupName;
1397 } // --------------------------------------------------------------------------------
1398 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1400 int nbFaces, faceID, shapeToTreat, method;
1401 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1402 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1403 _shapeIds.push_back( faceID );
1404 if ( load >> shapeToTreat ) {
1405 _isToIgnoreShapes = !shapeToTreat;
1406 if ( load >> method )
1407 _method = (ExtrusionMethod) method;
1409 if ( load >> nameSize && nameSize > 0 )
1411 _groupName.resize( nameSize );
1412 load.get( _groupName[0] ); // remove a white-space
1413 load.getline( &_groupName[0], nameSize + 1 );
1417 _isToIgnoreShapes = true; // old behavior
1420 } // --------------------------------------------------------------------------------
1421 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
1422 const TopoDS_Shape& /*theShape*/)
1426 } // --------------------------------------------------------------------------------
1427 SMESH_ComputeErrorPtr
1428 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1429 const TopoDS_Shape& theShape,
1430 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1432 VISCOUS_3D::_ViscousBuilder builder;
1433 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1434 if ( err && !err->IsOK() )
1435 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1437 theStatus = SMESH_Hypothesis::HYP_OK;
1441 // --------------------------------------------------------------------------------
1442 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1445 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1446 return IsToIgnoreShapes() ? !isIn : isIn;
1449 // --------------------------------------------------------------------------------
1450 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string& theName,
1451 SMESH_Mesh& theMesh,
1452 SMDSAbs_ElementType theType)
1454 SMESH_Group* group = 0;
1455 SMDS_MeshGroup* groupDS = 0;
1457 if ( theName.empty() )
1460 if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1461 while( grIt->more() && !group )
1463 group = grIt->next();
1465 group->GetGroupDS()->GetType() != theType ||
1466 group->GetName() != theName ||
1467 !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1471 group = theMesh.AddGroup( theType, theName.c_str() );
1473 groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1478 // END StdMeshers_ViscousLayers hypothesis
1479 //================================================================================
1481 namespace VISCOUS_3D
1483 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV,
1484 const double h0, bool* isRegularEdge = nullptr )
1488 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1489 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1490 gp_Pnt p = BRep_Tool::Pnt( fromV );
1491 gp_Pnt pf = c->Value( f ), pl = c->Value( l );
1492 double distF = p.SquareDistance( pf );
1493 double distL = p.SquareDistance( pl );
1494 c->D1(( distF < distL ? f : l), p, dir );
1495 if ( distL < distF ) dir.Reverse();
1496 bool isDifficult = false;
1497 if ( dir.SquareMagnitude() < h0 * h0 ) // check dir orientation
1499 gp_Pnt& pClose = distF < distL ? pf : pl;
1500 gp_Pnt& pFar = distF < distL ? pl : pf;
1501 gp_Pnt pMid = 0.9 * pClose.XYZ() + 0.1 * pFar.XYZ();
1502 gp_Vec vMid( p, pMid );
1503 double dot = vMid * dir;
1504 double cos2 = dot * dot / dir.SquareMagnitude() / vMid.SquareMagnitude();
1505 if ( cos2 < 0.7 * 0.7 || dot < 0 ) // large angle between dir and vMid
1507 double uClose = distF < distL ? f : l;
1508 double uFar = distF < distL ? l : f;
1509 double r = h0 / SMESH_Algo::EdgeLength( E );
1510 double uMid = ( 1 - r ) * uClose + r * uFar;
1511 pMid = c->Value( uMid );
1512 dir = gp_Vec( p, pMid );
1516 if ( isRegularEdge )
1517 *isRegularEdge = !isDifficult;
1521 //--------------------------------------------------------------------------------
1522 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1523 SMESH_MesherHelper& helper)
1526 double f,l; gp_Pnt p;
1527 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1528 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1529 double u = helper.GetNodeU( E, atNode );
1533 //--------------------------------------------------------------------------------
1534 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1535 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok/*,
1537 //--------------------------------------------------------------------------------
1538 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1539 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1542 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1545 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1546 return getFaceDir( F, v, node, helper, ok );
1548 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1549 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1550 gp_Pnt p; gp_Vec du, dv, norm;
1551 surface->D1( uv.X(),uv.Y(), p, du,dv );
1554 double u = helper.GetNodeU( fromE, node, 0, &ok );
1556 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1557 if ( o == TopAbs_REVERSED )
1560 gp_Vec dir = norm ^ du;
1562 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1563 helper.IsClosedEdge( fromE ))
1565 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1566 else c->D1( f, p, dv );
1567 if ( o == TopAbs_REVERSED )
1569 gp_Vec dir2 = norm ^ dv;
1570 dir = dir.Normalized() + dir2.Normalized();
1574 //--------------------------------------------------------------------------------
1575 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1576 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1577 bool& ok/*, double* cosin*/)
1579 TopoDS_Face faceFrw = F;
1580 faceFrw.Orientation( TopAbs_FORWARD );
1581 //double f,l; TopLoc_Location loc;
1582 TopoDS_Edge edges[2]; // sharing a vertex
1585 TopoDS_Vertex VV[2];
1586 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1587 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1589 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1590 if ( SMESH_Algo::isDegenerated( e )) continue;
1591 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1592 if ( VV[1].IsSame( fromV )) {
1593 nbEdges += edges[ 0 ].IsNull();
1596 else if ( VV[0].IsSame( fromV )) {
1597 nbEdges += edges[ 1 ].IsNull();
1602 gp_XYZ dir(0,0,0), edgeDir[2];
1605 // get dirs of edges going fromV
1607 for ( size_t i = 0; i < nbEdges && ok; ++i )
1609 edgeDir[i] = getEdgeDir( edges[i], fromV, 0.1 * SMESH_Algo::EdgeLength( edges[i] ));
1610 double size2 = edgeDir[i].SquareModulus();
1611 if (( ok = size2 > numeric_limits<double>::min() ))
1612 edgeDir[i] /= sqrt( size2 );
1614 if ( !ok ) return dir;
1616 // get angle between the 2 edges
1618 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1619 if ( Abs( angle ) < 5 * M_PI/180 )
1621 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1625 dir = edgeDir[0] + edgeDir[1];
1630 // double angle = faceNormal.Angle( dir );
1631 // *cosin = Cos( angle );
1634 else if ( nbEdges == 1 )
1636 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1637 //if ( cosin ) *cosin = 1.;
1647 //================================================================================
1649 * \brief Finds concave VERTEXes of a FACE
1651 //================================================================================
1653 bool getConcaveVertices( const TopoDS_Face& F,
1654 SMESH_MesherHelper& helper,
1655 set< TGeomID >* vertices = 0)
1657 // check angles at VERTEXes
1659 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1660 for ( size_t iW = 0; iW < wires.size(); ++iW )
1662 const int nbEdges = wires[iW]->NbEdges();
1663 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1665 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1667 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1668 int iE2 = ( iE1 + 1 ) % nbEdges;
1669 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1670 iE2 = ( iE2 + 1 ) % nbEdges;
1671 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1672 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1673 wires[iW]->Edge( iE2 ), F, V );
1674 if ( angle < -5. * M_PI / 180. )
1678 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1682 return vertices ? !vertices->empty() : false;
1685 //================================================================================
1687 * \brief Returns true if a FACE is bound by a concave EDGE
1689 //================================================================================
1691 bool isConcave( const TopoDS_Face& F,
1692 SMESH_MesherHelper& helper,
1693 set< TGeomID >* vertices = 0 )
1695 bool isConcv = false;
1696 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1698 gp_Vec2d drv1, drv2;
1700 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1701 for ( ; eExp.More(); eExp.Next() )
1703 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1704 if ( SMESH_Algo::isDegenerated( E )) continue;
1705 // check if 2D curve is concave
1706 BRepAdaptor_Curve2d curve( E, F );
1707 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1708 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1709 curve.Intervals( intervals, GeomAbs_C2 );
1710 bool isConvex = true;
1711 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1713 double u1 = intervals( i );
1714 double u2 = intervals( i+1 );
1715 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1716 double cross = drv1 ^ drv2;
1717 if ( E.Orientation() == TopAbs_REVERSED )
1719 isConvex = ( cross > -1e-9 ); // 0.1 );
1723 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1732 // check angles at VERTEXes
1733 if ( getConcaveVertices( F, helper, vertices ))
1739 //================================================================================
1741 * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1742 * \param [in] face - the mesh face to treat
1743 * \param [in] nodeOnEdge - a node on the EDGE
1744 * \param [out] faceSize - the computed distance
1745 * \return bool - true if faceSize computed
1747 //================================================================================
1749 bool getDistFromEdge( const SMDS_MeshElement* face,
1750 const SMDS_MeshNode* nodeOnEdge,
1753 faceSize = Precision::Infinite();
1756 int nbN = face->NbCornerNodes();
1757 int iOnE = face->GetNodeIndex( nodeOnEdge );
1758 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1759 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1760 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1761 face->GetNode( iNext[1] ) };
1762 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1763 double segLen = -1.;
1764 // look for two neighbor not in-FACE nodes of face
1765 for ( int i = 0; i < 2; ++i )
1767 if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1768 ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1770 // look for an in-FACE node
1771 for ( int iN = 0; iN < nbN; ++iN )
1773 if ( iN == iOnE || iN == iNext[i] )
1775 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1776 gp_XYZ v = pInFace - segEnd;
1779 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1780 segLen = segVec.Modulus();
1782 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1783 faceSize = Min( faceSize, distToSeg );
1791 //================================================================================
1793 * \brief Return direction of axis or revolution of a surface
1795 //================================================================================
1797 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1800 switch ( surface.GetType() ) {
1803 gp_Cone cone = surface.Cone();
1804 axis = cone.Axis().Direction();
1807 case GeomAbs_Sphere:
1809 gp_Sphere sphere = surface.Sphere();
1810 axis = sphere.Position().Direction();
1813 case GeomAbs_SurfaceOfRevolution:
1815 axis = surface.AxeOfRevolution().Direction();
1818 //case GeomAbs_SurfaceOfExtrusion:
1819 case GeomAbs_OffsetSurface:
1821 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1822 return getRovolutionAxis( base->Surface(), axis );
1824 default: return false;
1829 //--------------------------------------------------------------------------------
1830 // DEBUG. Dump intermediate node positions into a python script
1831 // HOWTO use: run python commands written in a console and defined in /tmp/viscous.py
1832 // to see construction steps of viscous layers
1838 PyDump(SMESH_Mesh& m) {
1839 int tag = 3 + m.GetId();
1840 const char* fname = "/tmp/viscous.py";
1841 cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1842 py = _pyStream = new ofstream(fname);
1843 *py << "import SMESH" << endl
1844 << "from salome.smesh import smeshBuilder" << endl
1845 << "smesh = smeshBuilder.New()" << endl
1846 << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1847 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1852 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1853 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1854 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1855 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1859 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1860 struct MyStream : public ostream
1862 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1864 void Pause() { py = &_mystream; }
1865 void Resume() { py = _pyStream; }
1869 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1870 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1871 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1872 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1873 void _dumpFunction(const string& fun, int ln)
1874 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1875 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1876 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1877 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1878 void _dumpCmd(const string& txt, int ln)
1879 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1880 void dumpFunctionEnd()
1881 { if (py) *py<< " return"<< endl; }
1882 void dumpChangeNodes( const SMDS_MeshElement* f )
1883 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1884 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1885 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1886 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1890 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1891 #define dumpFunction(f) f
1893 #define dumpMoveComm(n,txt)
1894 #define dumpCmd(txt)
1895 #define dumpFunctionEnd()
1896 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1897 #define debugMsg( txt ) {}
1902 using namespace VISCOUS_3D;
1904 //================================================================================
1906 * \brief Constructor of _ViscousBuilder
1908 //================================================================================
1910 _ViscousBuilder::_ViscousBuilder()
1912 _error = SMESH_ComputeError::New(COMPERR_OK);
1916 //================================================================================
1918 * \brief Stores error description and returns false
1920 //================================================================================
1922 bool _ViscousBuilder::error(const string& text, int solidId )
1924 const string prefix = string("Viscous layers builder: ");
1925 _error->myName = COMPERR_ALGO_FAILED;
1926 _error->myComment = prefix + text;
1929 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1930 if ( !sm && !_sdVec.empty() )
1931 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1932 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1934 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1935 if ( smError && smError->myAlgo )
1936 _error->myAlgo = smError->myAlgo;
1938 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1940 // set KO to all solids
1941 for ( size_t i = 0; i < _sdVec.size(); ++i )
1943 if ( _sdVec[i]._index == solidId )
1945 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1946 if ( !sm->IsEmpty() )
1948 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1949 if ( !smError || smError->IsOK() )
1951 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1952 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1956 makeGroupOfLE(); // debug
1961 //================================================================================
1963 * \brief At study restoration, restore event listeners used to clear an inferior
1964 * dim sub-mesh modified by viscous layers
1966 //================================================================================
1968 void _ViscousBuilder::RestoreListeners()
1973 //================================================================================
1975 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1977 //================================================================================
1979 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1981 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1982 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1983 for ( ; fExp.More(); fExp.Next() )
1985 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1986 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1988 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1990 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1993 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1994 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1996 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1997 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1998 while( prxIt->more() )
2000 const SMDS_MeshElement* fSrc = srcIt->next();
2001 const SMDS_MeshElement* fPrx = prxIt->next();
2002 if ( fSrc->NbNodes() != fPrx->NbNodes())
2003 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
2004 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
2005 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
2008 pm->_n2nMapComputed = true;
2012 //================================================================================
2014 * \brief Does its job
2016 //================================================================================
2018 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
2019 const TopoDS_Shape& theShape)
2025 // check if proxy mesh already computed
2026 TopExp_Explorer exp( theShape, TopAbs_SOLID );
2028 return error("No SOLID's in theShape"), _error;
2030 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
2031 return SMESH_ComputeErrorPtr(); // everything already computed
2033 // TODO: ignore already computed SOLIDs
2034 if ( !findSolidsWithLayers())
2037 if ( !findFacesWithLayers() )
2040 if ( !makeEdgesOnShape() )
2043 findPeriodicFaces();
2045 PyDump debugDump( theMesh );
2046 _pyDump = &debugDump;
2049 for ( size_t i = 0; i < _sdVec.size(); ++i )
2052 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
2053 if ( _sdVec[iSD]._before.IsEmpty() &&
2054 !_sdVec[iSD]._solid.IsNull() &&
2055 !_sdVec[iSD]._done )
2057 if ( iSD == _sdVec.size() )
2060 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
2063 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
2065 _sdVec[iSD]._solid.Nullify();
2069 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
2072 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
2075 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
2078 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2080 _sdVec[iSD]._done = true;
2082 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2083 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2084 _sdVec[iSD]._before.Remove( solid );
2087 makeGroupOfLE(); // debug
2093 //================================================================================
2095 * \brief Check validity of hypotheses
2097 //================================================================================
2099 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
2100 const TopoDS_Shape& shape )
2104 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2105 return SMESH_ComputeErrorPtr(); // everything already computed
2108 findSolidsWithLayers( /*checkFaceMesh=*/false );
2109 bool ok = findFacesWithLayers( true );
2111 // remove _MeshOfSolid's of _SolidData's
2112 for ( size_t i = 0; i < _sdVec.size(); ++i )
2113 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2118 return SMESH_ComputeErrorPtr();
2121 //================================================================================
2123 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2125 //================================================================================
2127 bool _ViscousBuilder::findSolidsWithLayers(const bool checkFaceMesh)
2130 TopTools_IndexedMapOfShape allSolids;
2131 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2132 _sdVec.reserve( allSolids.Extent());
2134 SMESH_HypoFilter filter;
2135 for ( int i = 1; i <= allSolids.Extent(); ++i )
2137 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2138 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2139 continue; // solid is already meshed
2140 // TODO: check if algo is hidden
2141 SMESH_Algo* algo = sm->GetAlgo();
2142 if ( !algo ) continue;
2143 // check if all FACEs are meshed, which can be false if Compute() a sub-shape
2144 if ( checkFaceMesh )
2146 bool facesMeshed = true;
2147 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,true);
2148 while ( smIt->more() && facesMeshed )
2150 SMESH_subMesh * faceSM = smIt->next();
2151 if ( faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2153 facesMeshed = faceSM->IsMeshComputed();
2158 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2159 const list <const SMESHDS_Hypothesis *> & allHyps =
2160 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2161 _SolidData* soData = 0;
2162 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2163 const StdMeshers_ViscousLayers* viscHyp = 0;
2164 for ( ; hyp != allHyps.end(); ++hyp )
2165 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2167 TopoDS_Shape hypShape;
2168 filter.Init( filter.Is( viscHyp ));
2169 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2173 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2176 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2177 soData = & _sdVec.back();
2178 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2179 soData->_helper = new SMESH_MesherHelper( *_mesh );
2180 soData->_helper->SetSubShape( allSolids(i) );
2181 _solids.Add( allSolids(i) );
2183 soData->_hyps.push_back( viscHyp );
2184 soData->_hypShapes.push_back( hypShape );
2187 if ( _sdVec.empty() )
2189 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2194 //================================================================================
2196 * \brief Set a _SolidData to be computed before another
2198 //================================================================================
2200 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2202 // check possibility to set this order; get all solids before solidBefore
2203 TopTools_IndexedMapOfShape allSolidsBefore;
2204 allSolidsBefore.Add( solidBefore._solid );
2205 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2207 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2210 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2211 for ( ; soIt.More(); soIt.Next() )
2212 allSolidsBefore.Add( soIt.Value() );
2215 if ( allSolidsBefore.Contains( solidAfter._solid ))
2218 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2219 solidAfter._before.Add( allSolidsBefore(i) );
2224 //================================================================================
2228 //================================================================================
2230 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2232 SMESH_MesherHelper helper( *_mesh );
2233 TopExp_Explorer exp;
2235 // collect all faces-to-ignore defined by hyp
2236 for ( size_t i = 0; i < _sdVec.size(); ++i )
2238 // get faces-to-ignore defined by each hyp
2239 typedef const StdMeshers_ViscousLayers* THyp;
2240 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2241 list< TFacesOfHyp > ignoreFacesOfHyps;
2242 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2243 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2244 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2246 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2247 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2250 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2251 const int nbHyps = _sdVec[i]._hyps.size();
2254 // check if two hypotheses define different parameters for the same FACE
2255 list< TFacesOfHyp >::iterator igFacesOfHyp;
2256 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2258 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2260 igFacesOfHyp = ignoreFacesOfHyps.begin();
2261 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2262 if ( ! igFacesOfHyp->first.count( faceID ))
2265 return error(SMESH_Comment("Several hypotheses define "
2266 "Viscous Layers on the face #") << faceID );
2267 hyp = igFacesOfHyp->second;
2270 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2272 _sdVec[i]._ignoreFaceIds.insert( faceID );
2275 // check if two hypotheses define different number of viscous layers for
2276 // adjacent faces of a solid
2277 set< int > nbLayersSet;
2278 igFacesOfHyp = ignoreFacesOfHyps.begin();
2279 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2281 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2283 if ( nbLayersSet.size() > 1 )
2285 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2287 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2288 THyp hyp1 = 0, hyp2 = 0;
2289 while( const TopoDS_Shape* face = fIt->next() )
2291 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2292 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2293 if ( f2h != _sdVec[i]._face2hyp.end() )
2295 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2298 if ( hyp1 && hyp2 &&
2299 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2301 return error("Two hypotheses define different number of "
2302 "viscous layers on adjacent faces");
2306 } // if ( nbHyps > 1 )
2309 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2313 if ( onlyWith ) // is called to check hypotheses compatibility only
2316 // fill _SolidData::_reversedFaceIds
2317 for ( size_t i = 0; i < _sdVec.size(); ++i )
2319 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2320 for ( ; exp.More(); exp.Next() )
2322 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2323 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2324 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2325 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2326 helper.IsReversedSubMesh( face ))
2328 _sdVec[i]._reversedFaceIds.insert( faceID );
2333 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2334 TopTools_IndexedMapOfShape shapes;
2335 std::string structAlgoName = "Hexa_3D";
2336 for ( size_t i = 0; i < _sdVec.size(); ++i )
2339 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2340 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2342 const TopoDS_Shape& edge = shapes(iE);
2343 // find 2 FACEs sharing an EDGE
2345 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2346 while ( fIt->more())
2348 const TopoDS_Shape* f = fIt->next();
2349 FF[ int( !FF[0].IsNull()) ] = *f;
2351 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2353 // check presence of layers on them
2355 for ( int j = 0; j < 2; ++j )
2356 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2357 if ( ignore[0] == ignore[1] )
2358 continue; // nothing interesting
2359 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2362 if ( !fWOL.IsNull())
2364 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2365 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2370 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2372 for ( size_t i = 0; i < _sdVec.size(); ++i )
2375 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2376 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2378 const TopoDS_Shape& vertex = shapes(iV);
2379 // find faces WOL sharing the vertex
2380 vector< TopoDS_Shape > facesWOL;
2381 size_t totalNbFaces = 0;
2382 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2383 while ( fIt->more())
2385 const TopoDS_Shape* f = fIt->next();
2387 const int fID = getMeshDS()->ShapeToIndex( *f );
2388 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2389 facesWOL.push_back( *f );
2391 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2392 continue; // no layers at this vertex or no WOL
2393 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2394 switch ( facesWOL.size() )
2398 helper.SetSubShape( facesWOL[0] );
2399 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2401 TopoDS_Shape seamEdge;
2402 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2403 while ( eIt->more() && seamEdge.IsNull() )
2405 const TopoDS_Shape* e = eIt->next();
2406 if ( helper.IsRealSeam( *e ) )
2409 if ( !seamEdge.IsNull() )
2411 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2415 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2420 // find an edge shared by 2 faces
2421 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2422 while ( eIt->more())
2424 const TopoDS_Shape* e = eIt->next();
2425 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2426 helper.IsSubShape( *e, facesWOL[1]))
2428 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2434 return error("Not yet supported case", _sdVec[i]._index);
2439 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2440 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2441 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2442 for ( size_t i = 0; i < _sdVec.size(); ++i )
2444 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2445 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2447 const TopoDS_Shape& fWOL = e2f->second;
2448 const TGeomID edgeID = e2f->first;
2449 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2450 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2451 if ( edge.ShapeType() != TopAbs_EDGE )
2452 continue; // shrink shape is VERTEX
2455 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2456 while ( soIt->more() && solid.IsNull() )
2458 const TopoDS_Shape* so = soIt->next();
2459 if ( !so->IsSame( _sdVec[i]._solid ))
2462 if ( solid.IsNull() )
2465 bool noShrinkE = false;
2466 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2467 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2468 size_t iSolid = _solids.FindIndex( solid ) - 1;
2469 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2471 // the adjacent SOLID has NO layers on fWOL;
2472 // shrink allowed if
2473 // - there are layers on the EDGE in the adjacent SOLID
2474 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2475 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2476 bool shrinkAllowed = (( hasWLAdj ) ||
2477 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2478 noShrinkE = !shrinkAllowed;
2480 else if ( iSolid < _sdVec.size() )
2482 // the adjacent SOLID has layers on fWOL;
2483 // check if SOLID's mesh is unstructured and then try to set it
2484 // to be computed after the i-th solid
2485 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2486 noShrinkE = true; // don't shrink fWOL
2490 // the adjacent SOLID has NO layers at all
2491 noShrinkE = isStructured;
2496 _sdVec[i]._noShrinkShapes.insert( edgeID );
2498 // check if there is a collision with to-shrink-from EDGEs in iSolid
2499 // if ( iSolid < _sdVec.size() )
2502 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2503 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2505 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2506 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2507 // if ( eID == edgeID ||
2508 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2509 // _sdVec[i]._noShrinkShapes.count( eID ))
2511 // for ( int is1st = 0; is1st < 2; ++is1st )
2513 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2514 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2516 // return error("No way to make a conformal mesh with "
2517 // "the given set of faces with layers", _sdVec[i]._index);
2524 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2525 // _shrinkShape2Shape is different in the adjacent SOLID
2526 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2528 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2529 bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2531 if ( iSolid < _sdVec.size() )
2533 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2535 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2536 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2537 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2538 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2539 noShrinkV = (( isStructured ) ||
2540 ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2542 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2546 noShrinkV = noShrinkE;
2551 // the adjacent SOLID has NO layers at all
2558 noShrinkV = noShrinkIfAdjMeshed =
2559 ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2563 if ( noShrinkV && noShrinkIfAdjMeshed )
2565 // noShrinkV if FACEs in the adjacent SOLID are meshed
2566 PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2567 *_mesh, TopAbs_FACE, &solid );
2568 while ( fIt->more() )
2570 const TopoDS_Shape* f = fIt->next();
2571 if ( !f->IsSame( fWOL ))
2573 noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2579 _sdVec[i]._noShrinkShapes.insert( vID );
2582 } // loop on _sdVec[i]._shrinkShape2Shape
2583 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2586 // add FACEs of other SOLIDs to _ignoreFaceIds
2587 for ( size_t i = 0; i < _sdVec.size(); ++i )
2590 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2592 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2594 if ( !shapes.Contains( exp.Current() ))
2595 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2602 //================================================================================
2604 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2606 //================================================================================
2608 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2609 const StdMeshers_ViscousLayers* hyp,
2610 const TopoDS_Shape& hypShape,
2611 set<TGeomID>& ignoreFaceIds)
2613 TopExp_Explorer exp;
2615 vector<TGeomID> ids = hyp->GetBndShapes();
2616 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2618 for ( size_t ii = 0; ii < ids.size(); ++ii )
2620 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2621 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2622 ignoreFaceIds.insert( ids[ii] );
2625 else // FACEs with layers are given
2627 exp.Init( solid, TopAbs_FACE );
2628 for ( ; exp.More(); exp.Next() )
2630 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2631 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2632 ignoreFaceIds.insert( faceInd );
2636 // ignore internal FACEs if inlets and outlets are specified
2637 if ( hyp->IsToIgnoreShapes() )
2639 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2640 TopExp::MapShapesAndAncestors( hypShape,
2641 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2643 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2645 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2646 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2649 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2651 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2656 //================================================================================
2658 * \brief Create the inner surface of the viscous layer and prepare data for infation
2660 //================================================================================
2662 bool _ViscousBuilder::makeLayer(_SolidData& data)
2664 // make a map to find new nodes on sub-shapes shared with other SOLID
2665 map< TGeomID, TNode2Edge* >::iterator s2ne;
2666 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2667 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2669 TGeomID shapeInd = s2s->first;
2670 for ( size_t i = 0; i < _sdVec.size(); ++i )
2672 if ( _sdVec[i]._index == data._index ) continue;
2673 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2674 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2675 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2677 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2683 // Create temporary faces and _LayerEdge's
2685 debugMsg( "######################" );
2686 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2688 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2690 data._stepSize = Precision::Infinite();
2691 data._stepSizeNodes[0] = 0;
2693 SMESH_MesherHelper helper( *_mesh );
2694 helper.SetSubShape( data._solid );
2695 helper.SetElementsOnShape( true );
2697 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2698 TNode2Edge::iterator n2e2;
2700 // make _LayerEdge's
2701 for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2703 const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2704 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2705 const TGeomID id = sm->GetId();
2706 if ( edgesByGeom[ id ]._shape.IsNull() )
2707 continue; // no layers
2708 SMESH_ProxyMesh::SubMesh* proxySub =
2709 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2711 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2712 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2714 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2715 while ( eIt->more() )
2717 const SMDS_MeshElement* face = eIt->next();
2718 double faceMaxCosin = -1;
2719 _LayerEdge* maxCosinEdge = 0;
2720 int nbDegenNodes = 0;
2722 newNodes.resize( face->NbCornerNodes() );
2723 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2725 const SMDS_MeshNode* n = face->GetNode( i );
2726 const int shapeID = n->getshapeId();
2727 const bool onDegenShap = helper.IsDegenShape( shapeID );
2728 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2733 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2734 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2735 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2736 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2746 TNode2Edge::iterator n2e = data._n2eMap.insert({ n, nullptr }).first;
2747 if ( !(*n2e).second )
2750 _LayerEdge* edge = _Factory::NewLayerEdge();
2751 edge->_nodes.push_back( n );
2753 edgesByGeom[ shapeID ]._edges.push_back( edge );
2754 const bool noShrink = data._noShrinkShapes.count( shapeID );
2756 SMESH_TNodeXYZ xyz( n );
2758 // set edge data or find already refined _LayerEdge and get data from it
2759 if (( !noShrink ) &&
2760 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2761 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2762 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2764 _LayerEdge* foundEdge = (*n2e2).second;
2765 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2766 foundEdge->_pos.push_back( lastPos );
2767 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2768 const_cast< SMDS_MeshNode* >
2769 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2775 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2777 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2780 if ( edge->_nodes.size() < 2 && !noShrink )
2781 edge->Block( data ); // a sole node is moved only if noShrink
2783 dumpMove(edge->_nodes.back());
2785 if ( edge->_cosin > faceMaxCosin && edge->_nodes.size() > 1 )
2787 faceMaxCosin = edge->_cosin;
2788 maxCosinEdge = edge;
2791 newNodes[ i ] = n2e->second->_nodes.back();
2794 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2796 if ( newNodes.size() - nbDegenNodes < 2 )
2799 // create a temporary face
2800 const SMDS_MeshElement* newFace =
2801 new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2802 proxySub->AddElement( newFace );
2804 // compute inflation step size by min size of element on a convex surface
2805 if ( faceMaxCosin > theMinSmoothCosin )
2806 limitStepSize( data, face, maxCosinEdge );
2808 } // loop on 2D elements on a FACE
2809 } // loop on FACEs of a SOLID to create _LayerEdge's
2812 // Set _LayerEdge::_neibors
2813 TNode2Edge::iterator n2e;
2814 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2816 _EdgesOnShape& eos = data._edgesOnShape[iS];
2817 for ( size_t i = 0; i < eos._edges.size(); ++i )
2819 _LayerEdge* edge = eos._edges[i];
2820 TIDSortedNodeSet nearNodes;
2821 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2822 while ( fIt->more() )
2824 const SMDS_MeshElement* f = fIt->next();
2825 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2826 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2828 nearNodes.erase( edge->_nodes[0] );
2829 edge->_neibors.reserve( nearNodes.size() );
2830 TIDSortedNodeSet::iterator node = nearNodes.begin();
2831 for ( ; node != nearNodes.end(); ++node )
2832 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2833 edge->_neibors.push_back( n2e->second );
2836 // Fix uv of nodes on periodic FACEs (bos #20643)
2838 if ( eos.ShapeType() != TopAbs_EDGE ||
2839 eos.SWOLType() != TopAbs_FACE ||
2843 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
2844 SMESH_MesherHelper faceHelper( *_mesh );
2845 faceHelper.SetSubShape( F );
2846 faceHelper.ToFixNodeParameters( true );
2847 if ( faceHelper.GetPeriodicIndex() == 0 )
2850 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( F );
2851 if ( !smDS || smDS->GetNodes() == 0 )
2854 bool toCheck = true;
2855 const double tol = 2 * helper.MaxTolerance( F );
2856 for ( SMDS_NodeIteratorPtr nIt = smDS->GetNodes(); nIt->more(); )
2858 const SMDS_MeshNode* node = nIt->next();
2859 gp_XY uvNew( Precision::Infinite(), 0 );
2863 gp_XY uv = faceHelper.GetNodeUV( F, node );
2864 if ( ! faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true ))
2865 break; // projection on F failed
2866 if (( uv - uvNew ).Modulus() < Precision::Confusion() )
2867 break; // current uv is OK
2869 faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true );
2873 data._epsilon = 1e-7;
2874 if ( data._stepSize < 1. )
2875 data._epsilon *= data._stepSize;
2877 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2880 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2881 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2883 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2884 const SMDS_MeshNode* nn[2];
2885 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2887 _EdgesOnShape& eos = data._edgesOnShape[iS];
2888 for ( size_t i = 0; i < eos._edges.size(); ++i )
2890 _LayerEdge* edge = eos._edges[i];
2891 if ( edge->IsOnEdge() )
2893 // get neighbor nodes
2894 bool hasData = ( edge->_2neibors->_edges[0] );
2895 if ( hasData ) // _LayerEdge is a copy of another one
2897 nn[0] = edge->_2neibors->srcNode(0);
2898 nn[1] = edge->_2neibors->srcNode(1);
2900 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2904 // set neighbor _LayerEdge's
2905 for ( int j = 0; j < 2; ++j )
2907 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2908 return error("_LayerEdge not found by src node", data._index);
2909 edge->_2neibors->_edges[j] = n2e->second;
2912 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2915 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2917 _Simplex& s = edge->_simplices[j];
2918 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2919 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2922 // For an _LayerEdge on a degenerated EDGE, copy some data from
2923 // a corresponding _LayerEdge on a VERTEX
2924 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2925 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2927 // Generally we should not get here
2928 if ( eos.ShapeType() != TopAbs_EDGE )
2930 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2931 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2932 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2934 const _LayerEdge* vEdge = n2e->second;
2935 edge->_normal = vEdge->_normal;
2936 edge->_lenFactor = vEdge->_lenFactor;
2937 edge->_cosin = vEdge->_cosin;
2940 } // loop on data._edgesOnShape._edges
2941 } // loop on data._edgesOnShape
2943 // fix _LayerEdge::_2neibors on EDGEs to smooth
2944 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2945 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2946 // if ( !e2c->second.IsNull() )
2948 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2949 // data.Sort2NeiborsOnEdge( eos->_edges );
2956 //================================================================================
2958 * \brief Compute inflation step size by min size of element on a convex surface
2960 //================================================================================
2962 void _ViscousBuilder::limitStepSize( _SolidData& data,
2963 const SMDS_MeshElement* face,
2964 const _LayerEdge* maxCosinEdge )
2967 double minSize = 10 * data._stepSize;
2968 const int nbNodes = face->NbCornerNodes();
2969 for ( int i = 0; i < nbNodes; ++i )
2971 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2972 const SMDS_MeshNode* curN = face->GetNode( i );
2973 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2974 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2976 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2977 if ( dist < minSize )
2978 minSize = dist, iN = i;
2981 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2982 if ( newStep < data._stepSize )
2984 data._stepSize = newStep;
2985 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2986 data._stepSizeNodes[0] = face->GetNode( iN );
2987 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2991 //================================================================================
2993 * \brief Compute inflation step size by min size of element on a convex surface
2995 //================================================================================
2997 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2999 if ( minSize < data._stepSize )
3001 data._stepSize = minSize;
3002 if ( data._stepSizeNodes[0] )
3005 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3006 data._stepSizeCoeff = data._stepSize / dist;
3011 //================================================================================
3013 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
3015 //================================================================================
3017 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
3019 SMESH_MesherHelper helper( *_mesh );
3021 BRepLProp_SLProps surfProp( 2, 1e-6 );
3022 data._convexFaces.clear();
3024 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3026 _EdgesOnShape& eof = data._edgesOnShape[iS];
3027 if ( eof.ShapeType() != TopAbs_FACE ||
3028 data._ignoreFaceIds.count( eof._shapeID ))
3031 TopoDS_Face F = TopoDS::Face( eof._shape );
3032 const TGeomID faceID = eof._shapeID;
3034 BRepAdaptor_Surface surface( F, false );
3035 surfProp.SetSurface( surface );
3037 _ConvexFace cnvFace;
3039 cnvFace._normalsFixed = false;
3040 cnvFace._isTooCurved = false;
3041 cnvFace._normalsFixedOnBorders = false;
3043 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
3044 if ( maxCurvature > 0 )
3046 limitStepSize( data, 0.9 / maxCurvature );
3047 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
3049 if ( !cnvFace._isTooCurved ) continue;
3051 _ConvexFace & convFace =
3052 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
3054 // skip a closed surface (data._convexFaces is useful anyway)
3055 bool isClosedF = false;
3056 helper.SetSubShape( F );
3057 if ( helper.HasRealSeam() )
3059 // in the closed surface there must be a closed EDGE
3060 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
3061 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
3065 // limit _LayerEdge::_maxLen on the FACE
3066 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
3067 const double minCurvature =
3068 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
3069 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
3070 if ( id2eos != cnvFace._subIdToEOS.end() )
3072 _EdgesOnShape& eos = * id2eos->second;
3073 for ( size_t i = 0; i < eos._edges.size(); ++i )
3075 _LayerEdge* ledge = eos._edges[ i ];
3076 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
3077 surfProp.SetParameters( uv.X(), uv.Y() );
3078 if ( surfProp.IsCurvatureDefined() )
3080 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
3081 surfProp.MinCurvature() * oriFactor );
3082 if ( curvature > minCurvature )
3083 ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
3090 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
3091 // prism distortion.
3092 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
3093 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
3095 // there are _LayerEdge's on the FACE it-self;
3096 // select _LayerEdge's near EDGEs
3097 _EdgesOnShape& eos = * id2eos->second;
3098 for ( size_t i = 0; i < eos._edges.size(); ++i )
3100 _LayerEdge* ledge = eos._edges[ i ];
3101 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
3102 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
3104 // do not select _LayerEdge's neighboring sharp EDGEs
3105 bool sharpNbr = false;
3106 for ( size_t iN = 0; iN < ledge->_neibors.size() && !sharpNbr; ++iN )
3107 sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
3109 convFace._simplexTestEdges.push_back( ledge );
3116 // where there are no _LayerEdge's on a _ConvexFace,
3117 // as e.g. on a fillet surface with no internal nodes - issue 22580,
3118 // so that collision of viscous internal faces is not detected by check of
3119 // intersection of _LayerEdge's with the viscous internal faces.
3121 set< const SMDS_MeshNode* > usedNodes;
3123 // look for _LayerEdge's with null _sWOL
3124 id2eos = convFace._subIdToEOS.begin();
3125 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3127 _EdgesOnShape& eos = * id2eos->second;
3128 if ( !eos._sWOL.IsNull() )
3130 for ( size_t i = 0; i < eos._edges.size(); ++i )
3132 _LayerEdge* ledge = eos._edges[ i ];
3133 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3134 if ( !usedNodes.insert( srcNode ).second ) continue;
3136 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3138 usedNodes.insert( ledge->_simplices[i]._nPrev );
3139 usedNodes.insert( ledge->_simplices[i]._nNext );
3141 convFace._simplexTestEdges.push_back( ledge );
3145 } // loop on FACEs of data._solid
3148 //================================================================================
3150 * \brief Detect shapes (and _LayerEdge's on them) to smooth
3152 //================================================================================
3154 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3156 // define allowed thickness
3157 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3160 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3161 // boundary inclined to the shape at a sharp angle
3163 TopTools_MapOfShape edgesOfSmooFaces;
3164 SMESH_MesherHelper helper( *_mesh );
3167 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3168 data._nbShapesToSmooth = 0;
3170 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3172 _EdgesOnShape& eos = edgesByGeom[iS];
3173 eos._toSmooth = false;
3174 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3177 double tgtThick = eos._hyp.GetTotalThickness();
3178 SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3179 while ( subIt->more() && !eos._toSmooth )
3181 TGeomID iSub = subIt->next()->GetId();
3182 const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3183 if ( eSub.empty() ) continue;
3186 for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3187 if ( eSub[i]->_cosin > theMinSmoothCosin )
3189 SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3190 while ( fIt->more() && !eos._toSmooth )
3192 const SMDS_MeshElement* face = fIt->next();
3193 if ( face->getshapeId() == eos._shapeID &&
3194 getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3196 eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3197 tgtThick * eSub[i]->_lenFactor,
3203 if ( eos._toSmooth )
3205 for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3206 edgesOfSmooFaces.Add( eExp.Current() );
3208 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3210 data._nbShapesToSmooth += eos._toSmooth;
3214 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3216 _EdgesOnShape& eos = edgesByGeom[iS];
3217 eos._edgeSmoother = NULL;
3218 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3219 if ( !eos._hyp.ToSmooth() ) continue;
3221 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3222 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3225 double tgtThick = eos._hyp.GetTotalThickness(), h0 = eos._hyp.Get1stLayerThickness();
3226 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3228 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3229 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3230 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3231 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ), h0 );
3232 double angle = eDir.Angle( eV[0]->_normal );
3233 double cosin = Cos( angle );
3234 double cosinAbs = Abs( cosin );
3235 if ( cosinAbs > theMinSmoothCosin )
3237 // always smooth analytic EDGEs
3238 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3239 eos._toSmooth = ! curve.IsNull();
3241 // compare tgtThick with the length of an end segment
3242 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3243 while ( eIt->more() && !eos._toSmooth )
3245 const SMDS_MeshElement* endSeg = eIt->next();
3246 if ( endSeg->getshapeId() == (int) iS )
3249 SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3250 eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3253 if ( eos._toSmooth )
3255 eos._edgeSmoother = new _Smoother1D( curve, eos );
3257 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3258 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3262 data._nbShapesToSmooth += eos._toSmooth;
3266 // Reset _cosin if no smooth is allowed by the user
3267 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3269 _EdgesOnShape& eos = edgesByGeom[iS];
3270 if ( eos._edges.empty() ) continue;
3272 if ( !eos._hyp.ToSmooth() )
3273 for ( size_t i = 0; i < eos._edges.size(); ++i )
3274 //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3275 eos._edges[i]->_lenFactor = 1;
3279 // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3281 TopTools_MapOfShape c1VV;
3283 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3285 _EdgesOnShape& eos = edgesByGeom[iS];
3286 if ( eos._edges.empty() ||
3287 eos.ShapeType() != TopAbs_FACE ||
3291 // check EDGEs of a FACE
3292 TopTools_MapOfShape checkedEE, allVV;
3293 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3294 while ( !smQueue.empty() )
3296 SMESH_subMesh* sm = smQueue.front();
3297 smQueue.pop_front();
3298 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3299 while ( smIt->more() )
3302 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3303 allVV.Add( sm->GetSubShape() );
3304 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3305 !checkedEE.Add( sm->GetSubShape() ))
3308 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3309 vector<_LayerEdge*>& eE = eoe->_edges;
3310 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3313 bool isC1 = true; // check continuity along an EDGE
3314 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3315 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3319 // check that mesh faces are C1 as well
3321 gp_XYZ norm1, norm2;
3322 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3323 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3324 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3326 while ( fIt->more() && isC1 )
3327 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3328 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3333 // add the EDGE and an adjacent FACE to _eosC1
3334 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3335 while ( const TopoDS_Shape* face = fIt->next() )
3337 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3338 if ( !eof ) continue; // other solid
3339 if ( eos._shapeID == eof->_shapeID ) continue;
3340 if ( !eos.HasC1( eof ))
3343 eos._eosC1.push_back( eof );
3344 eof->_toSmooth = false;
3345 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3346 smQueue.push_back( eof->_subMesh );
3348 if ( !eos.HasC1( eoe ))
3350 eos._eosC1.push_back( eoe );
3351 eoe->_toSmooth = false;
3352 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3357 if ( eos._eosC1.empty() )
3360 // check VERTEXes of C1 FACEs
3361 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3362 for ( ; vIt.More(); vIt.Next() )
3364 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3365 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3368 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3369 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3370 while ( const TopoDS_Shape* face = fIt->next() )
3372 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3373 if ( !eof ) continue; // other solid
3374 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3380 eos._eosC1.push_back( eov );
3381 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3382 c1VV.Add( eov->_shape );
3386 } // fill _eosC1 of FACEs
3391 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3393 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3395 _EdgesOnShape& eov = edgesByGeom[iS];
3396 if ( eov._edges.empty() ||
3397 eov.ShapeType() != TopAbs_VERTEX ||
3398 c1VV.Contains( eov._shape ))
3400 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3402 // get directions of surrounding EDGEs
3404 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3405 while ( const TopoDS_Shape* e = fIt->next() )
3407 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3408 if ( !eoe ) continue; // other solid
3409 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V, eoe->_hyp.Get1stLayerThickness() );
3410 if ( !Precision::IsInfinite( eDir.X() ))
3411 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3414 // find EDGEs with C1 directions
3415 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3416 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3417 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3419 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3420 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3423 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3424 for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3426 size_t k = isJ ? j : i;
3427 const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3428 double eLen = SMESH_Algo::EdgeLength( e );
3429 if ( eLen < maxEdgeLen )
3431 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3432 if ( oppV.IsSame( V ))
3433 oppV = SMESH_MesherHelper::IthVertex( 1, e );
3434 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3435 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3436 eov._eosC1.push_back( dirOfEdges[k].first );
3438 dirOfEdges[k].first = 0;
3442 } // fill _eosC1 of VERTEXes
3449 //================================================================================
3451 * \brief Set up _SolidData::_edgesOnShape
3453 //================================================================================
3455 int _ViscousBuilder::makeEdgesOnShape()
3457 const int nbShapes = getMeshDS()->MaxShapeIndex();
3460 for ( size_t i = 0; i < _sdVec.size(); ++i )
3462 _SolidData& data = _sdVec[ i ];
3463 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3464 edgesByGeom.resize( nbShapes+1 );
3466 // set data of _EdgesOnShape's
3468 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3470 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3471 while ( smIt->more() )
3474 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3475 data._ignoreFaceIds.count( sm->GetId() ))
3478 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3480 nbShapesWL += ( sm->GetSubShape().ShapeType() == TopAbs_FACE );
3483 if ( nbShapesWL == 0 ) // no shapes with layers in a SOLID
3486 SMESHUtils::FreeVector( edgesByGeom );
3496 //================================================================================
3498 * \brief initialize data of _EdgesOnShape
3500 //================================================================================
3502 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3506 if ( !eos._shape.IsNull() ||
3507 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3510 SMESH_MesherHelper helper( *_mesh );
3513 eos._shapeID = sm->GetId();
3514 eos._shape = sm->GetSubShape();
3515 if ( eos.ShapeType() == TopAbs_FACE )
3516 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3517 eos._toSmooth = false;
3519 eos._mapper2D = nullptr;
3522 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3523 data._shrinkShape2Shape.find( eos._shapeID );
3524 if ( s2s != data._shrinkShape2Shape.end() )
3525 eos._sWOL = s2s->second;
3527 eos._isRegularSWOL = true;
3528 if ( eos.SWOLType() == TopAbs_FACE )
3530 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3531 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3532 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3536 if ( data._hyps.size() == 1 )
3538 eos._hyp = data._hyps.back();
3542 // compute average StdMeshers_ViscousLayers parameters
3543 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3544 if ( eos.ShapeType() == TopAbs_FACE )
3546 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3547 eos._hyp = f2hyp->second;
3551 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3552 while ( const TopoDS_Shape* face = fIt->next() )
3554 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3555 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3556 eos._hyp.Add( f2hyp->second );
3562 if ( ! eos._hyp.UseSurfaceNormal() )
3564 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3566 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3567 if ( !smDS ) return;
3568 eos._faceNormals.reserve( smDS->NbElements() );
3570 double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3571 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3572 for ( ; eIt->more(); )
3574 const SMDS_MeshElement* face = eIt->next();
3575 gp_XYZ& norm = eos._faceNormals[face];
3576 if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3577 norm.SetCoord( 0,0,0 );
3581 else // find EOS of adjacent FACEs
3583 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3584 while ( const TopoDS_Shape* face = fIt->next() )
3586 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3587 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3588 if ( eos._faceEOS.back()->_shape.IsNull() )
3589 // avoid using uninitialised _shapeID in GetNormal()
3590 eos._faceEOS.back()->_shapeID = faceID;
3596 //================================================================================
3598 * \brief Returns normal of a face
3600 //================================================================================
3602 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3605 _EdgesOnShape* eos = 0;
3607 if ( face->getshapeId() == _shapeID )
3613 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3614 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3615 eos = _faceEOS[ iF ];
3619 ( ok = ( eos->_faceNormals.count( face ) )))
3621 norm = eos->_faceNormals[ face ];
3625 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3626 << " on _shape #" << _shapeID );
3631 //================================================================================
3633 * \brief EdgesOnShape destructor
3635 //================================================================================
3637 _EdgesOnShape::~_EdgesOnShape()
3639 delete _edgeSmoother;
3643 //================================================================================
3645 * \brief Set data of _LayerEdge needed for smoothing
3647 //================================================================================
3649 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3651 SMESH_MesherHelper& helper,
3654 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3657 edge._maxLen = Precision::Infinite();
3660 edge._curvature = 0;
3662 edge._smooFunction = 0;
3664 // --------------------------
3665 // Compute _normal and _cosin
3666 // --------------------------
3669 edge._lenFactor = 1.;
3670 edge._normal.SetCoord(0,0,0);
3671 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3673 int totalNbFaces = 0;
3675 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3679 const bool onShrinkShape = !eos._sWOL.IsNull();
3680 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3681 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3683 // get geom FACEs the node lies on
3684 //if ( useGeometry )
3686 set<TGeomID> faceIds;
3687 if ( eos.ShapeType() == TopAbs_FACE )
3689 faceIds.insert( eos._shapeID );
3693 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3694 while ( fIt->more() )
3695 faceIds.insert( fIt->next()->getshapeId() );
3697 set<TGeomID>::iterator id = faceIds.begin();
3698 for ( ; id != faceIds.end(); ++id )
3700 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3701 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3703 F = TopoDS::Face( s );
3704 face2Norm[ totalNbFaces ].first = F;
3710 bool fromVonF = false;
3713 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3714 eos.SWOLType() == TopAbs_FACE &&
3717 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3719 if ( eos.SWOLType() == TopAbs_EDGE )
3721 // inflate from VERTEX along EDGE
3722 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3723 eos._hyp.Get1stLayerThickness(), &eos._isRegularSWOL );
3725 else if ( eos.ShapeType() == TopAbs_VERTEX )
3727 // inflate from VERTEX along FACE
3728 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3729 node, helper, normOK/*, &edge._cosin*/);
3733 // inflate from EDGE along FACE
3734 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3735 node, helper, normOK);
3738 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3741 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3744 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3746 F = face2Norm[ iF ].first;
3747 geomNorm = getFaceNormal( node, F, helper, normOK );
3748 if ( !normOK ) continue;
3751 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3753 face2Norm[ iF ].second = geomNorm.XYZ();
3754 edge._normal += geomNorm.XYZ();
3756 if ( nbOkNorms == 0 )
3757 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3759 if ( totalNbFaces >= 3 )
3761 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3764 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3766 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3767 edge._normal.SetCoord( 0,0,0 );
3768 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3770 const TopoDS_Face& F = face2Norm[iF].first;
3771 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3772 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3775 face2Norm[ iF ].second = geomNorm.XYZ();
3776 edge._normal += face2Norm[ iF ].second;
3781 else // !useGeometry - get _normal using surrounding mesh faces
3783 edge._normal = getWeigthedNormal( &edge );
3785 // set<TGeomID> faceIds;
3787 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3788 // while ( fIt->more() )
3790 // const SMDS_MeshElement* face = fIt->next();
3791 // if ( eos.GetNormal( face, geomNorm ))
3793 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3794 // continue; // use only one mesh face on FACE
3795 // edge._normal += geomNorm.XYZ();
3802 //if ( eos._hyp.UseSurfaceNormal() )
3804 switch ( eos.ShapeType() )
3811 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3812 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3813 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3814 edge._cosin = Cos( angle );
3817 case TopAbs_VERTEX: {
3818 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3819 gp_Vec inFaceDir = getFaceDir( face2Norm[0].first , V, node, helper, normOK );
3820 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3821 edge._cosin = Cos( angle );
3824 if ( totalNbFaces > 1 || helper.IsSeamShape( node->getshapeId() ))
3825 for ( int iF = 1; iF < totalNbFaces; ++iF )
3827 F = face2Norm[ iF ].first;
3828 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3830 if ( onShrinkShape )
3832 gp_Vec faceNorm = getFaceNormal( node, F, helper, normOK );
3833 if ( !normOK ) continue;
3834 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3836 angle = 0.5 * M_PI - faceNorm.Angle( edge._normal );
3837 if ( inFaceDir * edge._normal < 0 )
3838 angle = M_PI - angle;
3842 angle = inFaceDir.Angle( edge._normal );
3844 double cosin = Cos( angle );
3845 if ( Abs( cosin ) > Abs( edge._cosin ))
3846 edge._cosin = cosin;
3852 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3856 double normSize = edge._normal.SquareModulus();
3857 if ( normSize < numeric_limits<double>::min() )
3858 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3860 edge._normal /= sqrt( normSize );
3862 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3864 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3865 edge._nodes.resize( 1 );
3866 edge._normal.SetCoord( 0,0,0 );
3867 edge.SetMaxLen( 0 );
3870 // Set the rest data
3871 // --------------------
3873 double realLenFactor = edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3874 // if ( realLenFactor > 3 )
3877 // if ( onShrinkShape )
3879 // edge.Set( _LayerEdge::RISKY_SWOL );
3880 // edge._lenFactor = 2;
3884 // edge._lenFactor = 1;
3888 if ( onShrinkShape )
3890 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3891 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3892 sm->RemoveNode( tgtNode );
3894 // set initial position which is parameters on _sWOL in this case
3895 if ( eos.SWOLType() == TopAbs_EDGE )
3897 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3898 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3899 if ( edge._nodes.size() > 1 )
3900 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3902 else // eos.SWOLType() == TopAbs_FACE
3904 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3905 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3906 if ( edge._nodes.size() > 1 )
3907 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3910 //if ( edge._nodes.size() > 1 ) -- allow RISKY_SWOL on noShrink shape
3912 // check if an angle between a FACE with layers and SWOL is sharp,
3913 // else the edge should not inflate
3915 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3916 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3917 F = face2Norm[iF].first;
3920 geomNorm = getFaceNormal( node, F, helper, normOK );
3921 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3922 geomNorm.Reverse(); // inside the SOLID
3923 if ( geomNorm * edge._normal < -0.001 )
3925 if ( edge._nodes.size() > 1 )
3927 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3928 edge._nodes.resize( 1 );
3931 else if ( realLenFactor > 3 ) /// -- moved to SetCosin()
3932 //else if ( edge._lenFactor > 3 )
3934 edge._lenFactor = 2;
3935 edge.Set( _LayerEdge::RISKY_SWOL );
3942 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3944 if ( eos.ShapeType() == TopAbs_FACE )
3947 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3949 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3950 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3955 // Set neighbor nodes for a _LayerEdge based on EDGE
3957 if ( eos.ShapeType() == TopAbs_EDGE /*||
3958 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3960 edge._2neibors = _Factory::NewNearEdges();
3961 // target nodes instead of source ones will be set later
3967 //================================================================================
3969 * \brief Return normal to a FACE at a node
3970 * \param [in] n - node
3971 * \param [in] face - FACE
3972 * \param [in] helper - helper
3973 * \param [out] isOK - true or false
3974 * \param [in] shiftInside - to find normal at a position shifted inside the face
3975 * \return gp_XYZ - normal
3977 //================================================================================
3979 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3980 const TopoDS_Face& face,
3981 SMESH_MesherHelper& helper,
3988 // get a shifted position
3989 gp_Pnt p = SMESH_TNodeXYZ( node );
3990 gp_XYZ shift( 0,0,0 );
3991 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3992 switch ( S.ShapeType() ) {
3995 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
4000 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
4008 p.Translate( shift * 1e-5 );
4010 TopLoc_Location loc;
4011 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
4013 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
4015 projector.Perform( p );
4016 if ( !projector.IsDone() || projector.NbPoints() < 1 )
4022 projector.LowerDistanceParameters(U,V);
4027 uv = helper.GetNodeUV( face, node, 0, &isOK );
4033 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4035 if ( !shiftInside &&
4036 helper.IsDegenShape( node->getshapeId() ) &&
4037 getFaceNormalAtSingularity( uv, face, helper, normal ))
4040 return normal.XYZ();
4043 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
4044 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4046 if ( pointKind == IMPOSSIBLE &&
4047 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
4049 // probably NormEstim() failed due to a too high tolerance
4050 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
4051 isOK = ( pointKind < IMPOSSIBLE );
4053 if ( pointKind < IMPOSSIBLE )
4055 if ( pointKind != REGULAR &&
4057 node->GetPosition()->GetDim() < 2 ) // FACE boundary
4059 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
4060 if ( normShift * normal.XYZ() < 0. )
4066 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
4068 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
4070 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4071 while ( fIt->more() )
4073 const SMDS_MeshElement* f = fIt->next();
4074 if ( f->getshapeId() == faceID )
4076 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
4079 TopoDS_Face ff = face;
4080 ff.Orientation( TopAbs_FORWARD );
4081 if ( helper.IsReversedSubMesh( ff ))
4088 return normal.XYZ();
4091 //================================================================================
4093 * \brief Try to get normal at a singularity of a surface basing on it's nature
4095 //================================================================================
4097 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
4098 const TopoDS_Face& face,
4099 SMESH_MesherHelper& /*helper*/,
4102 BRepAdaptor_Surface surface( face );
4104 if ( !getRovolutionAxis( surface, axis ))
4107 double f,l, d, du, dv;
4108 f = surface.FirstUParameter();
4109 l = surface.LastUParameter();
4110 d = ( uv.X() - f ) / ( l - f );
4111 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4112 f = surface.FirstVParameter();
4113 l = surface.LastVParameter();
4114 d = ( uv.Y() - f ) / ( l - f );
4115 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4118 gp_Pnt2d testUV = uv;
4119 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4121 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
4122 for ( int iLoop = 0; true ; ++iLoop )
4124 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
4125 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
4132 if ( axis * refDir < 0. )
4140 //================================================================================
4142 * \brief Return a normal at a node weighted with angles taken by faces
4144 //================================================================================
4146 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
4148 const SMDS_MeshNode* n = edge->_nodes[0];
4150 gp_XYZ resNorm(0,0,0);
4151 SMESH_TNodeXYZ p0( n ), pP, pN;
4152 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4154 pP.Set( edge->_simplices[i]._nPrev );
4155 pN.Set( edge->_simplices[i]._nNext );
4156 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
4157 double l0P = v0P.SquareMagnitude();
4158 double l0N = v0N.SquareMagnitude();
4159 double lPN = vPN.SquareMagnitude();
4160 if ( l0P < std::numeric_limits<double>::min() ||
4161 l0N < std::numeric_limits<double>::min() ||
4162 lPN < std::numeric_limits<double>::min() )
4164 double lNorm = norm.SquareMagnitude();
4165 double sin2 = lNorm / l0P / l0N;
4166 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4168 double weight = sin2 * angle / lPN;
4169 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4175 //================================================================================
4177 * \brief Return a normal at a node by getting a common point of offset planes
4178 * defined by the FACE normals
4180 //================================================================================
4182 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
4183 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4187 SMESH_TNodeXYZ p0 = edge->_nodes[0];
4189 gp_XYZ resNorm(0,0,0);
4190 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4191 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4193 for ( int i = 0; i < nbFaces; ++i )
4194 resNorm += f2Normal[i].second;
4198 // prepare _OffsetPlane's
4199 vector< _OffsetPlane > pln( nbFaces );
4200 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4202 pln[i]._faceIndex = i;
4203 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4207 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4208 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4211 // intersect neighboring OffsetPlane's
4212 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4213 while ( const TopoDS_Shape* edge = edgeIt->next() )
4215 int f1 = -1, f2 = -1;
4216 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
4217 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4218 (( f1 < 0 ) ? f1 : f2 ) = i;
4221 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4224 // get a common point
4225 gp_XYZ commonPnt( 0, 0, 0 );
4228 for ( int i = 0; i < nbFaces; ++i )
4230 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4231 nbPoints += isPointFound;
4233 gp_XYZ wgtNorm = getWeigthedNormal( edge );
4234 if ( nbPoints == 0 )
4237 commonPnt /= nbPoints;
4238 resNorm = commonPnt - p0;
4242 // choose the best among resNorm and wgtNorm
4243 resNorm.Normalize();
4244 wgtNorm.Normalize();
4245 double resMinDot = std::numeric_limits<double>::max();
4246 double wgtMinDot = std::numeric_limits<double>::max();
4247 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4249 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4250 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4253 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4255 edge->Set( _LayerEdge::MULTI_NORMAL );
4258 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4261 //================================================================================
4263 * \brief Compute line of intersection of 2 planes
4265 //================================================================================
4267 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
4268 const TopoDS_Edge& E,
4269 const TopoDS_Vertex& V )
4271 int iNext = bool( _faceIndexNext[0] >= 0 );
4272 _faceIndexNext[ iNext ] = pln._faceIndex;
4274 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4275 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4277 gp_XYZ lineDir = n1 ^ n2;
4279 double x = Abs( lineDir.X() );
4280 double y = Abs( lineDir.Y() );
4281 double z = Abs( lineDir.Z() );
4283 int cooMax; // max coordinate
4285 if (x > z) cooMax = 1;
4289 if (y > z) cooMax = 2;
4294 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4296 // parallel planes - intersection is an offset of the common EDGE
4297 gp_Pnt p = BRep_Tool::Pnt( V );
4298 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4299 lineDir = getEdgeDir( E, V, 0.1 * SMESH_Algo::EdgeLength( E ));
4303 // the constants in the 2 plane equations
4304 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
4305 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4310 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4311 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4314 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4316 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4319 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4320 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4324 gp_Lin& line = _lines[ iNext ];
4325 line.SetDirection( lineDir );
4326 line.SetLocation ( linePos );
4328 _isLineOK[ iNext ] = true;
4331 iNext = bool( pln._faceIndexNext[0] >= 0 );
4332 pln._lines [ iNext ] = line;
4333 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4334 pln._isLineOK [ iNext ] = true;
4337 //================================================================================
4339 * \brief Computes intersection point of two _lines
4341 //================================================================================
4343 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4344 const TopoDS_Vertex & V) const
4349 if ( NbLines() == 2 )
4351 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4352 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4353 if ( Abs( dot01 ) > 0.05 )
4355 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4356 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4357 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4362 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4363 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4364 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4365 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4366 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4374 //================================================================================
4376 * \brief Find 2 neighbor nodes of a node on EDGE
4378 //================================================================================
4380 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4381 const SMDS_MeshNode*& n1,
4382 const SMDS_MeshNode*& n2,
4386 const SMDS_MeshNode* node = edge->_nodes[0];
4387 const int shapeInd = eos._shapeID;
4388 SMESHDS_SubMesh* edgeSM = 0;
4389 if ( eos.ShapeType() == TopAbs_EDGE )
4391 edgeSM = eos._subMesh->GetSubMeshDS();
4392 if ( !edgeSM || edgeSM->NbElements() == 0 )
4393 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4397 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4398 while ( eIt->more() && !n2 )
4400 const SMDS_MeshElement* e = eIt->next();
4401 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4402 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4405 if (!edgeSM->Contains(e)) continue;
4409 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4410 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4412 ( iN++ ? n2 : n1 ) = nNeibor;
4415 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4419 //================================================================================
4421 * \brief Create _Curvature
4423 //================================================================================
4425 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4427 // double _r; // radius
4428 // double _k; // factor to correct node smoothed position
4429 // double _h2lenRatio; // avgNormProj / (2*avgDist)
4430 // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4433 if ( fabs( avgNormProj / avgDist ) > 1./200 )
4435 c = _Factory::NewCurvature();
4436 c->_r = avgDist * avgDist / avgNormProj;
4437 c->_k = avgDist * avgDist / c->_r / c->_r;
4438 //c->_k = avgNormProj / c->_r;
4439 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4440 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4442 c->_uv.SetCoord( 0., 0. );
4447 //================================================================================
4449 * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4451 //================================================================================
4453 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4454 const SMDS_MeshNode* n2,
4455 const _EdgesOnShape& eos,
4456 SMESH_MesherHelper& helper)
4458 if ( eos.ShapeType() != TopAbs_EDGE )
4460 if ( _curvature && Is( SMOOTHED_C1 ))
4463 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4464 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4465 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4469 double sumLen = vec1.Modulus() + vec2.Modulus();
4470 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4471 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4472 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4473 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4474 _curvature = _Curvature::New( avgNormProj, avgLen );
4475 // if ( _curvature )
4476 // debugMsg( _nodes[0]->GetID()
4477 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4478 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4479 // << _curvature->lenDelta(0) );
4483 if ( eos._sWOL.IsNull() )
4485 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4486 // if ( SMESH_Algo::isDegenerated( E ))
4488 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4489 gp_XYZ plnNorm = dirE ^ _normal;
4490 double proj0 = plnNorm * vec1;
4491 double proj1 = plnNorm * vec2;
4492 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4494 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4495 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4500 //================================================================================
4502 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4503 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4505 //================================================================================
4507 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4509 SMESH_MesherHelper& helper )
4511 _nodes = other._nodes;
4512 _normal = other._normal;
4514 _lenFactor = other._lenFactor;
4515 _cosin = other._cosin;
4516 _2neibors = other._2neibors;
4517 _curvature = other._curvature;
4518 _2neibors = other._2neibors;
4519 _maxLen = Precision::Infinite();//other._maxLen;
4523 gp_XYZ lastPos( 0,0,0 );
4524 if ( eos.SWOLType() == TopAbs_EDGE )
4526 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4527 _pos.push_back( gp_XYZ( u, 0, 0));
4529 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4534 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4535 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4537 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4538 lastPos.SetX( uv.X() );
4539 lastPos.SetY( uv.Y() );
4544 //================================================================================
4546 * \brief Set _cosin and _lenFactor
4548 //================================================================================
4550 double _LayerEdge::SetCosin( double cosin )
4553 cosin = Abs( _cosin );
4554 //_lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4555 double realLenFactor;
4556 if ( cosin < 1.-1e-12 )
4558 _lenFactor = realLenFactor = 1./sqrt(1-cosin*cosin );
4563 realLenFactor = Precision::Infinite();
4566 return realLenFactor;
4569 //================================================================================
4571 * \brief Check if another _LayerEdge is a neighbor on EDGE
4573 //================================================================================
4575 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4577 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4578 ( edge->_2neibors && edge->_2neibors->include( this )));
4581 //================================================================================
4583 * \brief Fills a vector<_Simplex >
4585 //================================================================================
4587 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4588 vector<_Simplex>& simplices,
4589 const set<TGeomID>& ingnoreShapes,
4590 const _SolidData* dataToCheckOri,
4594 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4595 while ( fIt->more() )
4597 const SMDS_MeshElement* f = fIt->next();
4598 const TGeomID shapeInd = f->getshapeId();
4599 if ( ingnoreShapes.count( shapeInd )) continue;
4600 const int nbNodes = f->NbCornerNodes();
4601 const int srcInd = f->GetNodeIndex( node );
4602 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4603 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4604 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4605 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4606 std::swap( nPrev, nNext );
4607 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4611 SortSimplices( simplices );
4614 //================================================================================
4616 * \brief Set neighbor simplices side by side
4618 //================================================================================
4620 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4622 vector<_Simplex> sortedSimplices( simplices.size() );
4623 sortedSimplices[0] = simplices[0];
4625 for ( size_t i = 1; i < simplices.size(); ++i )
4627 for ( size_t j = 1; j < simplices.size(); ++j )
4628 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4630 sortedSimplices[i] = simplices[j];
4635 if ( nbFound == simplices.size() - 1 )
4636 simplices.swap( sortedSimplices );
4639 //================================================================================
4641 * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4643 //================================================================================
4645 void _ViscousBuilder::makeGroupOfLE()
4648 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4650 if ( _sdVec[i]._n2eMap.empty() ) continue;
4652 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4653 TNode2Edge::iterator n2e;
4654 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4656 _LayerEdge* le = n2e->second;
4657 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4658 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4659 // << ", " << le->_nodes[iN]->GetID() <<"])");
4661 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4662 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4667 dumpFunction( SMESH_Comment("makeNormals") << i );
4668 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4670 _LayerEdge* edge = n2e->second;
4671 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4672 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4673 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4674 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4678 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4679 dumpCmd( "faceId1 = mesh.NbElements()" );
4680 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4681 for ( ; fExp.More(); fExp.Next() )
4683 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4685 if ( sm->NbElements() == 0 ) continue;
4686 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4687 while ( fIt->more())
4689 const SMDS_MeshElement* e = fIt->next();
4690 SMESH_Comment cmd("mesh.AddFace([");
4691 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4692 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4697 dumpCmd( "faceId2 = mesh.NbElements()" );
4698 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4699 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4700 << "'%s-%s' % (faceId1+1, faceId2))");
4706 //================================================================================
4708 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4710 //================================================================================
4712 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4714 data._geomSize = Precision::Infinite();
4715 double intersecDist;
4716 const SMDS_MeshElement* face;
4717 SMESH_MesherHelper helper( *_mesh );
4719 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4720 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4721 data._proxyMesh->GetFaces( data._solid )));
4723 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4725 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4726 if ( eos._edges.empty() )
4728 // get neighbor faces, intersection with which should not be considered since
4729 // collisions are avoided by means of smoothing
4730 set< TGeomID > neighborFaces;
4731 if ( eos._hyp.ToSmooth() )
4733 SMESH_subMeshIteratorPtr subIt =
4734 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4735 while ( subIt->more() )
4737 SMESH_subMesh* sm = subIt->next();
4738 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4739 while ( const TopoDS_Shape* face = fIt->next() )
4740 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4743 // find intersections
4744 double thinkness = eos._hyp.GetTotalThickness();
4745 for ( size_t i = 0; i < eos._edges.size(); ++i )
4747 if ( eos._edges[i]->_nodes.size() < 2 ) continue;
4748 eos._edges[i]->SetMaxLen( thinkness );
4749 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4750 if ( intersecDist > 0 && face )
4752 data._geomSize = Min( data._geomSize, intersecDist );
4753 if ( !neighborFaces.count( face->getshapeId() ))
4754 eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4759 data._maxThickness = 0;
4760 data._minThickness = 1e100;
4761 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4762 for ( ; hyp != data._hyps.end(); ++hyp )
4764 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4765 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4768 // Limit inflation step size by geometry size found by intersecting
4769 // normals of _LayerEdge's with mesh faces
4770 if ( data._stepSize > 0.3 * data._geomSize )
4771 limitStepSize( data, 0.3 * data._geomSize );
4773 if ( data._stepSize > data._minThickness )
4774 limitStepSize( data, data._minThickness );
4777 // -------------------------------------------------------------------------
4778 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4779 // so no need in detecting intersection at each inflation step
4780 // -------------------------------------------------------------------------
4782 int nbSteps = data._maxThickness / data._stepSize;
4783 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4786 vector< const SMDS_MeshElement* > closeFaces;
4789 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4791 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4792 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4795 for ( size_t i = 0; i < eos.size(); ++i )
4797 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4798 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4800 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4802 bool toIgnore = true;
4803 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4804 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4805 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4807 // check if a _LayerEdge will inflate in a direction opposite to a direction
4808 // toward a close face
4809 bool allBehind = true;
4810 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4812 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4813 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4815 toIgnore = allBehind;
4819 if ( toIgnore ) // no need to detect intersection
4821 eos[i]->Set( _LayerEdge::INTERSECTED );
4827 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4832 //================================================================================
4834 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4836 //================================================================================
4838 bool _ViscousBuilder::inflate(_SolidData& data)
4840 SMESH_MesherHelper helper( *_mesh );
4842 const double tgtThick = data._maxThickness;
4844 if ( data._stepSize < 1. )
4845 data._epsilon = data._stepSize * 1e-7;
4847 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4850 findCollisionEdges( data, helper );
4852 limitMaxLenByCurvature( data, helper );
4856 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4857 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4858 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4859 data._edgesOnShape[i]._edges.size() > 0 &&
4860 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4862 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4863 data._edgesOnShape[i]._edges[0]->Block( data );
4866 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4868 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4869 int nbSteps = 0, nbRepeats = 0;
4870 while ( avgThick < 0.99 )
4872 // new target length
4873 double prevThick = curThick;
4874 curThick += data._stepSize;
4875 if ( curThick > tgtThick )
4877 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4881 double stepSize = curThick - prevThick;
4882 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4884 // Elongate _LayerEdge's
4885 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4886 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4888 _EdgesOnShape& eos = data._edgesOnShape[iS];
4889 if ( eos._edges.empty() ) continue;
4891 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4892 for ( size_t i = 0; i < eos._edges.size(); ++i )
4894 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4899 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4902 // Improve and check quality
4903 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4907 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4908 debugMsg("NOT INVALIDATED STEP!");
4909 return error("Smoothing failed", data._index);
4911 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4912 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4914 _EdgesOnShape& eos = data._edgesOnShape[iS];
4915 for ( size_t i = 0; i < eos._edges.size(); ++i )
4916 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4920 break; // no more inflating possible
4924 // Evaluate achieved thickness
4926 int nbActiveEdges = 0;
4927 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4929 _EdgesOnShape& eos = data._edgesOnShape[iS];
4930 if ( eos._edges.empty() ) continue;
4932 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4933 for ( size_t i = 0; i < eos._edges.size(); ++i )
4935 if ( eos._edges[i]->_nodes.size() > 1 )
4936 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4939 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4942 avgThick /= data._n2eMap.size();
4943 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4945 #ifdef BLOCK_INFLATION
4946 if ( nbActiveEdges == 0 )
4948 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4952 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4954 debugMsg( "-- Stop inflation since "
4955 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4956 << tgtThick * avgThick << " ) * " << safeFactor );
4962 limitStepSize( data, 0.25 * distToIntersection );
4963 if ( data._stepSizeNodes[0] )
4964 data._stepSize = data._stepSizeCoeff *
4965 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4967 } // while ( avgThick < 0.99 )
4970 return error("failed at the very first inflation step", data._index);
4972 if ( avgThick < 0.99 )
4974 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4976 data._proxyMesh->_warning.reset
4977 ( new SMESH_ComputeError (COMPERR_WARNING,
4978 SMESH_Comment("Thickness ") << tgtThick <<
4979 " of viscous layers not reached,"
4980 " average reached thickness is " << avgThick*tgtThick));
4984 // Restore position of src nodes moved by inflation on _noShrinkShapes
4985 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4986 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4988 _EdgesOnShape& eos = data._edgesOnShape[iS];
4989 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4990 for ( size_t i = 0; i < eos._edges.size(); ++i )
4992 restoreNoShrink( *eos._edges[ i ] );
4997 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
5000 //================================================================================
5002 * \brief Improve quality of layer inner surface and check intersection
5004 //================================================================================
5006 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
5008 double & distToIntersection)
5010 if ( data._nbShapesToSmooth == 0 )
5011 return true; // no shapes needing smoothing
5013 bool moved, improved;
5015 vector< _LayerEdge* > movedEdges, badEdges;
5016 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
5017 vector< bool > isConcaveFace;
5019 SMESH_MesherHelper helper(*_mesh);
5020 Handle(ShapeAnalysis_Surface) surface;
5023 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
5025 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
5027 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5029 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5030 if ( !eos._toSmooth ||
5031 eos.ShapeType() != shapeType ||
5032 eos._edges.empty() )
5035 // already smoothed?
5036 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
5037 // if ( !toSmooth ) continue;
5039 if ( !eos._hyp.ToSmooth() )
5041 // smooth disabled by the user; check validy only
5042 if ( !isFace ) continue;
5044 for ( size_t i = 0; i < eos._edges.size(); ++i )
5046 _LayerEdge* edge = eos._edges[i];
5047 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
5048 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
5050 // debugMsg( "-- Stop inflation. Bad simplex ("
5051 // << " "<< edge->_nodes[0]->GetID()
5052 // << " "<< edge->_nodes.back()->GetID()
5053 // << " "<< edge->_simplices[iF]._nPrev->GetID()
5054 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
5056 badEdges.push_back( edge );
5059 if ( !badEdges.empty() )
5063 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5067 continue; // goto the next EDGE or FACE
5071 if ( eos.SWOLType() == TopAbs_FACE )
5073 if ( !F.IsSame( eos._sWOL )) {
5074 F = TopoDS::Face( eos._sWOL );
5075 helper.SetSubShape( F );
5076 surface = helper.GetSurface( F );
5081 F.Nullify(); surface.Nullify();
5083 const TGeomID sInd = eos._shapeID;
5085 // perform smoothing
5087 if ( eos.ShapeType() == TopAbs_EDGE )
5089 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
5091 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
5093 // smooth on EDGE's (normally we should not get here)
5097 for ( size_t i = 0; i < eos._edges.size(); ++i )
5099 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
5101 dumpCmd( SMESH_Comment("# end step ")<<step);
5103 while ( moved && step++ < 5 );
5108 else // smooth on FACE
5111 eosC1.push_back( & eos );
5112 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
5115 isConcaveFace.resize( eosC1.size() );
5116 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5118 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
5120 if ( eosC1[ iEOS ]->_mapper2D )
5122 // compute node position by boundary node position in structured mesh
5123 dumpFunction(SMESH_Comment("map2dS")<<data._index<<"_Fa"<<eos._shapeID
5124 <<"_InfStep"<<infStep);
5126 eosC1[ iEOS ]->_mapper2D->ComputeNodePositions();
5128 for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5129 le->_pos.back() = SMESH_NodeXYZ( le->_nodes.back() );
5135 for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5136 if ( le->Is( _LayerEdge::MOVED ) ||
5137 le->Is( _LayerEdge::NEAR_BOUNDARY ))
5138 movedEdges.push_back( le );
5140 makeOffsetSurface( *eosC1[ iEOS ], helper );
5143 int step = 0, stepLimit = 5, nbBad = 0;
5144 while (( ++step <= stepLimit ) || improved )
5146 int oldBadNb = nbBad;
5149 #ifdef INCREMENTAL_SMOOTH
5150 // smooth moved only
5151 if ( !movedEdges.empty() )
5152 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5153 <<"_InfStep"<<infStep<<"_"<<step); // debug
5154 bool findBest = false; // ( step == stepLimit );
5155 for ( size_t i = 0; i < movedEdges.size(); ++i )
5157 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
5158 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
5159 badEdges.push_back( movedEdges[i] );
5163 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5164 <<"_InfStep"<<infStep<<"_"<<step); // debug
5165 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
5166 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5168 if ( eosC1[ iEOS ]->_mapper2D )
5170 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
5171 for ( size_t i = 0; i < edges.size(); ++i )
5173 edges[i]->Unset( _LayerEdge::SMOOTHED );
5174 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
5175 badEdges.push_back( eos._edges[i] );
5179 nbBad = badEdges.size();
5182 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5184 if ( !badEdges.empty() && step >= stepLimit / 2 )
5186 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
5189 // resolve hard smoothing situation around concave VERTEXes
5190 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5192 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5193 for ( size_t i = 0; i < eosCoVe.size(); ++i )
5194 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5197 // look for the best smooth of _LayerEdge's neighboring badEdges
5199 for ( size_t i = 0; i < badEdges.size(); ++i )
5201 _LayerEdge* ledge = badEdges[i];
5202 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5204 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5205 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5207 ledge->Unset( _LayerEdge::SMOOTHED );
5208 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5210 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5213 if ( nbBad == oldBadNb &&
5215 step < stepLimit ) // smooth w/o check of validity
5218 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5219 <<"_InfStep"<<infStep<<"_"<<step); // debug
5220 for ( size_t i = 0; i < movedEdges.size(); ++i )
5222 movedEdges[i]->SmoothWoCheck();
5224 if ( stepLimit < 9 )
5228 improved = ( nbBad < oldBadNb );
5232 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5233 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5235 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5238 } // smoothing steps
5240 // project -- to prevent intersections or to fix bad simplices
5241 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5243 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5244 putOnOffsetSurface( *eosC1[ iEOS ], -infStep, eosC1 );
5247 //if ( !badEdges.empty() )
5250 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5252 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5254 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5256 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5257 edge->CheckNeiborsOnBoundary( & badEdges );
5258 if (( nbBad > 0 ) ||
5259 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5261 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5262 gp_XYZ prevXYZ = edge->PrevCheckPos();
5263 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5264 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5266 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5267 << " "<< tgtXYZ._node->GetID()
5268 << " "<< edge->_simplices[j]._nPrev->GetID()
5269 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5270 badEdges.push_back( edge );
5277 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5278 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5284 } // // smooth on FACE's
5286 } // smooth on [ EDGEs, FACEs ]
5288 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5290 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5292 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5293 if ( eos.ShapeType() == TopAbs_FACE ||
5294 eos._edges.empty() ||
5295 !eos._sWOL.IsNull() )
5299 for ( size_t i = 0; i < eos._edges.size(); ++i )
5301 _LayerEdge* edge = eos._edges[i];
5302 if ( edge->_nodes.size() < 2 ) continue;
5303 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5304 //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5305 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
5306 //const gp_XYZ& prevXYZ = edge->PrevPos();
5307 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5308 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5310 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5311 << " "<< tgtXYZ._node->GetID()
5312 << " "<< edge->_simplices[j]._nPrev->GetID()
5313 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5314 badEdges.push_back( edge );
5319 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5321 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5327 // Check if the last segments of _LayerEdge intersects 2D elements;
5328 // checked elements are either temporary faces or faces on surfaces w/o the layers
5330 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5331 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5332 data._proxyMesh->GetFaces( data._solid )) );
5334 #ifdef BLOCK_INFLATION
5335 const bool toBlockInfaltion = true;
5337 const bool toBlockInfaltion = false;
5339 distToIntersection = Precision::Infinite();
5341 const SMDS_MeshElement* intFace = 0;
5342 const SMDS_MeshElement* closestFace = 0;
5344 bool is1stBlocked = true; // dbg
5345 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5347 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5348 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5350 for ( size_t i = 0; i < eos._edges.size(); ++i )
5352 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5353 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5355 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5358 // commented due to "Illegal hash-positionPosition" error in NETGEN
5359 // on Debian60 on viscous_layers_01/B2 case
5360 // Collision; try to deflate _LayerEdge's causing it
5361 // badEdges.clear();
5362 // badEdges.push_back( eos._edges[i] );
5363 // eosC1[0] = & eos;
5364 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5368 // badEdges.clear();
5369 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5371 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5373 // const SMDS_MeshElement* srcFace =
5374 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5375 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5376 // while ( nIt->more() )
5378 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5379 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5380 // if ( n2e != data._n2eMap.end() )
5381 // badEdges.push_back( n2e->second );
5384 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5389 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5396 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5401 const bool isShorterDist = ( distToIntersection > dist );
5402 if ( toBlockInfaltion || isShorterDist )
5404 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5405 // lying on this _ConvexFace
5406 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5407 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5410 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5411 // ( avoid limiting the thickness on the case of issue 22576)
5412 if ( intFace->getshapeId() == eos._shapeID )
5415 // ignore intersection with intFace of an adjacent FACE
5416 if ( dist > 0.01 * eos._edges[i]->_len )
5418 bool toIgnore = false;
5419 if ( eos._toSmooth )
5421 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5422 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5424 TopExp_Explorer sub( eos._shape,
5425 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5426 for ( ; !toIgnore && sub.More(); sub.Next() )
5427 // is adjacent - has a common EDGE or VERTEX
5428 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5430 if ( toIgnore ) // check angle between normals
5433 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5434 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5438 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5440 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5442 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5443 toIgnore = ( nInd >= 0 );
5450 // intersection not ignored
5453 if ( eos._edges[i]->_maxLen < 0.99 * eos._hyp.GetTotalThickness() ) // limited length
5454 minDist = eos._edges[i]->_len * theThickToIntersection;
5456 if ( toBlockInfaltion && dist < minDist )
5458 if ( is1stBlocked ) { is1stBlocked = false; // debug
5459 dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5461 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5462 eos._edges[i]->Block( data ); // not to inflate
5464 //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5466 // block _LayerEdge's, on top of which intFace is
5467 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5469 const SMDS_MeshElement* srcFace = f->_srcFace;
5470 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5471 while ( nIt->more() )
5473 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5474 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5475 if ( n2e != data._n2eMap.end() )
5476 n2e->second->Block( data );
5482 if ( isShorterDist )
5484 distToIntersection = dist;
5486 closestFace = intFace;
5489 } // if ( toBlockInfaltion || isShorterDist )
5490 } // loop on eos._edges
5491 } // loop on data._edgesOnShape
5493 if ( !is1stBlocked )
5498 if ( closestFace && le )
5501 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5502 cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5503 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5504 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5505 << ") distance = " << distToIntersection<< endl;
5512 //================================================================================
5514 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5515 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5516 * \return int - resulting nb of bad _LayerEdge's
5518 //================================================================================
5520 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5521 SMESH_MesherHelper& helper,
5522 vector< _LayerEdge* >& badSmooEdges,
5523 vector< _EdgesOnShape* >& eosC1,
5526 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5528 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5531 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5532 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5533 ADDED = _LayerEdge::UNUSED_FLAG * 4
5535 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5538 bool haveInvalidated = true;
5539 while ( haveInvalidated )
5541 haveInvalidated = false;
5542 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5544 _LayerEdge* edge = badSmooEdges[i];
5545 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5547 bool invalidated = false;
5548 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5550 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5551 edge->Block( data );
5552 edge->Set( INVALIDATED );
5553 edge->Unset( TO_INVALIDATE );
5555 haveInvalidated = true;
5558 // look for _LayerEdge's of bad _simplices
5560 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5561 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5562 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5563 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5565 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5566 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5570 _LayerEdge* ee[2] = { 0,0 };
5571 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5572 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5573 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5575 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5576 while ( maxNbSteps > edge->NbSteps() && isBad )
5579 for ( int iE = 0; iE < 2; ++iE )
5581 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5582 ee[ iE ]->NbSteps() > 1 )
5584 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5585 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5586 ee[ iE ]->Block( data );
5587 ee[ iE ]->Set( INVALIDATED );
5588 haveInvalidated = true;
5591 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5592 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5596 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5597 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5598 ee[0]->Set( ADDED );
5599 ee[1]->Set( ADDED );
5602 ee[0]->Set( TO_INVALIDATE );
5603 ee[1]->Set( TO_INVALIDATE );
5607 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5609 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5610 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5611 edge->Block( data );
5612 edge->Set( INVALIDATED );
5613 edge->Unset( TO_INVALIDATE );
5614 haveInvalidated = true;
5616 } // loop on badSmooEdges
5617 } // while ( haveInvalidated )
5619 // re-smooth on analytical EDGEs
5620 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5622 _LayerEdge* edge = badSmooEdges[i];
5623 if ( !edge->Is( INVALIDATED )) continue;
5625 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5626 if ( eos->ShapeType() == TopAbs_VERTEX )
5628 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5629 while ( const TopoDS_Shape* e = eIt->next() )
5630 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5631 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5633 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5634 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5635 // F = TopoDS::Face( eoe->_sWOL );
5636 // surface = helper.GetSurface( F );
5638 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5639 eoe->_edgeSmoother->_anaCurve.Nullify();
5645 // check result of invalidation
5648 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5650 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5652 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5653 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5654 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5655 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5656 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5657 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5660 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5661 << " "<< tgtXYZ._node->GetID()
5662 << " "<< edge->_simplices[j]._nPrev->GetID()
5663 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5672 //================================================================================
5674 * \brief Create an offset surface
5676 //================================================================================
5678 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5680 if ( eos._offsetSurf.IsNull() ||
5681 eos._edgeForOffset == 0 ||
5682 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5685 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5688 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5689 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5690 eos._offsetValue = baseSurface->Gap();
5692 eos._offsetSurf.Nullify();
5696 BRepOffsetAPI_MakeOffsetShape offsetMaker;
5697 offsetMaker.PerformByJoin( eos._shape, -eos._offsetValue, Precision::Confusion() );
5698 if ( !offsetMaker.IsDone() ) return;
5700 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5701 if ( !fExp.More() ) return;
5703 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5704 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5705 if ( surf.IsNull() ) return;
5707 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5709 catch ( Standard_Failure& )
5714 //================================================================================
5716 * \brief Put nodes of a curved FACE to its offset surface
5718 //================================================================================
5720 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5722 vector< _EdgesOnShape* >& eosC1,
5726 _EdgesOnShape * eof = & eos;
5727 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5730 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5732 if ( eosC1[i]->_offsetSurf.IsNull() ||
5733 eosC1[i]->ShapeType() != TopAbs_FACE ||
5734 eosC1[i]->_edgeForOffset == 0 ||
5735 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5737 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5742 eof->_offsetSurf.IsNull() ||
5743 eof->ShapeType() != TopAbs_FACE ||
5744 eof->_edgeForOffset == 0 ||
5745 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5748 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5749 bool neighborHasRiskySWOL = false;
5750 for ( size_t i = 0; i < eos._edges.size(); ++i )
5752 _LayerEdge* edge = eos._edges[i];
5753 edge->Unset( _LayerEdge::MARKED );
5754 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5756 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5758 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5761 else if ( moveAll == _LayerEdge::RISKY_SWOL )
5763 if ( !edge->Is( _LayerEdge::RISKY_SWOL ) ||
5767 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5770 int nbBlockedAround = 0;
5771 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5773 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5774 if ( edge->_neibors[iN]->Is( _LayerEdge::RISKY_SWOL ) &&
5775 edge->_neibors[iN]->_cosin > 0 )
5776 neighborHasRiskySWOL = true;
5778 if ( nbBlockedAround > 1 )
5781 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5782 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5783 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5784 edge->_curvature->_uv = uv;
5785 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5787 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5788 gp_XYZ prevP = edge->PrevCheckPos();
5791 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5793 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5797 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5798 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5799 edge->_pos.back() = newP;
5801 edge->Set( _LayerEdge::MARKED );
5802 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5804 edge->_normal = ( newP - prevP ).Normalized();
5806 // if ( edge->_len < eof->_offsetValue )
5807 // edge->_len = eof->_offsetValue;
5809 if ( !eos._sWOL.IsNull() ) // RISKY_SWOL
5811 double change = eof->_offsetSurf->Gap() / eof->_offsetValue;
5812 if (( newP - tgtP.XYZ() ) * edge->_normal < 0 )
5813 change = 1 - change;
5815 change = 1 + change;
5816 gp_XYZ shitfVec = tgtP.XYZ() - SMESH_NodeXYZ( edge->_nodes[0] );
5817 gp_XYZ newShiftVec = shitfVec * change;
5818 double shift = edge->_normal * shitfVec;
5819 double newShift = edge->_normal * newShiftVec;
5820 newP = tgtP.XYZ() + edge->_normal * ( newShift - shift );
5822 uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, newP, preci );
5823 if ( eof->_offsetSurf->Gap() < edge->_len )
5825 edge->_curvature->_uv = uv;
5826 newP = eof->_offsetSurf->Value( uv ).XYZ();
5828 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5829 if ( !edge->UpdatePositionOnSWOL( n, /*tol=*/10 * edge->_len / ( edge->NbSteps() + 1 ),
5830 eos, eos.GetData().GetHelper() ))
5832 debugMsg("UpdatePositionOnSWOL fails in putOnOffsetSurface()" );
5841 // dumpMove() for debug
5843 for ( ; i < eos._edges.size(); ++i )
5844 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5846 if ( i < eos._edges.size() )
5848 dumpFunction(SMESH_Comment("putOnOffsetSurface_") << eos.ShapeTypeLetter() << eos._shapeID
5849 << "_InfStep" << infStep << "_" << Abs( smooStep ));
5850 for ( ; i < eos._edges.size(); ++i )
5852 if ( eos._edges[i]->Is( _LayerEdge::MARKED )) {
5853 dumpMove( eos._edges[i]->_nodes.back() );
5860 _ConvexFace* cnvFace;
5861 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5862 eos.ShapeType() == TopAbs_FACE &&
5863 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5864 !cnvFace->_normalsFixedOnBorders )
5866 // put on the surface nodes built on FACE boundaries
5867 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5868 while ( smIt->more() )
5870 SMESH_subMesh* sm = smIt->next();
5871 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5872 if ( !subEOS->_sWOL.IsNull() ) continue;
5873 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5875 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5877 cnvFace->_normalsFixedOnBorders = true;
5882 // negative smooStep means "final step", where we don't treat RISKY_SWOL edges
5883 // as edges based on FACE are a bit late comparing with them
5884 if ( smooStep >= 0 &&
5885 neighborHasRiskySWOL &&
5886 moveAll != _LayerEdge::RISKY_SWOL &&
5887 eos.ShapeType() == TopAbs_FACE )
5889 // put on the surface nodes built on FACE boundaries
5890 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5891 while ( smIt->more() )
5893 SMESH_subMesh* sm = smIt->next();
5894 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5895 if ( subEOS->_sWOL.IsNull() ) continue;
5896 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5898 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::RISKY_SWOL );
5903 //================================================================================
5905 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5906 * _LayerEdge's to be in a consequent order
5908 //================================================================================
5910 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5912 SMESH_MesherHelper& helper)
5914 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5916 TopLoc_Location loc; double f,l;
5918 Handle(Geom_Line) line;
5919 Handle(Geom_Circle) circle;
5920 bool isLine, isCirc;
5921 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5923 // check if the EDGE is a line
5924 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5925 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5926 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5928 line = Handle(Geom_Line)::DownCast( curve );
5929 circle = Handle(Geom_Circle)::DownCast( curve );
5930 isLine = (!line.IsNull());
5931 isCirc = (!circle.IsNull());
5933 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5935 isLine = SMESH_Algo::IsStraight( E );
5938 line = new Geom_Line( gp::OX() ); // only type does matter
5940 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5945 else //////////////////////////////////////////////////////////////////////// 2D case
5947 if ( !eos._isRegularSWOL ) // 23190
5950 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5952 // check if the EDGE is a line
5953 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5954 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5955 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5957 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5958 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5959 isLine = (!line2d.IsNull());
5960 isCirc = (!circle2d.IsNull());
5962 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5965 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5966 while ( nIt->more() )
5967 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5968 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5970 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5971 for ( int i = 0; i < 2 && !isLine; ++i )
5972 isLine = ( size.Coord( i+1 ) <= lineTol );
5974 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5980 line = new Geom_Line( gp::OX() ); // only type does matter
5984 gp_Pnt2d p = circle2d->Location();
5985 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5986 circle = new Geom_Circle( ax, 1.); // only center position does matter
5995 return Handle(Geom_Curve)();
5998 //================================================================================
6000 * \brief Smooth edges on EDGE
6002 //================================================================================
6004 bool _Smoother1D::Perform(_SolidData& data,
6005 Handle(ShapeAnalysis_Surface)& surface,
6006 const TopoDS_Face& F,
6007 SMESH_MesherHelper& helper )
6009 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
6012 findEdgesToSmooth();
6014 return smoothAnalyticEdge( data, surface, F, helper );
6016 return smoothComplexEdge ( data, surface, F, helper );
6019 //================================================================================
6021 * \brief Find edges to smooth
6023 //================================================================================
6025 void _Smoother1D::findEdgesToSmooth()
6027 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6028 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6029 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
6030 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6032 _eToSmooth[0].first = _eToSmooth[0].second = 0;
6034 for ( size_t i = 0; i < _eos.size(); ++i )
6036 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6038 if ( needSmoothing( _leOnV[0]._cosin,
6039 _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
6042 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6046 _eToSmooth[0].second = i+1;
6049 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
6051 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
6053 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6055 if ( needSmoothing( _leOnV[1]._cosin,
6056 _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
6058 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6062 _eToSmooth[1].first = i;
6066 //================================================================================
6068 * \brief Check if iE-th _LayerEdge needs smoothing
6070 //================================================================================
6072 bool _Smoother1D::isToSmooth( int iE )
6074 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
6075 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
6076 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
6077 gp_XYZ seg0 = pi - p0;
6078 gp_XYZ seg1 = p1 - pi;
6079 gp_XYZ tangent = seg0 + seg1;
6080 double tangentLen = tangent.Modulus();
6081 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
6082 if ( tangentLen < std::numeric_limits<double>::min() )
6084 tangent /= tangentLen;
6086 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
6088 _LayerEdge* ne = _eos[iE]->_neibors[i];
6089 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
6090 ne->_nodes.size() < 2 ||
6091 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
6093 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
6094 double proj = edgeVec * tangent;
6095 if ( needSmoothing( 1., proj, segMinLen ))
6101 //================================================================================
6103 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
6105 //================================================================================
6107 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
6108 Handle(ShapeAnalysis_Surface)& surface,
6109 const TopoDS_Face& F,
6110 SMESH_MesherHelper& helper)
6112 if ( !isAnalytic() ) return false;
6114 size_t iFrom = 0, iTo = _eos._edges.size();
6116 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
6118 if ( F.IsNull() ) // 3D
6120 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
6121 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
6122 //const gp_XYZ lineDir = pSrc1 - pSrc0;
6123 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
6124 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
6125 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6126 // vLE0->Is( _LayerEdge::BLOCKED ) ||
6127 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
6128 // vLE1->Is( _LayerEdge::BLOCKED ));
6129 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6131 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6132 if ( iFrom >= iTo ) continue;
6133 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
6134 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
6135 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6136 double param1 = _leParams[ iTo ];
6137 for ( size_t i = iFrom; i < iTo; ++i )
6139 _LayerEdge* edge = _eos[i];
6140 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
6141 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6142 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
6144 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
6146 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
6147 // double shift = ( lineDir * ( newPos - pSrc0 ) -
6148 // lineDir * ( curPos - pSrc0 ));
6149 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
6151 if ( edge->Is( _LayerEdge::BLOCKED ))
6153 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
6154 double curThick = pSrc.SquareDistance( tgtNode );
6155 double newThink = ( pSrc - newPos ).SquareModulus();
6156 if ( newThink > curThick )
6159 edge->_pos.back() = newPos;
6160 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6161 dumpMove( tgtNode );
6167 _LayerEdge* eV0 = getLEdgeOnV( 0 );
6168 _LayerEdge* eV1 = getLEdgeOnV( 1 );
6169 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
6170 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
6171 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
6173 int iPeriodic = helper.GetPeriodicIndex();
6174 if ( iPeriodic == 1 || iPeriodic == 2 )
6176 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
6177 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
6178 std::swap( uvV0, uvV1 );
6181 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6183 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6184 if ( iFrom >= iTo ) continue;
6185 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
6186 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
6187 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
6188 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
6189 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6190 double param1 = _leParams[ iTo ];
6191 gp_XY rangeUV = uv1 - uv0;
6192 for ( size_t i = iFrom; i < iTo; ++i )
6194 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6195 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6196 gp_XY newUV = uv0 + param * rangeUV;
6198 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6199 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6200 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6201 dumpMove( tgtNode );
6203 if ( SMDS_FacePositionPtr pos = tgtNode->GetPosition() ) // NULL if F is noShrink
6205 pos->SetUParameter( newUV.X() );
6206 pos->SetVParameter( newUV.Y() );
6209 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
6211 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
6213 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6214 if ( _eos[i]->_pos.size() > 2 )
6216 // modify previous positions to make _LayerEdge less sharply bent
6217 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
6218 const gp_XYZ uvShift = newUV0 - uvVec.back();
6219 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
6220 int iPrev = uvVec.size() - 2;
6223 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
6224 uvVec[ iPrev ] += uvShift * r;
6229 _eos[i]->_pos.back() = newUV0;
6236 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
6238 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
6239 gp_Pnt center3D = circle->Location();
6241 if ( F.IsNull() ) // 3D
6243 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
6244 return true; // closed EDGE - nothing to do
6246 // circle is a real curve of EDGE
6247 gp_Circ circ = circle->Circ();
6249 // new center is shifted along its axis
6250 const gp_Dir& axis = circ.Axis().Direction();
6251 _LayerEdge* e0 = getLEdgeOnV(0);
6252 _LayerEdge* e1 = getLEdgeOnV(1);
6253 SMESH_TNodeXYZ p0 = e0->_nodes.back();
6254 SMESH_TNodeXYZ p1 = e1->_nodes.back();
6255 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
6256 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
6257 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
6259 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
6261 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6262 gp_Circ newCirc( newAxis, newRadius );
6263 gp_Vec vecC1 ( newCenter, p1 );
6265 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6269 for ( size_t i = 0; i < _eos.size(); ++i )
6271 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6272 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6273 double u = uLast * _leParams[i];
6274 gp_Pnt p = ElCLib::Value( u, newCirc );
6275 _eos._edges[i]->_pos.back() = p.XYZ();
6277 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6278 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6279 dumpMove( tgtNode );
6285 const gp_XY center( center3D.X(), center3D.Y() );
6287 _LayerEdge* e0 = getLEdgeOnV(0);
6288 _LayerEdge* eM = _eos._edges[ 0 ];
6289 _LayerEdge* e1 = getLEdgeOnV(1);
6290 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6291 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6292 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6293 gp_Vec2d vec0( center, uv0 );
6294 gp_Vec2d vecM( center, uvM );
6295 gp_Vec2d vec1( center, uv1 );
6296 double uLast = vec0.Angle( vec1 ); // -PI - +PI
6297 double uMidl = vec0.Angle( vecM );
6298 if ( uLast * uMidl <= 0. )
6299 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6300 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6302 gp_Ax2d axis( center, vec0 );
6303 gp_Circ2d circ( axis, radius );
6304 for ( size_t i = 0; i < _eos.size(); ++i )
6306 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6307 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6308 double newU = uLast * _leParams[i];
6309 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6310 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6312 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6313 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6314 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6315 dumpMove( tgtNode );
6317 if ( SMDS_FacePositionPtr pos = tgtNode->GetPosition() ) // NULL if F is noShrink
6319 pos->SetUParameter( newUV.X() );
6320 pos->SetVParameter( newUV.Y() );
6322 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6331 //================================================================================
6333 * \brief smooth _LayerEdge's on a an EDGE
6335 //================================================================================
6337 bool _Smoother1D::smoothComplexEdge( _SolidData& /*data*/,
6338 Handle(ShapeAnalysis_Surface)& surface,
6339 const TopoDS_Face& F,
6340 SMESH_MesherHelper& /*helper*/)
6342 if ( _offPoints.empty() )
6345 // ----------------------------------------------
6346 // move _offPoints along normals of _LayerEdge's
6347 // ----------------------------------------------
6349 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6350 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6351 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6352 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
6353 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6354 _leOnV[0]._len = e[0]->_len;
6355 _leOnV[1]._len = e[1]->_len;
6356 for ( size_t i = 0; i < _offPoints.size(); i++ )
6358 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6359 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6360 const double w0 = _offPoints[i]._2edges._wgt[0];
6361 const double w1 = _offPoints[i]._2edges._wgt[1];
6362 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
6363 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6364 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6365 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6366 e1->Is( _LayerEdge::NORMAL_UPDATED ))
6367 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6369 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6370 _offPoints[i]._len = avgLen;
6374 if ( !surface.IsNull() ) // project _offPoints to the FACE
6376 fTol = 100 * BRep_Tool::Tolerance( F );
6377 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6379 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6380 //if ( surface->Gap() < 0.5 * segLen )
6381 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6383 for ( size_t i = 1; i < _offPoints.size(); ++i )
6385 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6386 //if ( surface->Gap() < 0.5 * segLen )
6387 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6391 // -----------------------------------------------------------------
6392 // project tgt nodes of extreme _LayerEdge's to the offset segments
6393 // -----------------------------------------------------------------
6395 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6396 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6397 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6399 gp_Pnt pExtreme[2], pProj[2];
6400 bool isProjected[2];
6401 for ( int is2nd = 0; is2nd < 2; ++is2nd )
6403 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6404 int i = _iSeg[ is2nd ];
6405 int di = is2nd ? -1 : +1;
6406 bool & projected = isProjected[ is2nd ];
6408 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6411 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
6412 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6413 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
6414 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6415 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6416 if ( dist < distMin || projected )
6419 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6422 else if ( dist > distPrev )
6424 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6430 while ( !projected &&
6431 i >= 0 && i+1 < (int)_offPoints.size() );
6435 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6438 _iSeg[1] = _offPoints.size()-2;
6439 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6444 if ( _iSeg[0] > _iSeg[1] )
6446 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6450 // adjust length of extreme LE (test viscous_layers_01/B7)
6451 gp_Vec vDiv0( pExtreme[0], pProj[0] );
6452 gp_Vec vDiv1( pExtreme[1], pProj[1] );
6453 double d0 = vDiv0.Magnitude();
6454 double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6455 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6456 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6457 else e[0]->_len -= d0;
6459 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6460 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6461 else e[1]->_len -= d1;
6464 // ---------------------------------------------------------------------------------
6465 // compute normalized length of the offset segments located between the projections
6466 // ---------------------------------------------------------------------------------
6468 // temporary replace extreme _offPoints by pExtreme
6469 gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0] ]._xyz,
6470 _offPoints[ _iSeg[1]+1 ]._xyz };
6471 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6472 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6474 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6475 vector< double > len( nbSeg + 1 );
6477 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6478 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6480 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6482 // if ( isProjected[ 1 ])
6483 // len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6485 // len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6487 double fullLen = len.back() - d0 - d1;
6488 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6489 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6491 // -------------------------------------------------------------
6492 // distribute tgt nodes of _LayerEdge's between the projections
6493 // -------------------------------------------------------------
6496 for ( size_t i = 0; i < _eos.size(); ++i )
6498 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6499 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6500 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6502 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6503 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6504 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6506 if ( surface.IsNull() )
6508 _eos[i]->_pos.back() = p;
6510 else // project a new node position to a FACE
6512 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6513 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6515 p = surface->Value( uv2 ).XYZ();
6516 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6518 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6519 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6520 dumpMove( tgtNode );
6523 _offPoints[ _iSeg[0] ]._xyz = opXYZ[0];
6524 _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6529 //================================================================================
6531 * \brief Prepare for smoothing
6533 //================================================================================
6535 void _Smoother1D::prepare(_SolidData& data)
6537 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6538 _curveLen = SMESH_Algo::EdgeLength( E );
6540 // sort _LayerEdge's by position on the EDGE
6541 data.SortOnEdge( E, _eos._edges );
6543 // compute normalized param of _eos._edges on EDGE
6544 _leParams.resize( _eos._edges.size() + 1 );
6547 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6549 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6551 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6552 curLen = p.Distance( pPrev );
6553 _leParams[i+1] = _leParams[i] + curLen;
6556 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6557 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6558 _leParams[i] = _leParams[i+1] / fullLen;
6559 _leParams.back() = 1.;
6562 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6564 // get cosin to use in findEdgesToSmooth()
6565 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6566 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6567 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6568 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6569 _leOnV[0]._flags = _leOnV[1]._flags = 0;
6570 if ( _eos._sWOL.IsNull() ) // 3D
6571 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6572 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6577 // divide E to have offset segments with low deflection
6578 BRepAdaptor_Curve c3dAdaptor( E );
6579 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2|*sin(p1p2,p1pM)
6580 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6581 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6582 if ( discret.NbPoints() <= 2 )
6584 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6588 const double u0 = c3dAdaptor.FirstParameter();
6589 gp_Pnt p; gp_Vec tangent;
6590 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6592 _offPoints.resize( discret.NbPoints() );
6593 for ( size_t i = 0; i < _offPoints.size(); i++ )
6595 double u = discret.Parameter( i+1 );
6596 c3dAdaptor.D1( u, p, tangent );
6597 _offPoints[i]._xyz = p.XYZ();
6598 _offPoints[i]._edgeDir = tangent.XYZ();
6599 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6604 std::vector< double > params( _eos.size() + 2 );
6606 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6607 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6608 for ( size_t i = 0; i < _eos.size(); i++ )
6609 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6611 if ( params[1] > params[ _eos.size() ] )
6612 std::reverse( params.begin() + 1, params.end() - 1 );
6614 _offPoints.resize( _eos.size() + 2 );
6615 for ( size_t i = 0; i < _offPoints.size(); i++ )
6617 const double u = params[i];
6618 c3dAdaptor.D1( u, p, tangent );
6619 _offPoints[i]._xyz = p.XYZ();
6620 _offPoints[i]._edgeDir = tangent.XYZ();
6621 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6626 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6627 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6628 _2NearEdges tmp2edges;
6629 tmp2edges._edges[1] = _eos._edges[0];
6630 _leOnV[0]._2neibors = & tmp2edges;
6631 _leOnV[0]._nodes = leOnV[0]->_nodes;
6632 _leOnV[1]._nodes = leOnV[1]->_nodes;
6633 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6634 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6636 // find _LayerEdge's located before and after an offset point
6637 // (_eos._edges[ iLE ] is next after ePrev)
6638 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6639 ePrev = _eos._edges[ iLE++ ];
6640 eNext = ePrev->_2neibors->_edges[1];
6642 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6643 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6644 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6645 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6648 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6649 for ( size_t i = 0; i < _offPoints.size(); i++ )
6650 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6651 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6653 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6654 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6655 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6658 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6660 int iLBO = _offPoints.size() - 2; // last but one
6662 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6663 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6665 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6666 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6667 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6669 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6670 _leOnV[ 0 ]._len = 0;
6671 _leOnV[ 1 ]._len = 0;
6672 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6673 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6676 _iSeg[1] = _offPoints.size()-2;
6678 // initialize OffPnt::_len
6679 for ( size_t i = 0; i < _offPoints.size(); ++i )
6680 _offPoints[i]._len = 0;
6682 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6684 _leOnV[0]._len = leOnV[0]->_len;
6685 _leOnV[1]._len = leOnV[1]->_len;
6686 for ( size_t i = 0; i < _offPoints.size(); i++ )
6688 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6689 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6690 const double w0 = _offPoints[i]._2edges._wgt[0];
6691 const double w1 = _offPoints[i]._2edges._wgt[1];
6692 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6693 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6694 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6695 _offPoints[i]._xyz = avgXYZ;
6696 _offPoints[i]._len = avgLen;
6701 //================================================================================
6703 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6705 //================================================================================
6707 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6708 const gp_XYZ& edgeDir)
6710 gp_XYZ cross = normal ^ edgeDir;
6711 gp_XYZ norm = edgeDir ^ cross;
6712 double size = norm.Modulus();
6714 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6715 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6717 if ( size < 1e-5 ) // normal || edgeDir (almost) at inflation along EDGE (bos #20643)
6719 const _LayerEdge* le = _eos._edges[ _eos._edges.size() / 2 ];
6720 const gp_XYZ& leNorm = le->_normal;
6722 cross = leNorm ^ edgeDir;
6723 norm = edgeDir ^ cross;
6724 size = norm.Modulus();
6730 //================================================================================
6732 * \brief Writes a script creating a mesh composed of _offPoints
6734 //================================================================================
6736 void _Smoother1D::offPointsToPython() const
6738 const char* fname = "/tmp/offPoints.py";
6739 cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6741 py << "import SMESH" << endl
6742 << "from salome.smesh import smeshBuilder" << endl
6743 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
6744 << "mesh = smesh.Mesh( 'offPoints' )"<<endl;
6745 for ( size_t i = 0; i < _offPoints.size(); i++ )
6747 py << "mesh.AddNode( "
6748 << _offPoints[i]._xyz.X() << ", "
6749 << _offPoints[i]._xyz.Y() << ", "
6750 << _offPoints[i]._xyz.Z() << " )" << endl;
6754 //================================================================================
6756 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6758 //================================================================================
6760 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6761 vector< _LayerEdge* >& edges)
6763 map< double, _LayerEdge* > u2edge;
6764 for ( size_t i = 0; i < edges.size(); ++i )
6765 u2edge.insert( u2edge.end(),
6766 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6768 ASSERT( u2edge.size() == edges.size() );
6769 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6770 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6771 edges[i] = u2e->second;
6773 Sort2NeiborsOnEdge( edges );
6776 //================================================================================
6778 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6780 //================================================================================
6782 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6784 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6786 for ( size_t i = 0; i < edges.size()-1; ++i )
6787 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6788 edges[i]->_2neibors->reverse();
6790 const size_t iLast = edges.size() - 1;
6791 if ( edges.size() > 1 &&
6792 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6793 edges[iLast]->_2neibors->reverse();
6796 //================================================================================
6798 * \brief Return _EdgesOnShape* corresponding to the shape
6800 //================================================================================
6802 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6804 if ( shapeID < (int)_edgesOnShape.size() &&
6805 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6806 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6808 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6809 if ( _edgesOnShape[i]._shapeID == shapeID )
6810 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6815 //================================================================================
6817 * \brief Return _EdgesOnShape* corresponding to the shape
6819 //================================================================================
6821 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6823 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6824 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6827 //================================================================================
6829 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6831 //================================================================================
6833 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6835 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6837 set< TGeomID > vertices;
6839 if ( eos->ShapeType() == TopAbs_FACE )
6841 // check FACE concavity and get concave VERTEXes
6842 F = TopoDS::Face( eos->_shape );
6843 if ( isConcave( F, helper, &vertices ))
6844 _concaveFaces.insert( eos->_shapeID );
6846 // set eos._eosConcaVer
6847 eos->_eosConcaVer.clear();
6848 eos->_eosConcaVer.reserve( vertices.size() );
6849 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6851 _EdgesOnShape* eov = GetShapeEdges( *v );
6852 if ( eov && eov->_edges.size() == 1 )
6854 eos->_eosConcaVer.push_back( eov );
6855 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6856 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6860 // SetSmooLen() to _LayerEdge's on FACE
6861 // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6863 // eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6865 // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6866 // while ( smIt->more() ) // loop on sub-shapes of the FACE
6868 // _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6869 // if ( !eoe ) continue;
6871 // vector<_LayerEdge*>& eE = eoe->_edges;
6872 // for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6874 // if ( eE[iE]->_cosin <= theMinSmoothCosin )
6877 // SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6878 // while ( segIt->more() )
6880 // const SMDS_MeshElement* seg = segIt->next();
6881 // if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6883 // if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6884 // continue; // not to check a seg twice
6885 // for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6887 // _LayerEdge* eN = eE[iE]->_neibors[iN];
6888 // if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6890 // double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6891 // double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6892 // eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6893 // eN->Set( _LayerEdge::NEAR_BOUNDARY );
6898 } // if ( eos->ShapeType() == TopAbs_FACE )
6900 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6902 eos->_edges[i]->_smooFunction = 0;
6903 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6905 bool isCurved = false;
6906 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6908 _LayerEdge* edge = eos->_edges[i];
6910 // get simplices sorted
6911 _Simplex::SortSimplices( edge->_simplices );
6913 // smoothing function
6914 edge->ChooseSmooFunction( vertices, _n2eMap );
6917 double avgNormProj = 0, avgLen = 0;
6918 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6920 _Simplex& s = edge->_simplices[iS];
6922 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6923 avgNormProj += edge->_normal * vec;
6924 avgLen += vec.Modulus();
6925 if ( substituteSrcNodes )
6927 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6928 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6931 avgNormProj /= edge->_simplices.size();
6932 avgLen /= edge->_simplices.size();
6933 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6935 edge->Set( _LayerEdge::SMOOTHED_C1 );
6937 SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6939 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6940 fPos = edge->_simplices[iS]._nPrev->GetPosition();
6942 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6946 // prepare for putOnOffsetSurface()
6947 if (( eos->ShapeType() == TopAbs_FACE ) &&
6948 ( isCurved || !eos->_eosConcaVer.empty() ))
6950 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6951 eos->_edgeForOffset = 0;
6953 double maxCosin = -1;
6954 //bool hasNoShrink = false;
6955 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6957 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6958 if ( !eoe || eoe->_edges.empty() ) continue;
6960 // if ( eos->GetData()._noShrinkShapes.count( eoe->_shapeID ))
6961 // hasNoShrink = true;
6963 vector<_LayerEdge*>& eE = eoe->_edges;
6964 _LayerEdge* e = eE[ eE.size() / 2 ];
6965 if ( !e->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > maxCosin )
6967 eos->_edgeForOffset = e;
6968 maxCosin = e->_cosin;
6971 if ( !eoe->_sWOL.IsNull() )
6972 for ( _LayerEdge* le : eoe->_edges )
6973 if ( le->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > 0 )
6975 // make _neibors on FACE be smoothed after le->Is( BLOCKED )
6976 for ( _LayerEdge* neibor : le->_neibors )
6978 int shapeDim = neibor->BaseShapeDim();
6979 if ( shapeDim == 2 )
6980 neibor->Set( _LayerEdge::NEAR_BOUNDARY ); // on FACE
6981 else if ( shapeDim == 0 )
6982 neibor->Set( _LayerEdge::RISKY_SWOL ); // on VERTEX
6984 if ( !neibor->_curvature )
6986 gp_XY uv = helper.GetNodeUV( F, neibor->_nodes[0] );
6987 neibor->_curvature = _Factory::NewCurvature();
6988 neibor->_curvature->_r = 0;
6989 neibor->_curvature->_k = 0;
6990 neibor->_curvature->_h2lenRatio = 0;
6991 neibor->_curvature->_uv = uv;
6997 // Try to initialize _Mapper2D
6999 // if ( hasNoShrink )
7002 SMDS_ElemIteratorPtr fIt = eos->_subMesh->GetSubMeshDS()->GetElements();
7003 if ( !fIt->more() || fIt->next()->NbCornerNodes() != 4 )
7006 // get EDGEs of quadrangle bottom
7007 std::list< TopoDS_Edge > edges;
7008 std::list< int > nbEdgesInWire;
7009 int nbWire = SMESH_Block::GetOrderedEdges( F, edges, nbEdgesInWire );
7010 if ( nbWire != 1 || nbEdgesInWire.front() < 4 )
7012 const SMDS_MeshNode* node;
7013 while ( true ) // make edges start at a corner VERTEX
7015 node = SMESH_Algo::VertexNode( helper.IthVertex( 0, edges.front() ), helper.GetMeshDS() );
7016 if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7019 if ( edges.empty() )
7022 std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
7023 while ( true ) // make edges finish at a corner VERTEX
7025 node = SMESH_Algo::VertexNode( helper.IthVertex( 1, *edgeIt ), helper.GetMeshDS() );
7027 if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7029 edges.erase( edgeIt, edges.end() );
7032 if ( edgeIt == edges.end() )
7036 // get structure of nodes
7037 TParam2ColumnMap param2ColumnMap;
7038 if ( !helper.LoadNodeColumns( param2ColumnMap, F, edges, helper.GetMeshDS() ))
7041 eos->_mapper2D = new _Mapper2D( param2ColumnMap, eos->GetData()._n2eMap );
7043 } // if eos is of curved FACE
7048 //================================================================================
7050 * \brief Add faces for smoothing
7052 //================================================================================
7054 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
7055 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
7057 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
7058 for ( ; eos != eosToSmooth.end(); ++eos )
7060 if ( !*eos || (*eos)->_toSmooth ) continue;
7062 (*eos)->_toSmooth = true;
7064 if ( (*eos)->ShapeType() == TopAbs_FACE )
7066 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
7067 (*eos)->_toSmooth = true;
7071 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
7072 if ( edgesNoAnaSmooth )
7073 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
7075 if ( (*eos)->_edgeSmoother )
7076 (*eos)->_edgeSmoother->_anaCurve.Nullify();
7080 //================================================================================
7082 * \brief Limit _LayerEdge::_maxLen according to local curvature
7084 //================================================================================
7086 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& /*helper*/ )
7088 // find intersection of neighbor _LayerEdge's to limit _maxLen
7089 // according to local curvature (IPAL52648)
7091 // This method must be called after findCollisionEdges() where _LayerEdge's
7092 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
7094 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7096 _EdgesOnShape& eosI = data._edgesOnShape[iS];
7097 if ( eosI._edges.empty() ) continue;
7098 if ( !eosI._hyp.ToSmooth() )
7100 for ( size_t i = 0; i < eosI._edges.size(); ++i )
7102 _LayerEdge* eI = eosI._edges[i];
7103 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
7105 _LayerEdge* eN = eI->_neibors[iN];
7106 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
7108 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
7109 limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
7114 else if ( eosI.ShapeType() == TopAbs_EDGE )
7116 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
7117 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
7119 _LayerEdge* e0 = eosI._edges[0];
7120 for ( size_t i = 1; i < eosI._edges.size(); ++i )
7122 _LayerEdge* eI = eosI._edges[i];
7123 limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
7130 //================================================================================
7132 * \brief Limit _LayerEdge::_maxLen according to local curvature
7134 //================================================================================
7136 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
7138 _EdgesOnShape& /*eos1*/,
7139 _EdgesOnShape& /*eos2*/,
7140 const bool /*isSmoothable*/ )
7142 if (( e1->_nodes[0]->GetPosition()->GetDim() !=
7143 e2->_nodes[0]->GetPosition()->GetDim() ) &&
7144 ( e1->_cosin < 0.75 ))
7145 return; // angle > 90 deg at e1
7147 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
7148 double norSize = plnNorm.SquareModulus();
7149 if ( norSize < std::numeric_limits<double>::min() )
7150 return; // parallel normals
7152 // find closest points of skew _LayerEdge's
7153 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
7154 gp_XYZ dir12 = src2 - src1;
7155 gp_XYZ perp1 = e1->_normal ^ plnNorm;
7156 gp_XYZ perp2 = e2->_normal ^ plnNorm;
7157 double dot1 = perp2 * e1->_normal;
7158 double dot2 = perp1 * e2->_normal;
7159 double u1 = ( perp2 * dir12 ) / dot1;
7160 double u2 = - ( perp1 * dir12 ) / dot2;
7161 if ( u1 > 0 && u2 > 0 )
7163 double ovl = ( u1 * e1->_normal * dir12 -
7164 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
7165 if ( ovl > theSmoothThickToElemSizeRatio )
7167 const double coef = 0.75;
7168 e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
7169 e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
7174 //================================================================================
7176 * \brief Fill data._collisionEdges
7178 //================================================================================
7180 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
7182 data._collisionEdges.clear();
7184 // set the full thickness of the layers to LEs
7185 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7187 _EdgesOnShape& eos = data._edgesOnShape[iS];
7188 if ( eos._edges.empty() ) continue;
7189 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7190 if ( !eos._sWOL.IsNull() ) continue; // PAL23566
7192 for ( size_t i = 0; i < eos._edges.size(); ++i )
7194 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
7195 double maxLen = eos._edges[i]->_maxLen;
7196 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
7197 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
7198 eos._edges[i]->_maxLen = maxLen;
7202 // make temporary quadrangles got by extrusion of
7203 // mesh edges along _LayerEdge._normal's
7205 vector< const SMDS_MeshElement* > tmpFaces;
7207 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7209 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7210 if ( eos.ShapeType() != TopAbs_EDGE )
7212 if ( eos._edges.empty() )
7214 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
7215 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
7216 while ( smIt->more() )
7217 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
7218 if ( eov->_edges.size() == 1 )
7219 edge[ bool( edge[0]) ] = eov->_edges[0];
7223 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
7224 tmpFaces.push_back( f );
7227 for ( size_t i = 0; i < eos._edges.size(); ++i )
7229 _LayerEdge* edge = eos._edges[i];
7230 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
7232 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
7233 if ( src2->GetPosition()->GetDim() > 0 &&
7234 src2->GetID() < edge->_nodes[0]->GetID() )
7235 continue; // avoid using same segment twice
7237 // a _LayerEdge containing tgt2
7238 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
7240 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
7241 tmpFaces.push_back( f );
7246 // Find _LayerEdge's intersecting tmpFaces.
7248 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
7250 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
7251 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
7253 double dist1, dist2, segLen, eps = 0.5;
7254 _CollisionEdges collEdges;
7255 vector< const SMDS_MeshElement* > suspectFaces;
7256 const double angle45 = Cos( 45. * M_PI / 180. );
7258 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7260 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7261 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
7263 // find sub-shapes whose VL can influence VL on eos
7264 set< TGeomID > neighborShapes;
7265 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
7266 while ( const TopoDS_Shape* face = fIt->next() )
7268 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
7269 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
7271 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
7272 while ( subIt->more() )
7273 neighborShapes.insert( subIt->next()->GetId() );
7276 if ( eos.ShapeType() == TopAbs_VERTEX )
7278 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
7279 while ( const TopoDS_Shape* edge = eIt->next() )
7280 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
7282 // find intersecting _LayerEdge's
7283 for ( size_t i = 0; i < eos._edges.size(); ++i )
7285 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
7286 _LayerEdge* edge = eos._edges[i];
7287 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
7290 gp_Vec eSegDir0, eSegDir1;
7291 if ( edge->IsOnEdge() )
7293 SMESH_TNodeXYZ eP( edge->_nodes[0] );
7294 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
7295 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
7297 suspectFaces.clear();
7298 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
7299 SMDSAbs_Face, suspectFaces );
7300 collEdges._intEdges.clear();
7301 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
7303 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
7304 if ( f->_le1 == edge || f->_le2 == edge ) continue;
7305 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
7306 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
7307 if ( edge->IsOnEdge() ) {
7308 if ( edge->_2neibors->include( f->_le1 ) ||
7309 edge->_2neibors->include( f->_le2 )) continue;
7312 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
7313 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
7315 dist1 = dist2 = Precision::Infinite();
7316 if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
7317 dist1 = Precision::Infinite();
7318 if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
7319 dist2 = Precision::Infinite();
7320 if (( dist1 > segLen ) && ( dist2 > segLen ))
7323 if ( edge->IsOnEdge() )
7325 // skip perpendicular EDGEs
7326 gp_Vec fSegDir = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
7327 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
7328 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
7329 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
7330 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
7335 // either limit inflation of edges or remember them for updating _normal
7336 // double dot = edge->_normal * f->GetDir();
7339 collEdges._intEdges.push_back( f->_le1 );
7340 collEdges._intEdges.push_back( f->_le2 );
7344 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
7345 // edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
7349 if ( !collEdges._intEdges.empty() )
7351 collEdges._edge = edge;
7352 data._collisionEdges.push_back( collEdges );
7357 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7360 // restore the zero thickness
7361 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7363 _EdgesOnShape& eos = data._edgesOnShape[iS];
7364 if ( eos._edges.empty() ) continue;
7365 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7367 for ( size_t i = 0; i < eos._edges.size(); ++i )
7369 eos._edges[i]->InvalidateStep( 1, eos );
7370 eos._edges[i]->_len = 0;
7375 //================================================================================
7377 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7378 * will be updated at each inflation step
7380 //================================================================================
7382 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
7384 SMESH_MesherHelper& helper )
7386 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7387 const double preci = BRep_Tool::Tolerance( convFace._face );
7388 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7390 bool edgesToUpdateFound = false;
7392 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7393 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7395 _EdgesOnShape& eos = * id2eos->second;
7396 if ( !eos._sWOL.IsNull() ) continue;
7397 if ( !eos._hyp.ToSmooth() ) continue;
7398 for ( size_t i = 0; i < eos._edges.size(); ++i )
7400 _LayerEdge* ledge = eos._edges[ i ];
7401 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7402 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7404 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7405 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7407 // the normal must be updated if distance from tgtPos to surface is less than
7410 // find an initial UV for search of a projection of tgtPos to surface
7411 const SMDS_MeshNode* nodeInFace = 0;
7412 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7413 while ( fIt->more() && !nodeInFace )
7415 const SMDS_MeshElement* f = fIt->next();
7416 if ( convFaceID != f->getshapeId() ) continue;
7418 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7419 while ( nIt->more() && !nodeInFace )
7421 const SMDS_MeshElement* n = nIt->next();
7422 if ( n->getshapeId() == convFaceID )
7423 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7428 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7431 surface->NextValueOfUV( uv, tgtPos, preci );
7432 double dist = surface->Gap();
7433 if ( dist < 0.95 * ledge->_maxLen )
7435 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7436 if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7437 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7438 edgesToUpdateFound = true;
7443 if ( !convFace._isTooCurved && edgesToUpdateFound )
7445 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7449 //================================================================================
7451 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7452 * _LayerEdge's on neighbor EDGE's
7454 //================================================================================
7456 bool _ViscousBuilder::updateNormals( _SolidData& data,
7457 SMESH_MesherHelper& helper,
7459 double /*stepSize*/)
7461 updateNormalsOfC1Vertices( data );
7463 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7466 // map to store new _normal and _cosin for each intersected edge
7467 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
7468 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7469 _LayerEdge zeroEdge;
7470 zeroEdge._normal.SetCoord( 0,0,0 );
7471 zeroEdge._maxLen = Precision::Infinite();
7472 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7474 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7476 double segLen, dist1, dist2, dist;
7477 vector< pair< _LayerEdge*, double > > intEdgesDist;
7478 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7480 for ( int iter = 0; iter < 5; ++iter )
7482 edge2newEdge.clear();
7484 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7486 _CollisionEdges& ce = data._collisionEdges[iE];
7487 _LayerEdge* edge1 = ce._edge;
7488 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7489 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7490 if ( !eos1 ) continue;
7492 // detect intersections
7493 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7494 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7496 intEdgesDist.clear();
7497 double minIntDist = Precision::Infinite();
7498 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7500 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7501 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
7502 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7504 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7505 double fact = ( 1.1 + dot * dot );
7506 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7507 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7508 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7509 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7510 dist1 = dist2 = Precision::Infinite();
7511 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
7512 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7515 if ( dist > testLen || dist <= 0 )
7518 if ( dist > testLen || dist <= 0 )
7521 // choose a closest edge
7522 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7523 double d1 = intP.SquareDistance( pSrc0 );
7524 double d2 = intP.SquareDistance( pSrc1 );
7525 int iClose = i + ( d2 < d1 );
7526 _LayerEdge* edge2 = ce._intEdges[iClose];
7527 edge2->Unset( _LayerEdge::MARKED );
7529 // choose a closest edge among neighbors
7530 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7531 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7532 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7534 _LayerEdge * edgeJ = intEdgesDist[j].first;
7535 if ( edge2->IsNeiborOnEdge( edgeJ ))
7537 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7538 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7541 intEdgesDist.push_back( make_pair( edge2, dist ));
7542 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7544 // iClose = i + !( d2 < d1 );
7545 // intEdges.push_back( ce._intEdges[iClose] );
7546 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7548 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7553 // compute new _normals
7554 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7556 _LayerEdge* edge2 = intEdgesDist[i].first;
7557 double distWgt = edge1->_len / intEdgesDist[i].second;
7558 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7559 // edge2->Is( _LayerEdge::BLOCKED )) continue;
7560 if ( edge2->Is( _LayerEdge::MARKED )) continue;
7561 edge2->Set( _LayerEdge::MARKED );
7564 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7566 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7567 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7568 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7569 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7570 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7571 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7572 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7573 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7574 newNormal.Normalize();
7578 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7579 if ( cos1 < theMinSmoothCosin )
7581 newCos = cos2 * sgn1;
7583 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7585 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7589 newCos = edge1->_cosin;
7592 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7593 e2neIt->second._normal += distWgt * newNormal;
7594 e2neIt->second._cosin = newCos;
7595 e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7596 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7597 e2neIt->second._normal += dir2;
7599 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7600 e2neIt->second._normal += distWgt * newNormal;
7601 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7603 e2neIt->second._cosin = edge2->_cosin;
7604 e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7606 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7607 e2neIt->second._normal += dir1;
7611 if ( edge2newEdge.empty() )
7612 break; //return true;
7614 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7616 // Update data of edges depending on a new _normal
7619 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7621 _LayerEdge* edge = e2neIt->first;
7622 _LayerEdge& newEdge = e2neIt->second;
7623 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7624 if ( edge->Is( _LayerEdge::BLOCKED ) && newEdge._maxLen > edge->_len )
7627 // Check if a new _normal is OK:
7628 newEdge._normal.Normalize();
7629 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7631 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7633 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7634 edge->SetMaxLen( newEdge._maxLen );
7635 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7637 continue; // the new _normal is bad
7639 // the new _normal is OK
7641 // find shapes that need smoothing due to change of _normal
7642 if ( edge->_cosin < theMinSmoothCosin &&
7643 newEdge._cosin > theMinSmoothCosin )
7645 if ( eos->_sWOL.IsNull() )
7647 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7648 while ( fIt->more() )
7649 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7651 else // edge inflates along a FACE
7653 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7654 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7655 while ( const TopoDS_Shape* E = eIt->next() )
7657 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ),
7658 eos->_hyp.Get1stLayerThickness() );
7659 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7660 if ( angle < M_PI / 2 )
7661 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7666 double len = edge->_len;
7667 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7668 edge->SetNormal( newEdge._normal );
7669 edge->SetCosin( newEdge._cosin );
7670 edge->SetNewLength( len, *eos, helper );
7671 edge->Set( _LayerEdge::MARKED );
7672 edge->Set( _LayerEdge::NORMAL_UPDATED );
7673 edgesNoAnaSmooth.insert( eos );
7676 // Update normals and other dependent data of not intersecting _LayerEdge's
7677 // neighboring the intersecting ones
7679 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7681 _LayerEdge* edge1 = e2neIt->first;
7682 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7683 if ( !edge1->Is( _LayerEdge::MARKED ))
7686 if ( edge1->IsOnEdge() )
7688 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7689 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7690 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7693 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7695 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7697 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7698 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7699 continue; // j-th neighbor is also intersected
7700 _LayerEdge* prevEdge = edge1;
7701 const int nbSteps = 10;
7702 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7704 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7705 neighbor->Is( _LayerEdge::MARKED ))
7707 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7708 if ( !eos ) continue;
7709 _LayerEdge* nextEdge = neighbor;
7710 if ( neighbor->_2neibors )
7713 nextEdge = neighbor->_2neibors->_edges[iNext];
7714 if ( nextEdge == prevEdge )
7715 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7717 double r = double(step-1)/nbSteps/(iter+1);
7718 if ( !nextEdge->_2neibors )
7721 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7722 newNorm.Normalize();
7723 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7726 double len = neighbor->_len;
7727 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7728 neighbor->SetNormal( newNorm );
7729 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7730 if ( neighbor->_2neibors )
7731 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7732 neighbor->SetNewLength( len, *eos, helper );
7733 neighbor->Set( _LayerEdge::MARKED );
7734 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7735 edgesNoAnaSmooth.insert( eos );
7737 if ( !neighbor->_2neibors )
7738 break; // neighbor is on VERTEX
7740 // goto the next neighbor
7741 prevEdge = neighbor;
7742 neighbor = nextEdge;
7749 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7754 //================================================================================
7756 * \brief Check if a new normal is OK
7758 //================================================================================
7760 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7762 const gp_XYZ& newNormal)
7764 // check a min angle between the newNormal and surrounding faces
7765 vector<_Simplex> simplices;
7766 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7767 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7768 double newMinDot = 1, curMinDot = 1;
7769 for ( size_t i = 0; i < simplices.size(); ++i )
7771 n1.Set( simplices[i]._nPrev );
7772 n2.Set( simplices[i]._nNext );
7773 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7774 double normLen2 = normFace.SquareModulus();
7775 if ( normLen2 < std::numeric_limits<double>::min() )
7777 normFace /= Sqrt( normLen2 );
7778 newMinDot = Min( newNormal * normFace, newMinDot );
7779 curMinDot = Min( edge._normal * normFace, curMinDot );
7782 if ( newMinDot < 0.5 )
7784 ok = ( newMinDot >= curMinDot * 0.9 );
7785 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7786 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7787 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7793 //================================================================================
7795 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7797 //================================================================================
7799 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7800 SMESH_MesherHelper& /*helper*/,
7802 const double stepSize )
7804 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7805 return true; // no shapes needing smoothing
7807 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7809 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7810 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7811 !eos._hyp.ToSmooth() ||
7812 eos.ShapeType() != TopAbs_FACE ||
7813 eos._edges.empty() )
7816 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7817 if ( !toSmooth ) continue;
7819 for ( size_t i = 0; i < eos._edges.size(); ++i )
7821 _LayerEdge* edge = eos._edges[i];
7822 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7824 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7827 const gp_XYZ& pPrev = edge->PrevPos();
7828 const gp_XYZ& pLast = edge->_pos.back();
7829 gp_XYZ stepVec = pLast - pPrev;
7830 double realStepSize = stepVec.Modulus();
7831 if ( realStepSize < numeric_limits<double>::min() )
7834 edge->_lenFactor = realStepSize / stepSize;
7835 edge->_normal = stepVec / realStepSize;
7836 edge->Set( _LayerEdge::NORMAL_UPDATED );
7843 //================================================================================
7845 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7847 //================================================================================
7849 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7851 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7853 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7854 if ( eov._eosC1.empty() ||
7855 eov.ShapeType() != TopAbs_VERTEX ||
7856 eov._edges.empty() )
7859 gp_XYZ newNorm = eov._edges[0]->_normal;
7860 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7861 bool normChanged = false;
7863 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7865 _EdgesOnShape* eoe = eov._eosC1[i];
7866 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7867 const double eLen = SMESH_Algo::EdgeLength( e );
7868 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7869 if ( oppV.IsSame( eov._shape ))
7870 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7871 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7872 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7873 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7875 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7876 if ( curThickOpp + curThick < eLen )
7879 double wgt = 2. * curThick / eLen;
7880 newNorm += wgt * eovOpp->_edges[0]->_normal;
7885 eov._edges[0]->SetNormal( newNorm.Normalized() );
7886 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7891 //================================================================================
7893 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7895 //================================================================================
7897 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7898 SMESH_MesherHelper& helper,
7901 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7904 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7905 for ( ; id2face != data._convexFaces.end(); ++id2face )
7907 _ConvexFace & convFace = (*id2face).second;
7908 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7910 if ( convFace._normalsFixed )
7911 continue; // already fixed
7912 if ( convFace.CheckPrisms() )
7913 continue; // nothing to fix
7915 convFace._normalsFixed = true;
7917 BRepAdaptor_Surface surface ( convFace._face, false );
7918 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7920 // check if the convex FACE is of spherical shape
7922 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7926 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7927 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7929 _EdgesOnShape& eos = *(id2eos->second);
7930 if ( eos.ShapeType() == TopAbs_VERTEX )
7932 _LayerEdge* ledge = eos._edges[ 0 ];
7933 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7934 centersBox.Add( center );
7936 for ( size_t i = 0; i < eos._edges.size(); ++i )
7937 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7939 if ( centersBox.IsVoid() )
7941 debugMsg( "Error: centersBox.IsVoid()" );
7944 const bool isSpherical =
7945 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7947 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7948 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7952 // set _LayerEdge::_normal as average of all normals
7954 // WARNING: different density of nodes on EDGEs is not taken into account that
7955 // can lead to an improper new normal
7957 gp_XYZ avgNormal( 0,0,0 );
7959 id2eos = convFace._subIdToEOS.begin();
7960 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7962 _EdgesOnShape& eos = *(id2eos->second);
7963 // set data of _CentralCurveOnEdge
7964 if ( eos.ShapeType() == TopAbs_EDGE )
7966 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7967 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7968 if ( !eos._sWOL.IsNull() )
7969 ceCurve._adjFace.Nullify();
7971 ceCurve._ledges.insert( ceCurve._ledges.end(),
7972 eos._edges.begin(), eos._edges.end());
7974 // summarize normals
7975 for ( size_t i = 0; i < eos._edges.size(); ++i )
7976 avgNormal += eos._edges[ i ]->_normal;
7978 double normSize = avgNormal.SquareModulus();
7979 if ( normSize < 1e-200 )
7981 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7984 avgNormal /= Sqrt( normSize );
7986 // compute new _LayerEdge::_cosin on EDGEs
7987 double avgCosin = 0;
7990 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7992 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7993 if ( ceCurve._adjFace.IsNull() )
7995 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7997 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7998 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
8001 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
8002 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
8003 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
8009 avgCosin /= nbCosin;
8011 // set _LayerEdge::_normal = avgNormal
8012 id2eos = convFace._subIdToEOS.begin();
8013 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8015 _EdgesOnShape& eos = *(id2eos->second);
8016 if ( eos.ShapeType() != TopAbs_EDGE )
8017 for ( size_t i = 0; i < eos._edges.size(); ++i )
8018 eos._edges[ i ]->_cosin = avgCosin;
8020 for ( size_t i = 0; i < eos._edges.size(); ++i )
8022 eos._edges[ i ]->SetNormal( avgNormal );
8023 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
8027 else // if ( isSpherical )
8029 // We suppose that centers of curvature at all points of the FACE
8030 // lie on some curve, let's call it "central curve". For all _LayerEdge's
8031 // having a common center of curvature we define the same new normal
8032 // as a sum of normals of _LayerEdge's on EDGEs among them.
8034 // get all centers of curvature for each EDGE
8036 helper.SetSubShape( convFace._face );
8037 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
8039 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
8040 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
8042 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
8044 // set adjacent FACE
8045 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
8047 // get _LayerEdge's of the EDGE
8048 TGeomID edgeID = meshDS->ShapeToIndex( edge );
8049 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
8050 if ( !eos || eos->_edges.empty() )
8052 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
8053 for ( int iV = 0; iV < 2; ++iV )
8055 TopoDS_Vertex v = helper.IthVertex( iV, edge );
8056 TGeomID vID = meshDS->ShapeToIndex( v );
8057 eos = data.GetShapeEdges( vID );
8058 vertexLEdges[ iV ] = eos->_edges[ 0 ];
8060 edgeLEdge = &vertexLEdges[0];
8061 edgeLEdgeEnd = edgeLEdge + 2;
8063 centerCurves[ iE ]._adjFace.Nullify();
8067 if ( ! eos->_toSmooth )
8068 data.SortOnEdge( edge, eos->_edges );
8069 edgeLEdge = &eos->_edges[ 0 ];
8070 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
8071 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
8072 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
8074 if ( ! eos->_sWOL.IsNull() )
8075 centerCurves[ iE ]._adjFace.Nullify();
8078 // Get curvature centers
8082 if ( edgeLEdge[0]->IsOnEdge() &&
8083 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
8085 centerCurves[ iE ].Append( center, vertexLEdges[0] );
8086 centersBox.Add( center );
8088 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
8089 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
8090 { // EDGE or VERTEXes
8091 centerCurves[ iE ].Append( center, *edgeLEdge );
8092 centersBox.Add( center );
8094 if ( edgeLEdge[-1]->IsOnEdge() &&
8095 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
8097 centerCurves[ iE ].Append( center, vertexLEdges[1] );
8098 centersBox.Add( center );
8100 centerCurves[ iE ]._isDegenerated =
8101 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
8103 } // loop on EDGES of convFace._face to set up data of centerCurves
8105 // Compute new normals for _LayerEdge's on EDGEs
8107 double avgCosin = 0;
8110 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
8112 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
8113 if ( ceCurve._isDegenerated )
8115 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
8116 vector< gp_XYZ > & newNormals = ceCurve._normals;
8117 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
8120 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
8123 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
8125 if ( isOK && !ceCurve._adjFace.IsNull() )
8127 // compute new _LayerEdge::_cosin
8128 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
8129 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
8132 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
8133 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
8134 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
8140 // set new normals to _LayerEdge's of NOT degenerated central curves
8141 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8143 if ( centerCurves[ iE ]._isDegenerated )
8145 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8147 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
8148 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8151 // set new normals to _LayerEdge's of degenerated central curves
8152 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8154 if ( !centerCurves[ iE ]._isDegenerated ||
8155 centerCurves[ iE ]._ledges.size() < 3 )
8157 // new normal is an average of new normals at VERTEXes that
8158 // was computed on non-degenerated _CentralCurveOnEdge's
8159 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
8160 centerCurves[ iE ]._ledges.back ()->_normal );
8161 double sz = newNorm.Modulus();
8165 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
8166 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
8167 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
8169 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
8170 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
8171 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8175 // Find new normals for _LayerEdge's based on FACE
8178 avgCosin /= nbCosin;
8179 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
8180 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
8181 if ( id2eos != convFace._subIdToEOS.end() )
8185 _EdgesOnShape& eos = * ( id2eos->second );
8186 for ( size_t i = 0; i < eos._edges.size(); ++i )
8188 _LayerEdge* ledge = eos._edges[ i ];
8189 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
8191 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
8193 iE = iE % centerCurves.size();
8194 if ( centerCurves[ iE ]._isDegenerated )
8196 newNorm.SetCoord( 0,0,0 );
8197 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
8199 ledge->SetNormal( newNorm );
8200 ledge->_cosin = avgCosin;
8201 ledge->Set( _LayerEdge::NORMAL_UPDATED );
8208 } // not a quasi-spherical FACE
8210 // Update _LayerEdge's data according to a new normal
8212 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
8213 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
8215 id2eos = convFace._subIdToEOS.begin();
8216 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8218 _EdgesOnShape& eos = * ( id2eos->second );
8219 for ( size_t i = 0; i < eos._edges.size(); ++i )
8221 _LayerEdge* & ledge = eos._edges[ i ];
8222 double len = ledge->_len;
8223 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
8224 ledge->SetCosin( ledge->_cosin );
8225 ledge->SetNewLength( len, eos, helper );
8227 if ( eos.ShapeType() != TopAbs_FACE )
8228 for ( size_t i = 0; i < eos._edges.size(); ++i )
8230 _LayerEdge* ledge = eos._edges[ i ];
8231 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
8233 _LayerEdge* neibor = ledge->_neibors[iN];
8234 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
8236 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
8237 neibor->Set( _LayerEdge::MOVED );
8238 neibor->SetSmooLen( neibor->_len );
8242 } // loop on sub-shapes of convFace._face
8244 // Find FACEs adjacent to convFace._face that got necessity to smooth
8245 // as a result of normals modification
8247 set< _EdgesOnShape* > adjFacesToSmooth;
8248 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8250 if ( centerCurves[ iE ]._adjFace.IsNull() ||
8251 centerCurves[ iE ]._adjFaceToSmooth )
8253 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8255 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
8257 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
8262 data.AddShapesToSmooth( adjFacesToSmooth );
8267 } // loop on data._convexFaces
8272 //================================================================================
8274 * \brief Return max curvature of a FACE
8276 //================================================================================
8278 double _ConvexFace::GetMaxCurvature( _SolidData& data,
8280 BRepLProp_SLProps& surfProp,
8281 SMESH_MesherHelper& helper)
8283 double maxCurvature = 0;
8285 TopoDS_Face F = TopoDS::Face( eof._shape );
8287 const int nbTestPnt = 5;
8288 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8289 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
8290 while ( smIt->more() )
8292 SMESH_subMesh* sm = smIt->next();
8293 const TGeomID subID = sm->GetId();
8295 // find _LayerEdge's of a sub-shape
8297 if (( eos = data.GetShapeEdges( subID )))
8298 this->_subIdToEOS.insert( make_pair( subID, eos ));
8302 // check concavity and curvature and limit data._stepSize
8303 const double minCurvature =
8304 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
8305 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
8306 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
8308 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
8309 surfProp.SetParameters( uv.X(), uv.Y() );
8310 if ( surfProp.IsCurvatureDefined() )
8312 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
8313 surfProp.MinCurvature() * oriFactor );
8314 maxCurvature = Max( maxCurvature, curvature );
8316 if ( curvature > minCurvature )
8317 this->_isTooCurved = true;
8320 } // loop on sub-shapes of the FACE
8322 return maxCurvature;
8325 //================================================================================
8327 * \brief Finds a center of curvature of a surface at a _LayerEdge
8329 //================================================================================
8331 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
8332 BRepLProp_SLProps& surfProp,
8333 SMESH_MesherHelper& helper,
8334 gp_Pnt & center ) const
8336 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
8337 surfProp.SetParameters( uv.X(), uv.Y() );
8338 if ( !surfProp.IsCurvatureDefined() )
8341 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8342 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
8343 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
8344 if ( surfCurvatureMin > surfCurvatureMax )
8345 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
8347 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
8352 //================================================================================
8354 * \brief Check that prisms are not distorted
8356 //================================================================================
8358 bool _ConvexFace::CheckPrisms() const
8361 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8363 const _LayerEdge* edge = _simplexTestEdges[i];
8364 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8365 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8366 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8368 debugMsg( "Bad simplex of _simplexTestEdges ("
8369 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8370 << " "<< edge->_simplices[j]._nPrev->GetID()
8371 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8378 //================================================================================
8380 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8381 * stored in this _CentralCurveOnEdge.
8382 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8383 * \param [in,out] newNormal - current normal at this point, to be redefined
8384 * \return bool - true if succeeded.
8386 //================================================================================
8388 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8390 if ( this->_isDegenerated )
8393 // find two centers the given one lies between
8395 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
8397 double sl2 = 1.001 * _segLength2[ i ];
8399 double d1 = center.SquareDistance( _curvaCenters[ i ]);
8403 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8404 if ( d2 > sl2 || d2 + d1 < 1e-100 )
8409 double r = d1 / ( d1 + d2 );
8410 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
8411 ( r ) * _ledges[ i+1 ]->_normal );
8415 double sz = newNormal.Modulus();
8424 //================================================================================
8426 * \brief Set shape members
8428 //================================================================================
8430 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
8431 const _ConvexFace& convFace,
8433 SMESH_MesherHelper& helper)
8437 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8438 while ( const TopoDS_Shape* F = fIt->next())
8439 if ( !convFace._face.IsSame( *F ))
8441 _adjFace = TopoDS::Face( *F );
8442 _adjFaceToSmooth = false;
8443 // _adjFace already in a smoothing queue ?
8444 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8445 _adjFaceToSmooth = eos->_toSmooth;
8450 //================================================================================
8452 * \brief Looks for intersection of it's last segment with faces
8453 * \param distance - returns shortest distance from the last node to intersection
8455 //================================================================================
8457 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
8459 const double& epsilon,
8461 const SMDS_MeshElement** intFace)
8463 vector< const SMDS_MeshElement* > suspectFaces;
8465 gp_Ax1 lastSegment = LastSegment( segLen, eos );
8466 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8468 bool segmentIntersected = false;
8469 distance = Precision::Infinite();
8470 int iFace = -1; // intersected face
8471 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8473 const SMDS_MeshElement* face = suspectFaces[j];
8474 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8475 face->GetNodeIndex( _nodes[0] ) >= 0 )
8476 continue; // face sharing _LayerEdge node
8477 const int nbNodes = face->NbCornerNodes();
8478 bool intFound = false;
8480 SMDS_MeshElement::iterator nIt = face->begin_nodes();
8483 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8487 const SMDS_MeshNode* tria[3];
8490 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8493 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8499 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8500 segmentIntersected = true;
8501 if ( distance > dist )
8502 distance = dist, iFace = j;
8505 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8509 if ( segmentIntersected )
8512 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8513 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8514 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8515 << ", intersection with face ("
8516 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8517 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8518 << ") distance = " << distance << endl;
8522 return segmentIntersected;
8525 //================================================================================
8527 * \brief Returns a point used to check orientation of _simplices
8529 //================================================================================
8531 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8533 size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8535 if ( !eos || eos->_sWOL.IsNull() )
8538 if ( eos->SWOLType() == TopAbs_EDGE )
8540 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8542 //else // TopAbs_FACE
8544 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8547 //================================================================================
8549 * \brief Returns size and direction of the last segment
8551 //================================================================================
8553 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8555 // find two non-coincident positions
8556 gp_XYZ orig = _pos.back();
8558 int iPrev = _pos.size() - 2;
8559 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8560 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8561 while ( iPrev >= 0 )
8563 vec = orig - _pos[iPrev];
8564 if ( vec.SquareModulus() > tol*tol )
8574 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8575 segDir.SetDirection( _normal );
8580 gp_Pnt pPrev = _pos[ iPrev ];
8581 if ( !eos._sWOL.IsNull() )
8583 TopLoc_Location loc;
8584 if ( eos.SWOLType() == TopAbs_EDGE )
8587 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8588 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8592 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8593 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8595 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8597 segDir.SetLocation( pPrev );
8598 segDir.SetDirection( vec );
8599 segLen = vec.Modulus();
8605 //================================================================================
8607 * \brief Return the last (or \a which) position of the target node on a FACE.
8608 * \param [in] F - the FACE this _LayerEdge is inflated along
8609 * \param [in] which - index of position
8610 * \return gp_XY - result UV
8612 //================================================================================
8614 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8616 if ( F.IsSame( eos._sWOL )) // F is my FACE
8617 return gp_XY( _pos.back().X(), _pos.back().Y() );
8619 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8620 return gp_XY( 1e100, 1e100 );
8622 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8623 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8624 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8625 if ( !C2d.IsNull() && f <= u && u <= l )
8626 return C2d->Value( u ).XY();
8628 return gp_XY( 1e100, 1e100 );
8631 //================================================================================
8633 * \brief Test intersection of the last segment with a given triangle
8634 * using Moller-Trumbore algorithm
8635 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8637 //================================================================================
8639 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8640 const gp_XYZ& vert0,
8641 const gp_XYZ& vert1,
8642 const gp_XYZ& vert2,
8644 const double& EPSILON) const
8646 const gp_Pnt& orig = lastSegment.Location();
8647 const gp_Dir& dir = lastSegment.Direction();
8649 /* calculate distance from vert0 to ray origin */
8650 //gp_XYZ tvec = orig.XYZ() - vert0;
8652 //if ( tvec * dir > EPSILON )
8653 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8656 gp_XYZ edge1 = vert1 - vert0;
8657 gp_XYZ edge2 = vert2 - vert0;
8659 /* begin calculating determinant - also used to calculate U parameter */
8660 gp_XYZ pvec = dir.XYZ() ^ edge2;
8662 /* if determinant is near zero, ray lies in plane of triangle */
8663 double det = edge1 * pvec;
8665 const double ANGL_EPSILON = 1e-12;
8666 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8669 /* calculate distance from vert0 to ray origin */
8670 gp_XYZ tvec = orig.XYZ() - vert0;
8672 /* calculate U parameter and test bounds */
8673 double u = ( tvec * pvec ) / det;
8674 //if (u < 0.0 || u > 1.0)
8675 if ( u < -EPSILON || u > 1.0 + EPSILON )
8678 /* prepare to test V parameter */
8679 gp_XYZ qvec = tvec ^ edge1;
8681 /* calculate V parameter and test bounds */
8682 double v = (dir.XYZ() * qvec) / det;
8683 //if ( v < 0.0 || u + v > 1.0 )
8684 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8687 /* calculate t, ray intersects triangle */
8688 t = (edge2 * qvec) / det;
8694 //================================================================================
8696 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8697 * neighbor _LayerEdge's by it's own inflation vector.
8698 * \param [in] eov - EOS of the VERTEX
8699 * \param [in] eos - EOS of the FACE
8700 * \param [in] step - inflation step
8701 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8703 //================================================================================
8705 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8706 const _EdgesOnShape* eos,
8708 vector< _LayerEdge* > & badSmooEdges )
8710 // check if any of _neibors is in badSmooEdges
8711 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8712 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8715 // get all edges to move
8717 set< _LayerEdge* > edges;
8719 // find a distance between _LayerEdge on VERTEX and its neighbors
8720 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8722 for ( size_t i = 0; i < _neibors.size(); ++i )
8724 _LayerEdge* nEdge = _neibors[i];
8725 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8727 edges.insert( nEdge );
8728 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8731 // add _LayerEdge's close to curPosV
8735 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8737 _LayerEdge* edgeF = *e;
8738 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8740 _LayerEdge* nEdge = edgeF->_neibors[i];
8741 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8742 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8743 edges.insert( nEdge );
8747 while ( nbE < edges.size() );
8749 // move the target node of the got edges
8751 gp_XYZ prevPosV = PrevPos();
8752 if ( eov->SWOLType() == TopAbs_EDGE )
8754 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8755 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8757 else if ( eov->SWOLType() == TopAbs_FACE )
8759 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8760 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8763 SMDS_FacePositionPtr fPos;
8764 //double r = 1. - Min( 0.9, step / 10. );
8765 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8767 _LayerEdge* edgeF = *e;
8768 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8769 const gp_XYZ newPosF = curPosV + prevVF;
8770 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8771 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8772 edgeF->_pos.back() = newPosF;
8773 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8775 // set _curvature to make edgeF updated by putOnOffsetSurface()
8776 if ( !edgeF->_curvature )
8777 if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8779 edgeF->_curvature = _Factory::NewCurvature();
8780 edgeF->_curvature->_r = 0;
8781 edgeF->_curvature->_k = 0;
8782 edgeF->_curvature->_h2lenRatio = 0;
8783 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8786 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8787 // SMESH_TNodeXYZ( _nodes[0] ));
8788 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8790 // _LayerEdge* edgeF = *e;
8791 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8792 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8793 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8794 // edgeF->_pos.back() = newPosF;
8795 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8798 // smooth _LayerEdge's around moved nodes
8799 //size_t nbBadBefore = badSmooEdges.size();
8800 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8802 _LayerEdge* edgeF = *e;
8803 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8804 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8805 //&& !edges.count( edgeF->_neibors[j] ))
8807 _LayerEdge* edgeFN = edgeF->_neibors[j];
8808 edgeFN->Unset( SMOOTHED );
8809 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8812 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8813 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8814 // int nbBadAfter = edgeFN->_simplices.size();
8816 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8818 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8820 // if ( nbBadAfter <= nbBad )
8822 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8823 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8824 // edgeF->_pos.back() = newPosF;
8825 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8826 // nbBad = nbBadAfter;
8830 badSmooEdges.push_back( edgeFN );
8833 // move a bit not smoothed around moved nodes
8834 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8836 // _LayerEdge* edgeF = badSmooEdges[i];
8837 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8838 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8839 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8840 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8841 // edgeF->_pos.back() = newPosF;
8842 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8846 //================================================================================
8848 * \brief Perform smooth of _LayerEdge's based on EDGE's
8849 * \retval bool - true if node has been moved
8851 //================================================================================
8853 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8854 const TopoDS_Face& F,
8855 SMESH_MesherHelper& helper)
8857 ASSERT( IsOnEdge() );
8859 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8860 SMESH_TNodeXYZ oldPos( tgtNode );
8861 double dist01, distNewOld;
8863 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8864 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8865 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8867 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8868 double lenDelta = 0;
8871 //lenDelta = _curvature->lenDelta( _len );
8872 lenDelta = _curvature->lenDeltaByDist( dist01 );
8873 newPos.ChangeCoord() += _normal * lenDelta;
8876 distNewOld = newPos.Distance( oldPos );
8880 if ( _2neibors->_plnNorm )
8882 // put newPos on the plane defined by source node and _plnNorm
8883 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8884 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8885 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8887 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8888 _pos.back() = newPos.XYZ();
8892 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8893 gp_XY uv( Precision::Infinite(), 0 );
8894 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8895 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8897 newPos = surface->Value( uv );
8898 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8901 // commented for IPAL0052478
8902 // if ( _curvature && lenDelta < 0 )
8904 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8905 // _len -= prevPos.Distance( oldPos );
8906 // _len += prevPos.Distance( newPos );
8908 bool moved = distNewOld > dist01/50;
8910 dumpMove( tgtNode ); // debug
8915 //================================================================================
8917 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8919 //================================================================================
8921 void _LayerEdge::SmoothWoCheck()
8923 if ( Is( DIFFICULT ))
8926 bool moved = Is( SMOOTHED );
8927 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8928 moved = _neibors[i]->Is( SMOOTHED );
8932 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8934 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8935 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8936 _pos.back() = newPos;
8938 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8941 //================================================================================
8943 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8945 //================================================================================
8947 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8949 if ( ! Is( NEAR_BOUNDARY ))
8954 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8956 _LayerEdge* eN = _neibors[iN];
8957 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8960 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8961 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8962 eN->_pos.size() != _pos.size() );
8964 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8965 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8966 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8967 if ( eN->_nodes.size() > 1 &&
8968 eN->_simplices[i].Includes( _nodes.back() ) &&
8969 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8974 badNeibors->push_back( eN );
8975 debugMsg("Bad boundary simplex ( "
8976 << " "<< eN->_nodes[0]->GetID()
8977 << " "<< eN->_nodes.back()->GetID()
8978 << " "<< eN->_simplices[i]._nPrev->GetID()
8979 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8990 //================================================================================
8992 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8993 * \retval int - nb of bad simplices around this _LayerEdge
8995 //================================================================================
8997 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8999 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
9000 return 0; // shape of simplices not changed
9001 if ( _simplices.size() < 2 )
9002 return 0; // _LayerEdge inflated along EDGE or FACE
9004 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
9007 const gp_XYZ& curPos = _pos.back();
9008 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
9010 // quality metrics (orientation) of tetras around _tgtNode
9012 double vol, minVolBefore = 1e100;
9013 for ( size_t i = 0; i < _simplices.size(); ++i )
9015 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9016 minVolBefore = Min( minVolBefore, vol );
9018 int nbBad = _simplices.size() - nbOkBefore;
9020 bool bndNeedSmooth = false;
9022 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
9026 // evaluate min angle
9027 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
9029 size_t nbGoodAngles = _simplices.size();
9031 for ( size_t i = 0; i < _simplices.size(); ++i )
9033 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
9036 if ( nbGoodAngles == _simplices.size() )
9042 if ( Is( ON_CONCAVE_FACE ))
9045 if ( step % 2 == 0 )
9048 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9050 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
9051 _smooFunction = _funs[ FUN_CENTROIDAL ];
9053 _smooFunction = _funs[ FUN_LAPLACIAN ];
9056 // compute new position for the last _pos using different _funs
9059 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9062 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9063 else if ( _funs[ iFun ] == _smooFunction )
9064 continue; // _smooFunction again
9065 else if ( step > 1 )
9066 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9068 break; // let "easy" functions improve elements around distorted ones
9072 double delta = _curvature->lenDelta( _len );
9074 newPos += _normal * delta;
9077 double segLen = _normal * ( newPos - prevPos );
9078 if ( segLen + delta > 0 )
9079 newPos += _normal * delta;
9081 // double segLenChange = _normal * ( curPos - newPos );
9082 // newPos += 0.5 * _normal * segLenChange;
9086 double minVolAfter = 1e100;
9087 for ( size_t i = 0; i < _simplices.size(); ++i )
9089 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9090 minVolAfter = Min( minVolAfter, vol );
9093 if ( nbOkAfter < nbOkBefore )
9097 ( nbOkAfter == nbOkBefore ) &&
9098 ( minVolAfter <= minVolBefore ))
9101 nbBad = _simplices.size() - nbOkAfter;
9102 minVolBefore = minVolAfter;
9103 nbOkBefore = nbOkAfter;
9106 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9107 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9108 _pos.back() = newPos;
9110 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9111 << (nbBad ? " --BAD" : ""));
9115 continue; // look for a better function
9121 } // loop on smoothing functions
9123 if ( moved ) // notify _neibors
9126 for ( size_t i = 0; i < _neibors.size(); ++i )
9127 if ( !_neibors[i]->Is( MOVED ))
9129 _neibors[i]->Set( MOVED );
9130 toSmooth.push_back( _neibors[i] );
9137 //================================================================================
9139 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
9140 * \retval int - nb of bad simplices around this _LayerEdge
9142 //================================================================================
9144 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
9146 if ( !_smooFunction )
9147 return 0; // _LayerEdge inflated along EDGE or FACE
9149 return 0; // not inflated
9151 const gp_XYZ& curPos = _pos.back();
9152 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
9154 // quality metrics (orientation) of tetras around _tgtNode
9156 double vol, minVolBefore = 1e100;
9157 for ( size_t i = 0; i < _simplices.size(); ++i )
9159 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9160 minVolBefore = Min( minVolBefore, vol );
9162 int nbBad = _simplices.size() - nbOkBefore;
9164 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9166 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
9167 _smooFunction = _funs[ FUN_LAPLACIAN ];
9168 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
9169 _smooFunction = _funs[ FUN_CENTROIDAL ];
9172 // compute new position for the last _pos using different _funs
9174 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9177 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9178 else if ( _funs[ iFun ] == _smooFunction )
9179 continue; // _smooFunction again
9180 else if ( step > 1 )
9181 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9183 break; // let "easy" functions improve elements around distorted ones
9187 double delta = _curvature->lenDelta( _len );
9189 newPos += _normal * delta;
9192 double segLen = _normal * ( newPos - prevPos );
9193 if ( segLen + delta > 0 )
9194 newPos += _normal * delta;
9196 // double segLenChange = _normal * ( curPos - newPos );
9197 // newPos += 0.5 * _normal * segLenChange;
9201 double minVolAfter = 1e100;
9202 for ( size_t i = 0; i < _simplices.size(); ++i )
9204 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9205 minVolAfter = Min( minVolAfter, vol );
9208 if ( nbOkAfter < nbOkBefore )
9210 if (( isConcaveFace || findBest ) &&
9211 ( nbOkAfter == nbOkBefore ) &&
9212 ( minVolAfter <= minVolBefore )
9216 nbBad = _simplices.size() - nbOkAfter;
9217 minVolBefore = minVolAfter;
9218 nbOkBefore = nbOkAfter;
9220 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9221 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9222 _pos.back() = newPos;
9224 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9225 << ( nbBad ? "--BAD" : ""));
9227 // commented for IPAL0052478
9228 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
9229 // _len += prevPos.Distance(newPos);
9231 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
9233 //_smooFunction = _funs[ iFun ];
9234 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
9235 // << "\t nbBad: " << _simplices.size() - nbOkAfter
9236 // << " minVol: " << minVolAfter
9237 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
9239 continue; // look for a better function
9245 } // loop on smoothing functions
9250 //================================================================================
9252 * \brief Chooses a smoothing technique giving a position most close to an initial one.
9253 * For a correct result, _simplices must contain nodes lying on geometry.
9255 //================================================================================
9257 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
9258 const TNode2Edge& /*n2eMap*/)
9260 if ( _smooFunction ) return;
9262 // use smoothNefPolygon() near concaveVertices
9263 if ( !concaveVertices.empty() )
9265 _smooFunction = _funs[ FUN_CENTROIDAL ];
9267 Set( ON_CONCAVE_FACE );
9269 for ( size_t i = 0; i < _simplices.size(); ++i )
9271 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
9273 _smooFunction = _funs[ FUN_NEFPOLY ];
9275 // set FUN_CENTROIDAL to neighbor edges
9276 for ( i = 0; i < _neibors.size(); ++i )
9278 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
9280 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
9287 // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
9288 // // where the nodes are smoothed too far along a sphere thus creating
9289 // // inverted _simplices
9290 // double dist[theNbSmooFuns];
9291 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
9292 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
9294 // double minDist = Precision::Infinite();
9295 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
9296 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
9298 // gp_Pnt newP = (this->*_funs[i])();
9299 // dist[i] = p.SquareDistance( newP );
9300 // if ( dist[i]*coef[i] < minDist )
9302 // _smooFunction = _funs[i];
9303 // minDist = dist[i]*coef[i];
9309 _smooFunction = _funs[ FUN_LAPLACIAN ];
9312 // for ( size_t i = 0; i < _simplices.size(); ++i )
9313 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
9314 // if ( minDim == 0 )
9315 // _smooFunction = _funs[ FUN_CENTROIDAL ];
9316 // else if ( minDim == 1 )
9317 // _smooFunction = _funs[ FUN_CENTROIDAL ];
9321 // for ( int i = 0; i < FUN_NB; ++i )
9323 // //cout << dist[i] << " ";
9324 // if ( _smooFunction == _funs[i] ) {
9326 // //debugMsg( fNames[i] );
9330 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
9333 //================================================================================
9335 * \brief Returns a name of _SmooFunction
9337 //================================================================================
9339 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
9342 fun = _smooFunction;
9343 for ( int i = 0; i < theNbSmooFuns; ++i )
9344 if ( fun == _funs[i] )
9347 return theNbSmooFuns;
9350 //================================================================================
9352 * \brief Computes a new node position using Laplacian smoothing
9354 //================================================================================
9356 gp_XYZ _LayerEdge::smoothLaplacian()
9358 gp_XYZ newPos (0,0,0);
9359 for ( size_t i = 0; i < _simplices.size(); ++i )
9360 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9361 newPos /= _simplices.size();
9366 //================================================================================
9368 * \brief Computes a new node position using angular-based smoothing
9370 //================================================================================
9372 gp_XYZ _LayerEdge::smoothAngular()
9374 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
9375 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
9376 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
9378 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9380 for ( size_t i = 0; i < _simplices.size(); ++i )
9382 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9383 edgeDir.push_back( p - pPrev );
9384 edgeSize.push_back( edgeDir.back().Magnitude() );
9385 if ( edgeSize.back() < numeric_limits<double>::min() )
9388 edgeSize.pop_back();
9392 edgeDir.back() /= edgeSize.back();
9393 points.push_back( p );
9398 edgeDir.push_back ( edgeDir[0] );
9399 edgeSize.push_back( edgeSize[0] );
9400 pN /= points.size();
9402 gp_XYZ newPos(0,0,0);
9404 for ( size_t i = 0; i < points.size(); ++i )
9406 gp_Vec toN = pN - points[i];
9407 double toNLen = toN.Magnitude();
9408 if ( toNLen < numeric_limits<double>::min() )
9413 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
9414 double bisecLen = bisec.SquareMagnitude();
9415 if ( bisecLen < numeric_limits<double>::min() )
9417 gp_Vec norm = edgeDir[i] ^ toN;
9418 bisec = norm ^ edgeDir[i];
9419 bisecLen = bisec.SquareMagnitude();
9421 bisecLen = Sqrt( bisecLen );
9425 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9426 sumSize += bisecLen;
9428 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9429 sumSize += ( edgeSize[i] + edgeSize[i+1] );
9435 // project newPos to an average plane
9437 gp_XYZ norm(0,0,0); // plane normal
9438 points.push_back( points[0] );
9439 for ( size_t i = 1; i < points.size(); ++i )
9441 gp_XYZ vec1 = points[ i-1 ] - pN;
9442 gp_XYZ vec2 = points[ i ] - pN;
9443 gp_XYZ cross = vec1 ^ vec2;
9446 if ( cross * norm < numeric_limits<double>::min() )
9447 norm += cross.Reversed();
9451 catch (Standard_Failure&) { // if |cross| == 0.
9454 gp_XYZ vec = newPos - pN;
9455 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
9456 newPos = newPos - r * norm;
9461 //================================================================================
9463 * \brief Computes a new node position using weighted node positions
9465 //================================================================================
9467 gp_XYZ _LayerEdge::smoothLengthWeighted()
9469 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9470 vector< gp_XYZ > points; points. reserve( _simplices.size() );
9472 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9473 for ( size_t i = 0; i < _simplices.size(); ++i )
9475 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9476 edgeSize.push_back( ( p - pPrev ).Modulus() );
9477 if ( edgeSize.back() < numeric_limits<double>::min() )
9479 edgeSize.pop_back();
9483 points.push_back( p );
9487 edgeSize.push_back( edgeSize[0] );
9489 gp_XYZ newPos(0,0,0);
9491 for ( size_t i = 0; i < points.size(); ++i )
9493 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9494 sumSize += edgeSize[i] + edgeSize[i+1];
9500 //================================================================================
9502 * \brief Computes a new node position using angular-based smoothing
9504 //================================================================================
9506 gp_XYZ _LayerEdge::smoothCentroidal()
9508 gp_XYZ newPos(0,0,0);
9509 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9511 for ( size_t i = 0; i < _simplices.size(); ++i )
9513 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9514 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9515 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9516 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9519 newPos += gc * size;
9526 //================================================================================
9528 * \brief Computes a new node position located inside a Nef polygon
9530 //================================================================================
9532 gp_XYZ _LayerEdge::smoothNefPolygon()
9533 #ifdef OLD_NEF_POLYGON
9535 gp_XYZ newPos(0,0,0);
9537 // get a plane to search a solution on
9539 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9541 const double tol = numeric_limits<double>::min();
9542 gp_XYZ center(0,0,0);
9543 for ( i = 0; i < _simplices.size(); ++i )
9545 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9546 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9547 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9549 vecs.back() = vecs[0];
9550 center /= _simplices.size();
9552 gp_XYZ zAxis(0,0,0);
9553 for ( i = 0; i < _simplices.size(); ++i )
9554 zAxis += vecs[i] ^ vecs[i+1];
9557 for ( i = 0; i < _simplices.size(); ++i )
9560 if ( yAxis.SquareModulus() > tol )
9563 gp_XYZ xAxis = yAxis ^ zAxis;
9564 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9565 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9566 // p0.Distance( _simplices[2]._nPrev ));
9567 // gp_XYZ center = smoothLaplacian();
9568 // gp_XYZ xAxis, yAxis, zAxis;
9569 // for ( i = 0; i < _simplices.size(); ++i )
9571 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9572 // if ( xAxis.SquareModulus() > tol*tol )
9575 // for ( i = 1; i < _simplices.size(); ++i )
9577 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9578 // zAxis = xAxis ^ yAxis;
9579 // if ( zAxis.SquareModulus() > tol*tol )
9582 // if ( i == _simplices.size() ) return newPos;
9584 yAxis = zAxis ^ xAxis;
9585 xAxis /= xAxis.Modulus();
9586 yAxis /= yAxis.Modulus();
9588 // get half-planes of _simplices
9590 vector< _halfPlane > halfPlns( _simplices.size() );
9592 for ( size_t i = 0; i < _simplices.size(); ++i )
9594 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9595 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9596 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9597 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9598 gp_XY vec12 = p2 - p1;
9599 double dist12 = vec12.Modulus();
9603 halfPlns[ nbHP ]._pos = p1;
9604 halfPlns[ nbHP ]._dir = vec12;
9605 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9609 // intersect boundaries of half-planes, define state of intersection points
9610 // in relation to all half-planes and calculate internal point of a 2D polygon
9613 gp_XY newPos2D (0,0);
9615 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9616 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9617 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9619 vector< vector< TIntPntState > > allIntPnts( nbHP );
9620 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9622 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9623 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9625 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9626 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9629 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9631 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9633 if ( iHP1 == iHP2 ) continue;
9635 TIntPntState & ips1 = intPnts1[ iHP2 ];
9636 if ( ips1.second == UNDEF )
9638 // find an intersection point of boundaries of iHP1 and iHP2
9640 if ( iHP2 == iPrev ) // intersection with neighbors is known
9641 ips1.first = halfPlns[ iHP1 ]._pos;
9642 else if ( iHP2 == iNext )
9643 ips1.first = halfPlns[ iHP2 ]._pos;
9644 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9645 ips1.second = NO_INT;
9647 // classify the found intersection point
9648 if ( ips1.second != NO_INT )
9650 ips1.second = NOT_OUT;
9651 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9652 if ( i != iHP1 && i != iHP2 &&
9653 halfPlns[ i ].IsOut( ips1.first, tol ))
9654 ips1.second = IS_OUT;
9656 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9657 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9658 TIntPntState & ips2 = intPnts2[ iHP1 ];
9661 if ( ips1.second == NOT_OUT )
9664 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9668 // find a NOT_OUT segment of boundary which is located between
9669 // two NOT_OUT int points
9672 continue; // no such a segment
9676 // sort points along the boundary
9677 map< double, TIntPntState* > ipsByParam;
9678 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9680 TIntPntState & ips1 = intPnts1[ iHP2 ];
9681 if ( ips1.second != NO_INT )
9683 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9684 double param = op * halfPlns[ iHP1 ]._dir;
9685 ipsByParam.insert( make_pair( param, & ips1 ));
9688 // look for two neighboring NOT_OUT points
9690 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9691 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9693 TIntPntState & ips1 = *(u2ips->second);
9694 if ( ips1.second == NOT_OUT )
9695 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9696 else if ( nbNotOut >= 2 )
9703 if ( nbNotOut >= 2 )
9705 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9708 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9715 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9724 #else // OLD_NEF_POLYGON
9725 { ////////////////////////////////// NEW
9726 gp_XYZ newPos(0,0,0);
9728 // get a plane to search a solution on
9731 gp_XYZ center(0,0,0);
9732 for ( i = 0; i < _simplices.size(); ++i )
9733 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9734 center /= _simplices.size();
9736 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9737 for ( i = 0; i < _simplices.size(); ++i )
9738 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9739 vecs.back() = vecs[0];
9741 const double tol = numeric_limits<double>::min();
9742 gp_XYZ zAxis(0,0,0);
9743 for ( i = 0; i < _simplices.size(); ++i )
9745 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9748 if ( cross * zAxis < tol )
9749 zAxis += cross.Reversed();
9753 catch (Standard_Failure) { // if |cross| == 0.
9758 for ( i = 0; i < _simplices.size(); ++i )
9761 if ( yAxis.SquareModulus() > tol )
9764 gp_XYZ xAxis = yAxis ^ zAxis;
9765 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9766 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9767 // p0.Distance( _simplices[2]._nPrev ));
9768 // gp_XYZ center = smoothLaplacian();
9769 // gp_XYZ xAxis, yAxis, zAxis;
9770 // for ( i = 0; i < _simplices.size(); ++i )
9772 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9773 // if ( xAxis.SquareModulus() > tol*tol )
9776 // for ( i = 1; i < _simplices.size(); ++i )
9778 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9779 // zAxis = xAxis ^ yAxis;
9780 // if ( zAxis.SquareModulus() > tol*tol )
9783 // if ( i == _simplices.size() ) return newPos;
9785 yAxis = zAxis ^ xAxis;
9786 xAxis /= xAxis.Modulus();
9787 yAxis /= yAxis.Modulus();
9789 // get half-planes of _simplices
9791 vector< _halfPlane > halfPlns( _simplices.size() );
9793 for ( size_t i = 0; i < _simplices.size(); ++i )
9795 const gp_XYZ& OP1 = vecs[ i ];
9796 const gp_XYZ& OP2 = vecs[ i+1 ];
9797 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9798 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9799 gp_XY vec12 = p2 - p1;
9800 double dist12 = vec12.Modulus();
9804 halfPlns[ nbHP ]._pos = p1;
9805 halfPlns[ nbHP ]._dir = vec12;
9806 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9810 // intersect boundaries of half-planes, define state of intersection points
9811 // in relation to all half-planes and calculate internal point of a 2D polygon
9814 gp_XY newPos2D (0,0);
9816 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9817 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9818 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9820 vector< vector< TIntPntState > > allIntPnts( nbHP );
9821 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9823 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9824 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9826 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9827 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9830 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9832 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9834 if ( iHP1 == iHP2 ) continue;
9836 TIntPntState & ips1 = intPnts1[ iHP2 ];
9837 if ( ips1.second == UNDEF )
9839 // find an intersection point of boundaries of iHP1 and iHP2
9841 if ( iHP2 == iPrev ) // intersection with neighbors is known
9842 ips1.first = halfPlns[ iHP1 ]._pos;
9843 else if ( iHP2 == iNext )
9844 ips1.first = halfPlns[ iHP2 ]._pos;
9845 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9846 ips1.second = NO_INT;
9848 // classify the found intersection point
9849 if ( ips1.second != NO_INT )
9851 ips1.second = NOT_OUT;
9852 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9853 if ( i != iHP1 && i != iHP2 &&
9854 halfPlns[ i ].IsOut( ips1.first, tol ))
9855 ips1.second = IS_OUT;
9857 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9858 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9859 TIntPntState & ips2 = intPnts2[ iHP1 ];
9862 if ( ips1.second == NOT_OUT )
9865 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9869 // find a NOT_OUT segment of boundary which is located between
9870 // two NOT_OUT int points
9873 continue; // no such a segment
9877 // sort points along the boundary
9878 map< double, TIntPntState* > ipsByParam;
9879 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9881 TIntPntState & ips1 = intPnts1[ iHP2 ];
9882 if ( ips1.second != NO_INT )
9884 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9885 double param = op * halfPlns[ iHP1 ]._dir;
9886 ipsByParam.insert( make_pair( param, & ips1 ));
9889 // look for two neighboring NOT_OUT points
9891 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9892 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9894 TIntPntState & ips1 = *(u2ips->second);
9895 if ( ips1.second == NOT_OUT )
9896 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9897 else if ( nbNotOut >= 2 )
9904 if ( nbNotOut >= 2 )
9906 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9909 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9916 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9925 #endif // OLD_NEF_POLYGON
9927 //================================================================================
9929 * \brief Add a new segment to _LayerEdge during inflation
9931 //================================================================================
9933 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9938 if ( len > _maxLen )
9941 Block( eos.GetData() );
9943 const double lenDelta = len - _len;
9944 // if ( lenDelta < 0 )
9946 if ( lenDelta < len * 1e-3 )
9948 Block( eos.GetData() );
9952 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9953 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9955 if ( eos._hyp.IsOffsetMethod() )
9959 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9960 while ( faceIt->more() )
9962 const SMDS_MeshElement* face = faceIt->next();
9963 if ( !eos.GetNormal( face, faceNorm ))
9966 // translate plane of a face
9967 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9969 // find point of intersection of the face plane located at baryCenter
9970 // and _normal located at newXYZ
9971 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9972 double dot = ( faceNorm.XYZ() * _normal );
9973 if ( dot < std::numeric_limits<double>::min() )
9974 dot = lenDelta * 1e-3;
9975 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9976 newXYZ += step * _normal;
9978 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9982 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9985 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9986 _pos.push_back( newXYZ );
9988 if ( !eos._sWOL.IsNull() )
9989 if ( !UpdatePositionOnSWOL( n, 2*lenDelta, eos, helper ))
9991 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9993 Block( eos.GetData() );
10000 if ( eos.ShapeType() != TopAbs_FACE )
10002 for ( size_t i = 0; i < _neibors.size(); ++i )
10003 //if ( _len > _neibors[i]->GetSmooLen() )
10004 _neibors[i]->Set( MOVED );
10008 dumpMove( n ); //debug
10012 //================================================================================
10014 * \brief Update last position on SWOL by projecting node on SWOL
10016 //================================================================================
10018 bool _LayerEdge::UpdatePositionOnSWOL( SMDS_MeshNode* n,
10020 _EdgesOnShape& eos,
10021 SMESH_MesherHelper& helper )
10025 if ( eos.SWOLType() == TopAbs_EDGE )
10027 double u = Precision::Infinite(); // to force projection w/o distance check
10028 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u, tol, /*force=*/true, distXYZ );
10029 _pos.back().SetCoord( u, 0, 0 );
10030 if ( _nodes.size() > 1 && uvOK )
10032 SMDS_EdgePositionPtr pos = n->GetPosition();
10033 pos->SetUParameter( u );
10036 else // TopAbs_FACE
10038 gp_XY uv( Precision::Infinite(), 0 );
10039 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv, tol, /*force=*/true, distXYZ );
10040 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
10041 if ( _nodes.size() > 1 && uvOK )
10043 SMDS_FacePositionPtr pos = n->GetPosition();
10044 pos->SetUParameter( uv.X() );
10045 pos->SetVParameter( uv.Y() );
10050 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
10055 //================================================================================
10057 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
10059 //================================================================================
10061 void _LayerEdge::Block( _SolidData& data )
10063 //if ( Is( BLOCKED )) return;
10066 SMESH_Comment msg( "#BLOCK shape=");
10067 msg << data.GetShapeEdges( this )->_shapeID
10068 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
10069 dumpCmd( msg + " -- BEGIN");
10072 std::queue<_LayerEdge*> queue;
10073 queue.push( this );
10075 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
10076 while ( !queue.empty() )
10078 _LayerEdge* edge = queue.front(); queue.pop();
10079 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
10080 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
10081 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
10083 _LayerEdge* neibor = edge->_neibors[iN];
10084 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
10086 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
10087 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
10088 double minDist = pSrc.SquareDistance( pSrcN );
10089 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
10090 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
10091 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
10092 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
10093 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
10095 //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
10096 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
10097 // neibor->_lenFactor / edge->_lenFactor );
10099 if ( neibor->_maxLen > newMaxLen )
10101 neibor->SetMaxLen( newMaxLen );
10102 if ( neibor->_maxLen < neibor->_len )
10104 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
10105 int lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
10106 while ( neibor->_len > neibor->_maxLen &&
10107 neibor->NbSteps() > lastStep )
10108 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
10109 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
10110 //neibor->Block( data );
10112 queue.push( neibor );
10116 dumpCmd( msg + " -- END");
10119 //================================================================================
10121 * \brief Remove last inflation step
10123 //================================================================================
10125 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
10127 if ( _pos.size() > curStep && _nodes.size() > 1 )
10129 _pos.resize( curStep );
10131 gp_Pnt nXYZ = _pos.back();
10132 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
10133 SMESH_TNodeXYZ curXYZ( n );
10134 if ( !eos._sWOL.IsNull() )
10136 TopLoc_Location loc;
10137 if ( eos.SWOLType() == TopAbs_EDGE )
10139 SMDS_EdgePositionPtr pos = n->GetPosition();
10140 pos->SetUParameter( nXYZ.X() );
10142 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
10143 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
10147 SMDS_FacePositionPtr pos = n->GetPosition();
10148 pos->SetUParameter( nXYZ.X() );
10149 pos->SetVParameter( nXYZ.Y() );
10150 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
10151 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
10154 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
10157 if ( restoreLength )
10159 if ( NbSteps() == 0 )
10161 else if ( IsOnFace() && Is( MOVED ))
10162 _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
10164 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
10170 //================================================================================
10172 * \brief Return index of a _pos distant from _normal
10174 //================================================================================
10176 int _LayerEdge::GetSmoothedPos( const double tol )
10179 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
10181 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
10182 if ( normDist > tol * tol )
10188 //================================================================================
10190 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
10192 //================================================================================
10194 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
10196 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
10199 // find the 1st smoothed _pos
10200 int iSmoothed = GetSmoothedPos( tol );
10201 if ( !iSmoothed ) return;
10203 gp_XYZ normal = _normal;
10204 if ( Is( NORMAL_UPDATED ))
10207 for ( size_t i = 0; i < _neibors.size(); ++i )
10209 if ( _neibors[i]->IsOnFace() )
10211 double dot = _normal * _neibors[i]->_normal;
10212 if ( dot < minDot )
10214 normal = _neibors[i]->_normal;
10219 if ( minDot == 1. )
10220 for ( size_t i = 1; i < _pos.size(); ++i )
10222 normal = _pos[i] - _pos[0];
10223 double size = normal.Modulus();
10224 if ( size > RealSmall() )
10231 const double r = 0.2;
10232 for ( int iter = 0; iter < 50; ++iter )
10235 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
10237 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
10238 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
10240 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
10241 double newLen = ( 1-r ) * midLen + r * segLen[i];
10242 const_cast< double& >( segLen[i] ) = newLen;
10243 // check angle between normal and (_pos[i+1], _pos[i] )
10244 gp_XYZ posDir = _pos[i+1] - _pos[i];
10245 double size = posDir.SquareModulus();
10246 if ( size > RealSmall() )
10247 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
10249 if ( minDot > 0.5 * 0.5 )
10255 //================================================================================
10257 * \brief Print flags
10259 //================================================================================
10261 std::string _LayerEdge::DumpFlags() const
10263 SMESH_Comment dump;
10264 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
10265 if ( _flags & flag )
10267 EFlags f = (EFlags) flag;
10269 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
10270 case MOVED: dump << "MOVED"; break;
10271 case SMOOTHED: dump << "SMOOTHED"; break;
10272 case DIFFICULT: dump << "DIFFICULT"; break;
10273 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
10274 case BLOCKED: dump << "BLOCKED"; break;
10275 case INTERSECTED: dump << "INTERSECTED"; break;
10276 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
10277 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
10278 case MARKED: dump << "MARKED"; break;
10279 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
10280 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
10281 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
10282 case DISTORTED: dump << "DISTORTED"; break;
10283 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
10284 case SHRUNK: dump << "SHRUNK"; break;
10285 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
10289 cout << dump << endl;
10294 //================================================================================
10296 * \brief Create layers of prisms
10298 //================================================================================
10300 bool _ViscousBuilder::refine(_SolidData& data)
10302 SMESH_MesherHelper& helper = data.GetHelper();
10303 helper.SetElementsOnShape(false);
10305 Handle(Geom_Curve) curve;
10306 Handle(ShapeAnalysis_Surface) surface;
10307 TopoDS_Edge geomEdge;
10308 TopoDS_Face geomFace;
10309 TopLoc_Location loc;
10312 vector< gp_XYZ > pos3D;
10313 bool isOnEdge, isTooConvexFace = false;
10314 TGeomID prevBaseId = -1;
10315 TNode2Edge* n2eMap = 0;
10316 TNode2Edge::iterator n2e;
10318 // Create intermediate nodes on each _LayerEdge
10320 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
10322 _EdgesOnShape& eos = data._edgesOnShape[iS];
10323 if ( eos._edges.empty() ) continue;
10325 if ( eos._edges[0]->_nodes.size() < 2 )
10326 continue; // on _noShrinkShapes
10328 // get data of a shrink shape
10330 geomEdge.Nullify(); geomFace.Nullify();
10331 curve.Nullify(); surface.Nullify();
10332 if ( !eos._sWOL.IsNull() )
10334 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
10337 geomEdge = TopoDS::Edge( eos._sWOL );
10338 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
10342 geomFace = TopoDS::Face( eos._sWOL );
10343 surface = helper.GetSurface( geomFace );
10346 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
10348 geomFace = TopoDS::Face( eos._shape );
10349 surface = helper.GetSurface( geomFace );
10350 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
10351 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
10352 eos._eosC1[ i ]->_toSmooth = true;
10354 isTooConvexFace = false;
10355 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
10356 isTooConvexFace = cf->_isTooCurved;
10359 vector< double > segLen;
10360 for ( size_t i = 0; i < eos._edges.size(); ++i )
10362 _LayerEdge& edge = *eos._edges[i];
10363 if ( edge._pos.size() < 2 )
10366 // get accumulated length of segments
10367 segLen.resize( edge._pos.size() );
10369 if ( eos._sWOL.IsNull() )
10371 bool useNormal = true;
10372 bool usePos = false;
10373 bool smoothed = false;
10374 double preci = 0.1 * edge._len;
10375 if ( eos._toSmooth && edge._pos.size() > 2 )
10377 smoothed = edge.GetSmoothedPos( preci );
10381 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10383 useNormal = usePos = false;
10384 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10385 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10387 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10388 if ( surface->Gap() < 2. * edge._len )
10389 segLen[j] = surface->Gap();
10395 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10397 #ifndef __NODES_AT_POS
10398 useNormal = usePos = false;
10399 edge._pos[1] = edge._pos.back();
10400 edge._pos.resize( 2 );
10401 segLen.resize( 2 );
10402 segLen[ 1 ] = edge._len;
10405 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10407 useNormal = usePos = false;
10408 _LayerEdge tmpEdge; // get original _normal
10409 tmpEdge._nodes.push_back( edge._nodes[0] );
10410 if ( !setEdgeData( tmpEdge, eos, helper, data ))
10413 for ( size_t j = 1; j < edge._pos.size(); ++j )
10414 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10418 for ( size_t j = 1; j < edge._pos.size(); ++j )
10419 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10423 for ( size_t j = 1; j < edge._pos.size(); ++j )
10424 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10428 bool swapped = ( edge._pos.size() > 2 );
10432 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10433 if ( segLen[j] > segLen.back() )
10435 segLen.erase( segLen.begin() + j );
10436 edge._pos.erase( edge._pos.begin() + j );
10439 else if ( segLen[j] < segLen[j-1] )
10441 std::swap( segLen[j], segLen[j-1] );
10442 std::swap( edge._pos[j], edge._pos[j-1] );
10447 // smooth a path formed by edge._pos
10448 #ifndef __NODES_AT_POS
10449 if (( smoothed ) /*&&
10450 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10451 edge.SmoothPos( segLen, preci );
10454 else if ( eos._isRegularSWOL ) // usual SWOL
10456 if ( edge.Is( _LayerEdge::SMOOTHED ))
10458 SMESH_NodeXYZ p0( edge._nodes[0] );
10459 for ( size_t j = 1; j < edge._pos.size(); ++j )
10461 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10462 segLen[j] = ( pj - p0 ) * edge._normal;
10467 for ( size_t j = 1; j < edge._pos.size(); ++j )
10468 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10471 else // SWOL is surface with singularities or irregularly parametrized curve
10473 pos3D.resize( edge._pos.size() );
10475 if ( !surface.IsNull() )
10476 for ( size_t j = 0; j < edge._pos.size(); ++j )
10477 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10478 else if ( !curve.IsNull() )
10479 for ( size_t j = 0; j < edge._pos.size(); ++j )
10480 pos3D[j] = curve->Value( edge._pos[j].X() ).XYZ();
10482 for ( size_t j = 1; j < edge._pos.size(); ++j )
10483 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10486 // allocate memory for new nodes if it is not yet refined
10487 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10488 if ( edge._nodes.size() == 2 )
10490 #ifdef __NODES_AT_POS
10491 int nbNodes = edge._pos.size();
10493 int nbNodes = eos._hyp.GetNumberLayers() + 1;
10495 edge._nodes.resize( nbNodes, 0 );
10496 edge._nodes[1] = 0;
10497 edge._nodes.back() = tgtNode;
10499 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10500 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10501 if ( baseShapeId != prevBaseId )
10503 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10504 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10505 prevBaseId = baseShapeId;
10507 _LayerEdge* edgeOnSameNode = 0;
10508 bool useExistingPos = false;
10509 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10511 edgeOnSameNode = n2e->second;
10512 useExistingPos = ( edgeOnSameNode->_len < edge._len ||
10513 segLen[0] == segLen.back() ); // too short inflation step (bos #20643)
10514 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10515 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
10518 SMDS_EdgePositionPtr epos = lastPos;
10519 epos->SetUParameter( otherTgtPos.X() );
10523 SMDS_FacePositionPtr fpos = lastPos;
10524 fpos->SetUParameter( otherTgtPos.X() );
10525 fpos->SetVParameter( otherTgtPos.Y() );
10529 // create intermediate nodes
10530 const double h0 = eos._hyp.Get1stLayerThickness( segLen.back() );
10531 const double zeroLen = std::numeric_limits<double>::min();
10532 double hSum = 0, hi = h0/eos._hyp.GetStretchFactor();
10534 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10536 // compute an intermediate position
10537 hi *= eos._hyp.GetStretchFactor();
10539 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10541 int iPrevSeg = iSeg-1;
10542 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10544 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10545 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10546 #ifdef __NODES_AT_POS
10547 pos = edge._pos[ iStep ];
10549 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10550 if ( !eos._sWOL.IsNull() )
10552 // compute XYZ by parameters <pos>
10557 pos = curve->Value( u ).Transformed(loc);
10559 else if ( eos._isRegularSWOL )
10561 uv.SetCoord( pos.X(), pos.Y() );
10563 pos = surface->Value( pos.X(), pos.Y() );
10567 uv.SetCoord( pos.X(), pos.Y() );
10568 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10569 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10571 pos = surface->Value( uv );
10574 // create or update the node
10577 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10578 if ( !eos._sWOL.IsNull() )
10581 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10583 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10587 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10592 if ( !eos._sWOL.IsNull() )
10594 // make average pos from new and current parameters
10597 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10598 if ( useExistingPos )
10599 u = helper.GetNodeU( geomEdge, node );
10600 pos = curve->Value( u ).Transformed(loc);
10602 SMDS_EdgePositionPtr epos = node->GetPosition();
10603 epos->SetUParameter( u );
10607 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10608 if ( useExistingPos )
10609 uv = helper.GetNodeUV( geomFace, node );
10610 pos = surface->Value( uv );
10612 SMDS_FacePositionPtr fpos = node->GetPosition();
10613 fpos->SetUParameter( uv.X() );
10614 fpos->SetVParameter( uv.Y() );
10617 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10619 } // loop on edge._nodes
10621 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10624 edge._pos.back().SetCoord( u, 0,0);
10626 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10628 if ( edgeOnSameNode )
10629 edgeOnSameNode->_pos.back() = edge._pos.back();
10632 } // loop on eos._edges to create nodes
10635 if ( !getMeshDS()->IsEmbeddedMode() )
10636 // Log node movement
10637 for ( size_t i = 0; i < eos._edges.size(); ++i )
10639 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10640 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10647 helper.SetElementsOnShape(true);
10649 vector< vector<const SMDS_MeshNode*>* > nnVec;
10650 set< vector<const SMDS_MeshNode*>* > nnSet;
10651 set< int > degenEdgeInd;
10652 vector<const SMDS_MeshElement*> degenVols;
10654 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10655 for ( ; exp.More(); exp.Next() )
10657 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10658 if ( data._ignoreFaceIds.count( faceID ))
10660 _EdgesOnShape* eos = data.GetShapeEdges( faceID );
10661 SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10664 std::vector< const SMDS_MeshElement* > vols;
10665 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10666 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10667 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10668 while ( fIt->more() )
10670 const SMDS_MeshElement* face = fIt->next();
10671 const int nbNodes = face->NbCornerNodes();
10672 nnVec.resize( nbNodes );
10674 degenEdgeInd.clear();
10675 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10676 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10677 for ( int iN = 0; iN < nbNodes; ++iN )
10679 const SMDS_MeshNode* n = nIt->next();
10680 _LayerEdge* edge = data._n2eMap[ n ];
10681 const int i = isReversedFace ? nbNodes-1-iN : iN;
10682 nnVec[ i ] = & edge->_nodes;
10683 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10684 minZ = std::min( minZ, nnVec[ i ]->size() );
10686 if ( helper.HasDegeneratedEdges() )
10687 nnSet.insert( nnVec[ i ]);
10692 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10696 const SMDS_MeshElement* vol;
10703 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10705 vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10706 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10707 vols.push_back( vol );
10710 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10712 for ( int iN = 0; iN < nbNodes; ++iN )
10713 if ( nnVec[ iN ]->size() < iZ+1 )
10714 degenEdgeInd.insert( iN );
10716 if ( degenEdgeInd.size() == 1 ) // PYRAM
10718 int i2 = *degenEdgeInd.begin();
10719 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10720 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10721 vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10722 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10723 vols.push_back( vol );
10727 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10728 vol = helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10729 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10730 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10731 (*nnVec[ i3 ])[ iZ ]);
10732 vols.push_back( vol );
10740 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10742 vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10743 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10744 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10745 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10746 vols.push_back( vol );
10749 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10751 for ( int iN = 0; iN < nbNodes; ++iN )
10752 if ( nnVec[ iN ]->size() < iZ+1 )
10753 degenEdgeInd.insert( iN );
10755 switch ( degenEdgeInd.size() )
10759 int i2 = *degenEdgeInd.begin();
10760 int i3 = *degenEdgeInd.rbegin();
10761 bool ok = ( i3 - i2 == 1 );
10762 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10763 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10764 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10766 vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10767 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10768 vols.push_back( vol );
10770 degenVols.push_back( vol );
10774 default: // degen HEX
10776 vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10777 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10778 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10779 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10780 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10781 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10782 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10783 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10784 vols.push_back( vol );
10785 degenVols.push_back( vol );
10792 return error("Not supported type of element", data._index);
10794 } // switch ( nbNodes )
10797 for ( size_t i = 0; i < vols.size(); ++i )
10798 group->Add( vols[ i ]);
10800 } // while ( fIt->more() )
10803 if ( !degenVols.empty() )
10805 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10806 if ( !err || err->IsOK() )
10808 SMESH_BadInputElements* badElems =
10809 new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10810 badElems->myBadElements.insert( badElems->myBadElements.end(),
10811 degenVols.begin(),degenVols.end() );
10812 err.reset( badElems );
10819 namespace VISCOUS_3D
10822 //--------------------------------------------------------------------------------
10824 * \brief Pair of periodic FACEs
10826 struct PeriodicFaces
10828 typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10830 ShrinkFace* _shriFace[2];
10831 TNodeNodeMap _nnMap;
10834 PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10835 bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10836 bool MoveNodes( const TopoDS_Face& tgtFace );
10837 void Clear() { _nnMap.clear(); }
10838 bool IsEmpty() const { return _nnMap.empty(); }
10841 //--------------------------------------------------------------------------------
10843 * \brief Shrink FACE data used to find periodic FACEs
10847 // ................................................................................
10848 struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10850 bool _isShrink, _isReverse;
10853 std::vector< SMESH_NodeXYZ > _nodes;
10854 TopAbs_ShapeEnum _vertSWOLType[2]; // shrink part includes VERTEXes
10855 AverageHyp* _vertHyp[2];
10856 double _edgeWOLLen[2]; // length of wol EDGE
10857 double _tol; // to compare _edgeWOLLen's
10860 _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10861 _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }, _edgeWOLLen{ 0., 0.}
10864 bool IsEqualLengthEWOL( const BndPart& other ) const
10866 return ( std::abs( _edgeWOLLen[0] - other._edgeWOLLen[0] ) < _tol &&
10867 std::abs( _edgeWOLLen[1] - other._edgeWOLLen[1] ) < _tol );
10870 bool operator==( const BndPart& other ) const
10872 return ( _isShrink == other._isShrink &&
10873 _nbSegments == other._nbSegments &&
10874 _nodes.size() == other._nodes.size() &&
10875 vertSWOLType1() == other.vertSWOLType1() &&
10876 vertSWOLType2() == other.vertSWOLType2() &&
10878 ( *_hyp == *other._hyp &&
10879 vertHyp1() == other.vertHyp1() &&
10880 vertHyp2() == other.vertHyp2() &&
10881 IsEqualLengthEWOL( other )))
10884 bool CanAppend( const BndPart& other )
10886 return ( _isShrink == other._isShrink &&
10888 ( *_hyp == *other._hyp &&
10889 *_hyp == vertHyp2() &&
10890 vertHyp2() == other.vertHyp1() ))
10893 void Append( const BndPart& other )
10895 _nbSegments += other._nbSegments;
10896 bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10897 _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10898 _vertSWOLType[1] = other._vertSWOLType[1];
10900 _vertHyp[1] = other._vertHyp[1];
10901 _edgeWOLLen[1] = other._edgeWOLLen[1];
10904 const SMDS_MeshNode* Node(size_t i) const
10906 return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10908 void Reverse() { _isReverse = !_isReverse; }
10909 const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse ]; }
10910 const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10911 const AverageHyp& vertHyp1() const { return *(_vertHyp[ _isReverse ]); }
10912 const AverageHyp& vertHyp2() const { return *(_vertHyp[ !_isReverse ]); }
10914 // ................................................................................
10916 SMESH_subMesh* _subMesh;
10917 _SolidData* _data1;
10918 _SolidData* _data2;
10920 std::list< BndPart > _boundary;
10921 int _boundarySize, _nbBoundaryParts;
10923 void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10925 _subMesh = sm; _data1 = sd1; _data2 = sd2;
10927 bool IsSame( const TopoDS_Face& face ) const
10929 return _subMesh->GetSubShape().IsSame( face );
10931 bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10933 return shrunkFaces.Contains( _subMesh->GetSubShape() );
10936 //================================================================================
10938 * Check if meshes on two FACEs are equal
10940 bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10942 if ( !IsSameNbElements( other ))
10945 this->SetBoundary();
10946 other.SetBoundary();
10947 if ( this->_boundarySize != other._boundarySize ||
10948 this->_nbBoundaryParts != other._nbBoundaryParts )
10951 for ( int isReverse = 0; isReverse < 2; ++isReverse )
10954 Reverse( _boundary );
10956 // check boundaries
10957 bool equalBoundary = false;
10958 for ( int iP = 0; iP < _nbBoundaryParts && !equalBoundary; ++iP )
10960 if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10961 // set first part at end
10962 _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10964 if ( !equalBoundary )
10967 // check connectivity
10968 std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10969 this->GetElements( elemsThis );
10970 other.GetElements( elemsOther );
10971 SMESH_MeshEditor::Sew_Error err =
10972 SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10973 this->_boundary.front().Node(0),
10974 other._boundary.front().Node(0),
10975 this->_boundary.front().Node(1),
10976 other._boundary.front().Node(1),
10978 if ( err != SMESH_MeshEditor::SEW_OK )
10981 // check node positions
10982 std::vector< gp_XYZ > srcPnts, tgtPnts;
10983 this->GetBoundaryPoints( srcPnts );
10984 other.GetBoundaryPoints( tgtPnts );
10985 if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10988 double tol = std::numeric_limits<double>::max(); // tolerance by segment size
10989 for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10990 tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10992 tol = 0.01 * Sqrt( tol );
10993 for ( BndPart& boundary : _boundary ) { // tolerance by VL thickness
10994 if ( boundary._isShrink )
10995 tol = Min( tol, boundary._hyp->Get1stLayerThickness() / 50. );
10997 bool nodeCoincide = true;
10998 TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10999 for ( ; n2n != periodic._nnMap.end() && nodeCoincide; ++n2n )
11001 SMESH_NodeXYZ nSrc = n2n->first;
11002 SMESH_NodeXYZ nTgt = n2n->second;
11003 gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
11004 nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol * tol );
11006 if ( nodeCoincide )
11012 bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
11014 SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
11015 SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
11016 return ( sm1->NbElements() == sm2->NbElements() &&
11017 sm1->NbNodes() == sm2->NbNodes() );
11020 void Reverse( std::list< BndPart >& boundary )
11022 boundary.reverse();
11023 for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
11029 if ( !_boundary.empty() )
11032 TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
11033 if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
11034 std::list< TopoDS_Edge > edges;
11035 std::list< int > nbEdgesInWire;
11036 /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
11038 // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
11039 // if ( nbWires > 1 ) {
11040 // edgesEnd = edges.begin();
11041 // std::advance( edgesEnd, nbEdgesInWire.front() );
11043 StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
11044 /*fwd=*/true, /*skipMedium=*/true );
11045 _boundarySize = fSide.NbSegments();
11047 //TopoDS_Vertex vv[2];
11048 //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
11049 for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
11053 std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
11054 bndPart._nodes.assign( nodes.begin(), nodes.end() );
11055 bndPart._nbSegments = bndPart._nodes.size() - 1;
11057 _EdgesOnShape* eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
11059 bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
11060 if ( bndPart._isShrink )
11061 if (( _data1->_noShrinkShapes.count( eos->_shapeID )) ||
11062 ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
11063 bndPart._isShrink = false;
11065 if ( bndPart._isShrink )
11067 bndPart._hyp = & eos->_hyp;
11068 _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
11069 _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
11070 for ( int iV = 0; iV < 2; ++iV )
11072 bndPart._vertHyp [iV] = & eov[iV]->_hyp;
11073 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11074 if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
11075 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11076 if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
11078 eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
11079 if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
11080 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11081 else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
11082 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11085 bndPart._edgeWOLLen[0] = fSide.EdgeLength( iE - 1 );
11086 bndPart._edgeWOLLen[1] = fSide.EdgeLength( iE + 1 );
11088 bndPart._tol = std::numeric_limits<double>::max(); // tolerance by segment size
11089 for ( size_t i = 1; i < bndPart._nodes.size(); ++i )
11090 bndPart._tol = Min( bndPart._tol,
11091 ( bndPart._nodes[i-1] - bndPart._nodes[i] ).SquareModulus() );
11094 if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
11095 _boundary.push_back( bndPart );
11097 _boundary.back().Append( bndPart );
11100 _nbBoundaryParts = _boundary.size();
11101 if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
11103 _boundary.back().Append( _boundary.front() );
11104 _boundary.pop_front();
11105 --_nbBoundaryParts;
11109 void GetElements( std::set<const SMDS_MeshElement*>& theElems)
11111 if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
11112 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
11113 theElems.insert( theElems.end(), fIt->next() );
11118 void GetBoundaryPoints( std::vector< gp_XYZ >& points )
11120 points.reserve( _boundarySize );
11121 size_t nb = _boundary.rbegin()->_nodes.size();
11122 smIdType lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
11123 std::list< BndPart >::const_iterator part = _boundary.begin();
11124 for ( ; part != _boundary.end(); ++part )
11126 size_t nb = part->_nodes.size();
11128 size_t iR = nb - 1;
11129 size_t* i = part->_isReverse ? &iR : &iF;
11130 if ( part->_nodes[ *i ]->GetID() == lastID )
11132 for ( ; iF < nb; ++iF, --iR )
11133 points.push_back( part->_nodes[ *i ]);
11135 lastID = part->_nodes[ *i ]->GetID();
11138 }; // struct ShrinkFace
11140 //--------------------------------------------------------------------------------
11142 * \brief Periodic FACEs
11146 std::vector< ShrinkFace > _shrinkFaces;
11147 std::vector< PeriodicFaces > _periodicFaces;
11149 PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
11151 for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11152 if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
11153 return & _periodicFaces[ i ];
11156 void ClearPeriodic( const TopoDS_Face& face )
11158 for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11159 if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
11160 _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
11161 _periodicFaces[ i ].Clear();
11165 //================================================================================
11167 * Check if a pair includes the given FACE and the other FACE is already shrunk
11169 bool PeriodicFaces::IncludeShrunk( const TopoDS_Face& face,
11170 const TopTools_MapOfShape& shrunkFaces ) const
11172 if ( IsEmpty() ) return false;
11173 return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
11174 ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
11177 //================================================================================
11179 * Make equal meshes on periodic faces by moving corresponding nodes
11181 bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
11183 int iTgt = _shriFace[1]->IsSame( tgtFace );
11184 int iSrc = 1 - iTgt;
11186 _SolidData* dataSrc = _shriFace[iSrc]->_data1;
11187 _SolidData* dataTgt = _shriFace[iTgt]->_data1;
11189 Trsf * trsf = & _trsf, trsfInverse;
11192 trsfInverse = _trsf;
11193 if ( !trsfInverse.Invert())
11195 trsf = &trsfInverse;
11197 SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
11199 dumpFunction(SMESH_Comment("periodicMoveNodes_F")
11200 << _shriFace[iSrc]->_subMesh->GetId() << "_F"
11201 << _shriFace[iTgt]->_subMesh->GetId() );
11202 TNode2Edge::iterator n2e;
11203 TNodeNodeMap::iterator n2n = _nnMap.begin();
11204 for ( ; n2n != _nnMap.end(); ++n2n )
11206 const SMDS_MeshNode* const* nn = & n2n->first;
11207 const SMDS_MeshNode* nSrc = nn[ iSrc ];
11208 const SMDS_MeshNode* nTgt = nn[ iTgt ];
11210 if (( nSrc->GetPosition()->GetDim() == 2 ) ||
11211 (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
11213 SMESH_NodeXYZ pSrc = nSrc;
11214 gp_XYZ pTgt = trsf->Transform( pSrc );
11215 meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
11219 _LayerEdge* leSrc = n2e->second;
11220 n2e = dataTgt->_n2eMap.find( nTgt );
11221 if ( n2e == dataTgt->_n2eMap.end() )
11223 _LayerEdge* leTgt = n2e->second;
11224 if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
11226 for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
11228 SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
11229 gp_XYZ pTgt = trsf->Transform( pSrc );
11230 meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
11232 dumpMove( leTgt->_nodes[ iN ]);
11236 bool done = ( n2n == _nnMap.end() );
11237 debugMsg( "PeriodicFaces::MoveNodes "
11238 << _shriFace[iSrc]->_subMesh->GetId() << " -> "
11239 << _shriFace[iTgt]->_subMesh->GetId() << " -- "
11240 << ( done ? "DONE" : "FAIL"));
11245 } // namespace VISCOUS_3D; Periodicity part
11248 //================================================================================
11250 * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
11251 * and should remain equal after shrink
11253 //================================================================================
11255 void _ViscousBuilder::findPeriodicFaces()
11257 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11258 // _LayerEdge's inflated along FACE or EDGE)
11259 std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
11260 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11262 _SolidData& data = _sdVec[i];
11263 std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11264 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11265 if ( s2s->second.ShapeType() == TopAbs_FACE )
11266 id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11269 _periodicity.reset( new Periodicity );
11270 _periodicity->_shrinkFaces.resize( id2sdMap.size() );
11272 std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
11273 for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
11275 _SolidData* sd1 = id2sdIt->second.front();
11276 _SolidData* sd2 = id2sdIt->second.back();
11277 _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
11280 for ( size_t i1 = 0; i1 < _periodicity->_shrinkFaces.size(); ++i1 )
11281 for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
11283 PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
11284 & _periodicity->_shrinkFaces[ i2 ]);
11285 if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
11287 _periodicity->_periodicFaces.push_back( pf );
11293 //================================================================================
11295 * \brief Shrink 2D mesh on faces to let space for inflated layers
11297 //================================================================================
11299 bool _ViscousBuilder::shrink(_SolidData& theData)
11301 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11302 // _LayerEdge's inflated along FACE or EDGE)
11303 map< TGeomID, list< _SolidData* > > f2sdMap;
11304 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11306 _SolidData& data = _sdVec[i];
11307 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11308 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11309 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
11311 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11313 // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
11314 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
11315 // by StdMeshers_QuadToTriaAdaptor
11316 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
11318 SMESH_ProxyMesh::SubMesh* proxySub =
11319 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
11320 if ( proxySub->NbElements() == 0 )
11322 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11323 while ( fIt->more() )
11325 const SMDS_MeshElement* f = fIt->next();
11326 // as a result 3D algo will use elements from proxySub and not from smDS
11327 proxySub->AddElement( f );
11328 f->setIsMarked( true );
11330 // Mark nodes on the FACE to discriminate them from nodes
11331 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
11332 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
11334 const SMDS_MeshNode* n = f->GetNode( iN );
11335 if ( n->GetPosition()->GetDim() == 2 )
11336 n->setIsMarked( true );
11344 SMESH_MesherHelper helper( *_mesh );
11345 helper.ToFixNodeParameters( true );
11348 map< TGeomID, _Shrinker1D > e2shrMap;
11349 vector< _EdgesOnShape* > subEOS;
11350 vector< _LayerEdge* > lEdges;
11352 // loop on FACEs to shrink mesh on
11353 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
11354 for ( ; f2sd != f2sdMap.end(); ++f2sd )
11356 list< _SolidData* > & dataList = f2sd->second;
11357 if ( dataList.front()->_n2eMap.empty() ||
11358 dataList.back() ->_n2eMap.empty() )
11359 continue; // not yet computed
11360 if ( dataList.front() != &theData &&
11361 dataList.back() != &theData )
11364 _SolidData& data = *dataList.front();
11365 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
11366 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
11367 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
11368 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
11370 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
11372 _shrunkFaces.Add( F );
11373 helper.SetSubShape( F );
11375 // ==============================
11376 // Use periodicity to move nodes
11377 // ==============================
11379 PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
11380 bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
11382 // ===========================
11383 // Prepare data for shrinking
11384 // ===========================
11386 // Collect nodes to smooth (they are marked at the beginning of this method)
11387 vector < const SMDS_MeshNode* > smoothNodes;
11389 if ( !movedByPeriod )
11391 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11392 while ( nIt->more() )
11394 const SMDS_MeshNode* n = nIt->next();
11395 if ( n->isMarked() )
11396 smoothNodes.push_back( n );
11399 // Find out face orientation
11400 double refSign = 1;
11401 const set<TGeomID> ignoreShapes;
11403 if ( !smoothNodes.empty() )
11405 vector<_Simplex> simplices;
11406 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11407 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11408 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11409 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11410 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11414 // Find _LayerEdge's inflated along F
11418 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11419 /*complexFirst=*/true); //!!!
11420 while ( subIt->more() )
11422 const TGeomID subID = subIt->next()->GetId();
11423 if ( data._noShrinkShapes.count( subID ))
11425 _EdgesOnShape* eos = data.GetShapeEdges( subID );
11426 if ( !eos || eos->_sWOL.IsNull() )
11427 if ( data2 ) // check in adjacent SOLID
11429 eos = data2->GetShapeEdges( subID );
11430 if ( !eos || eos->_sWOL.IsNull() )
11433 subEOS.push_back( eos );
11435 if ( !movedByPeriod )
11436 for ( size_t i = 0; i < eos->_edges.size(); ++i )
11438 lEdges.push_back( eos->_edges[ i ] );
11439 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11444 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11445 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11446 while ( fIt->more() )
11447 if ( const SMDS_MeshElement* f = fIt->next() )
11448 dumpChangeNodes( f );
11451 // Replace source nodes by target nodes in mesh faces to shrink
11452 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11453 const SMDS_MeshNode* nodes[20];
11454 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11456 _EdgesOnShape& eos = * subEOS[ iS ];
11457 for ( size_t i = 0; i < eos._edges.size(); ++i )
11459 _LayerEdge& edge = *eos._edges[i];
11460 const SMDS_MeshNode* srcNode = edge._nodes[0];
11461 const SMDS_MeshNode* tgtNode = edge._nodes.back();
11462 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11463 while ( fIt->more() )
11465 const SMDS_MeshElement* f = fIt->next();
11466 if ( !smDS->Contains( f ) || !f->isMarked() )
11468 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11469 for ( int iN = 0; nIt->more(); ++iN )
11471 const SMDS_MeshNode* n = nIt->next();
11472 nodes[iN] = ( n == srcNode ? tgtNode : n );
11474 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11475 dumpChangeNodes( f );
11481 // find out if a FACE is concave
11482 const bool isConcaveFace = isConcave( F, helper );
11484 // Create _SmoothNode's on face F
11485 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11487 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11488 const bool sortSimplices = isConcaveFace;
11489 for ( size_t i = 0; i < smoothNodes.size(); ++i )
11491 const SMDS_MeshNode* n = smoothNodes[i];
11492 nodesToSmooth[ i ]._node = n;
11493 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11494 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11495 // fix up incorrect uv of nodes on the FACE
11496 helper.GetNodeUV( F, n, 0, &isOkUV);
11501 //if ( nodesToSmooth.empty() ) continue;
11503 // Find EDGE's to shrink and set simpices to LayerEdge's
11504 set< _Shrinker1D* > eShri1D;
11506 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11508 _EdgesOnShape& eos = * subEOS[ iS ];
11509 if ( eos.SWOLType() == TopAbs_EDGE )
11511 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11512 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11513 if ( !movedByPeriod )
11515 _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11516 eShri1D.insert( & shrinker );
11517 shrinker.AddEdge( eos._edges[0], eos, helper );
11518 // restore params of nodes on EDGE if the EDGE has been already
11519 // shrunk while shrinking other FACE
11520 shrinker.RestoreParams();
11523 for ( size_t i = 0; i < eos._edges.size(); ++i )
11525 _LayerEdge& edge = * eos._edges[i];
11526 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11528 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11529 // not-marked nodes are those added by refine()
11530 edge._nodes.back()->setIsMarked( true );
11535 bool toFixTria = false; // to improve quality of trias by diagonal swap
11536 if ( isConcaveFace && !movedByPeriod )
11538 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11539 if ( hasTria != hasQuad ) {
11540 toFixTria = hasTria;
11543 set<int> nbNodesSet;
11544 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11545 while ( fIt->more() && nbNodesSet.size() < 2 )
11546 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11547 toFixTria = ( *nbNodesSet.begin() == 3 );
11551 // ==================
11552 // Perform shrinking
11553 // ==================
11555 bool shrunk = !movedByPeriod;
11556 int nbBad, shriStep=0, smooStep=0;
11557 _SmoothNode::SmoothType smoothType
11558 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11559 SMESH_Comment errMsg;
11563 // Move boundary nodes (actually just set new UV)
11564 // -----------------------------------------------
11565 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11567 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11569 _EdgesOnShape& eos = * subEOS[ iS ];
11570 for ( size_t i = 0; i < eos._edges.size(); ++i )
11572 shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11577 // Move nodes on EDGE's
11578 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11579 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11580 for ( ; shr != eShri1D.end(); ++shr )
11581 (*shr)->Compute( /*set3D=*/false, helper );
11584 // -----------------
11585 int nbNoImpSteps = 0;
11588 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11590 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11592 int oldBadNb = nbBad;
11595 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11596 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11597 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11599 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11600 smooTy, /*set3D=*/isConcaveFace);
11602 if ( nbBad < oldBadNb )
11612 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11613 if ( shriStep > 200 )
11614 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11615 if ( !errMsg.empty() )
11618 // Fix narrow triangles by swapping diagonals
11619 // ---------------------------------------
11622 set<const SMDS_MeshNode*> usedNodes;
11623 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11625 // update working data
11626 set<const SMDS_MeshNode*>::iterator n;
11627 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11629 n = usedNodes.find( nodesToSmooth[ i ]._node );
11630 if ( n != usedNodes.end())
11632 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11633 nodesToSmooth[ i ]._simplices,
11634 ignoreShapes, NULL,
11635 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11636 usedNodes.erase( n );
11639 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11641 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11642 if ( n != usedNodes.end())
11644 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11645 lEdges[i]->_simplices,
11647 usedNodes.erase( n );
11651 // TODO: check effect of this additional smooth
11652 // additional laplacian smooth to increase allowed shrink step
11653 // for ( int st = 1; st; --st )
11655 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11656 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11658 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11659 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
11663 } // while ( shrunk )
11665 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11667 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11670 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11672 vector< const SMDS_MeshElement* > facesToRm;
11675 facesToRm.reserve( psm->NbElements() );
11676 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11677 facesToRm.push_back( ite->next() );
11679 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11680 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11683 for ( size_t i = 0; i < facesToRm.size(); ++i )
11684 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11688 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11689 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11690 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11691 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11692 subEOS[iS]->_edges[i]->_nodes.end() );
11694 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11695 while ( itn->more() ) {
11696 const SMDS_MeshNode* n = itn->next();
11697 if ( !nodesToKeep.count( n ))
11698 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11701 _periodicity->ClearPeriodic( F );
11703 // restore position and UV of target nodes
11705 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11706 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11708 _LayerEdge* edge = subEOS[iS]->_edges[i];
11709 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11710 if ( edge->_pos.empty() ||
11711 edge->Is( _LayerEdge::SHRUNK )) continue;
11712 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11714 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11715 pos->SetUParameter( edge->_pos[0].X() );
11716 pos->SetVParameter( edge->_pos[0].Y() );
11717 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11721 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11722 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11723 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11725 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11726 dumpMove( tgtNode );
11728 // shrink EDGE sub-meshes and set proxy sub-meshes
11729 UVPtStructVec uvPtVec;
11730 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11731 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11733 _Shrinker1D* shr = (*shrIt);
11734 shr->Compute( /*set3D=*/true, helper );
11736 // set proxy mesh of EDGEs w/o layers
11737 map< double, const SMDS_MeshNode* > nodes;
11738 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11739 // remove refinement nodes
11740 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11741 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11742 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11743 if ( u2n->second == sn0 || u2n->second == sn1 )
11745 while ( u2n->second != tn0 && u2n->second != tn1 )
11747 nodes.erase( nodes.begin(), u2n );
11749 u2n = --nodes.end();
11750 if ( u2n->second == sn0 || u2n->second == sn1 )
11752 while ( u2n->second != tn0 && u2n->second != tn1 )
11754 nodes.erase( ++u2n, nodes.end() );
11756 // set proxy sub-mesh
11757 uvPtVec.resize( nodes.size() );
11758 u2n = nodes.begin();
11759 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11760 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11762 uvPtVec[ i ].node = u2n->second;
11763 uvPtVec[ i ].param = u2n->first;
11764 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11766 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11767 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11770 // set proxy mesh of EDGEs with layers
11771 vector< _LayerEdge* > edges;
11772 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11774 _EdgesOnShape& eos = * subEOS[ iS ];
11775 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11776 if ( eos.size() == 0 )
11779 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11780 data.SortOnEdge( E, eos._edges );
11783 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11784 if ( !eov->_edges.empty() )
11785 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11787 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11789 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11790 if ( !eov->_edges.empty() )
11791 edges.push_back( eov->_edges[0] ); // on last VERTEX
11793 uvPtVec.resize( edges.size() );
11794 for ( size_t i = 0; i < edges.size(); ++i )
11796 uvPtVec[ i ].node = edges[i]->_nodes.back();
11797 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11798 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11800 if ( uvPtVec[ 0 ].node == uvPtVec.back().node && // closed
11801 helper.IsSeamShape( uvPtVec[ 0 ].node->GetShapeID() ))
11803 uvPtVec[ 0 ].SetUV( helper.GetNodeUV( F,
11804 edges[0]->_nodes.back(),
11805 edges[1]->_nodes.back() ));
11806 size_t i = edges.size() - 1;
11807 uvPtVec[ i ].SetUV( helper.GetNodeUV( F,
11808 edges[i ]->_nodes.back(),
11809 edges[i-1]->_nodes.back() ));
11811 // if ( edges.empty() )
11813 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11814 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11815 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11817 // temporary clear the FACE sub-mesh from faces made by refine()
11818 vector< const SMDS_MeshElement* > elems;
11819 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11820 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11821 elems.push_back( ite->next() );
11822 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11823 elems.push_back( ite->next() );
11826 // compute the mesh on the FACE
11827 TopTools_IndexedMapOfShape allowed(1);
11828 allowed.Add( sm->GetSubShape() );
11829 sm->SetAllowedSubShapes( &allowed );
11830 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11831 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11832 sm->SetAllowedSubShapes( nullptr );
11834 // re-fill proxy sub-meshes of the FACE
11835 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11836 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11837 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11838 psm->AddElement( ite->next() );
11841 for ( size_t i = 0; i < elems.size(); ++i )
11842 smDS->AddElement( elems[i] );
11844 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11845 return error( errMsg );
11847 } // end of re-meshing in case of failed smoothing
11848 else if ( !movedByPeriod )
11850 // No wrongly shaped faces remain; final smooth. Set node XYZ.
11851 bool isStructuredFixed = false;
11852 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11853 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11854 if ( !isStructuredFixed )
11856 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11857 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11859 for ( int st = 3; st; --st )
11862 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11863 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11864 case 3: smoothType = _SmoothNode::ANGULAR; break;
11866 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11867 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11869 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11870 smoothType,/*set3D=*/st==1 );
11875 if ( !getMeshDS()->IsEmbeddedMode() )
11876 // Log node movement
11877 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11879 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11880 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11884 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11885 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11887 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11889 } // loop on FACES to shrink mesh on
11892 // Replace source nodes by target nodes in shrunk mesh edges
11894 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11895 for ( ; e2shr != e2shrMap.end(); ++e2shr )
11896 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11901 //================================================================================
11903 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11905 //================================================================================
11907 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
11908 _EdgesOnShape& eos,
11909 SMESH_MesherHelper& helper,
11910 const SMESHDS_SubMesh* /*faceSubMesh*/)
11912 const SMDS_MeshNode* srcNode = edge._nodes[0];
11913 const SMDS_MeshNode* tgtNode = edge._nodes.back();
11915 if ( eos.SWOLType() == TopAbs_FACE )
11917 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11920 edge.Set( _LayerEdge::SHRUNK );
11921 return srcNode == tgtNode;
11923 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
11924 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11925 gp_Vec2d uvDir( srcUV, tgtUV );
11926 double uvLen = uvDir.Magnitude();
11928 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11931 //edge._pos.resize(1);
11932 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11934 // set UV of source node to target node
11935 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11936 pos->SetUParameter( srcUV.X() );
11937 pos->SetVParameter( srcUV.Y() );
11939 else // _sWOL is TopAbs_EDGE
11941 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11944 edge.Set( _LayerEdge::SHRUNK );
11945 return srcNode == tgtNode;
11947 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11948 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11949 if ( !edgeSM || edgeSM->NbElements() == 0 )
11950 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11952 const SMDS_MeshNode* n2 = 0;
11953 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11954 while ( eIt->more() && !n2 )
11956 const SMDS_MeshElement* e = eIt->next();
11957 if ( !edgeSM->Contains(e)) continue;
11958 n2 = e->GetNode( 0 );
11959 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11962 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11964 if ( n2 == tgtNode || // for 3D_mesh_GHS3D_01/B1
11965 n2 == edge._nodes[1] ) // bos #20643
11967 // shrunk by other SOLID
11968 edge.Set( _LayerEdge::SHRUNK ); // ???
11972 double uSrc = helper.GetNodeU( E, srcNode, n2 );
11973 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11974 double u2 = helper.GetNodeU( E, n2, srcNode );
11976 //edge._pos.clear();
11978 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11980 // tgtNode is located so that it does not make faces with wrong orientation
11981 edge.Set( _LayerEdge::SHRUNK );
11984 //edge._pos.resize(1);
11985 edge._pos[0].SetCoord( U_TGT, uTgt );
11986 edge._pos[0].SetCoord( U_SRC, uSrc );
11987 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11989 edge._simplices.resize( 1 );
11990 edge._simplices[0]._nPrev = n2;
11992 // set U of source node to the target node
11993 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11994 pos->SetUParameter( uSrc );
11999 //================================================================================
12001 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
12003 //================================================================================
12005 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
12007 if ( edge._nodes.size() == 1 )
12012 const SMDS_MeshNode* srcNode = edge._nodes[0];
12013 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
12014 if ( S.IsNull() ) return;
12018 switch ( S.ShapeType() )
12023 TopLoc_Location loc;
12024 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
12025 if ( curve.IsNull() ) return;
12026 SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
12027 p = curve->Value( ePos->GetUParameter() );
12030 case TopAbs_VERTEX:
12032 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
12037 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
12038 dumpMove( srcNode );
12042 //================================================================================
12044 * \brief Try to fix triangles with high aspect ratio by swapping diagonals
12046 //================================================================================
12048 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
12049 SMESH_MesherHelper& helper,
12052 set<const SMDS_MeshNode*> * involvedNodes)
12054 SMESH::Controls::AspectRatio qualifier;
12055 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
12056 const double maxAspectRatio = is2D ? 4. : 2;
12057 _NodeCoordHelper xyz( F, helper, is2D );
12059 // find bad triangles
12061 vector< const SMDS_MeshElement* > badTrias;
12062 vector< double > badAspects;
12063 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
12064 SMDS_ElemIteratorPtr fIt = sm->GetElements();
12065 while ( fIt->more() )
12067 const SMDS_MeshElement * f = fIt->next();
12068 if ( f->NbCornerNodes() != 3 ) continue;
12069 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
12070 double aspect = qualifier.GetValue( points );
12071 if ( aspect > maxAspectRatio )
12073 badTrias.push_back( f );
12074 badAspects.push_back( aspect );
12079 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
12080 SMDS_ElemIteratorPtr fIt = sm->GetElements();
12081 while ( fIt->more() )
12083 const SMDS_MeshElement * f = fIt->next();
12084 if ( f->NbCornerNodes() == 3 )
12085 dumpChangeNodes( f );
12089 if ( badTrias.empty() )
12092 // find couples of faces to swap diagonal
12094 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
12095 vector< T2Trias > triaCouples;
12097 TIDSortedElemSet involvedFaces, emptySet;
12098 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
12101 double aspRatio [3];
12104 if ( !involvedFaces.insert( badTrias[iTia] ).second )
12106 for ( int iP = 0; iP < 3; ++iP )
12107 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
12109 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
12110 int bestCouple = -1;
12111 for ( int iSide = 0; iSide < 3; ++iSide )
12113 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
12114 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
12115 trias [iSide].first = badTrias[iTia];
12116 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
12118 if (( ! trias[iSide].second ) ||
12119 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
12120 ( ! sm->Contains( trias[iSide].second )))
12123 // aspect ratio of an adjacent tria
12124 for ( int iP = 0; iP < 3; ++iP )
12125 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
12126 double aspectInit = qualifier.GetValue( points2 );
12128 // arrange nodes as after diag-swaping
12129 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
12130 i3 = helper.WrapIndex( i1-1, 3 );
12132 i3 = helper.WrapIndex( i1+1, 3 );
12134 points1( 1+ iSide ) = points2( 1+ i3 );
12135 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
12137 // aspect ratio after diag-swaping
12138 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
12139 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
12142 // prevent inversion of a triangle
12143 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
12144 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
12145 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
12148 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
12149 bestCouple = iSide;
12152 if ( bestCouple >= 0 )
12154 triaCouples.push_back( trias[bestCouple] );
12155 involvedFaces.insert ( trias[bestCouple].second );
12159 involvedFaces.erase( badTrias[iTia] );
12162 if ( triaCouples.empty() )
12167 SMESH_MeshEditor editor( helper.GetMesh() );
12168 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12169 for ( size_t i = 0; i < triaCouples.size(); ++i )
12171 dumpChangeNodes( triaCouples[i].first );
12172 dumpChangeNodes( triaCouples[i].second );
12173 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
12176 if ( involvedNodes )
12177 for ( size_t i = 0; i < triaCouples.size(); ++i )
12179 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
12180 triaCouples[i].first->end_nodes() );
12181 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
12182 triaCouples[i].second->end_nodes() );
12185 // just for debug dump resulting triangles
12186 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12187 for ( size_t i = 0; i < triaCouples.size(); ++i )
12189 dumpChangeNodes( triaCouples[i].first );
12190 dumpChangeNodes( triaCouples[i].second );
12194 //================================================================================
12196 * \brief Move target node to it's final position on the FACE during shrinking
12198 //================================================================================
12200 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
12201 const TopoDS_Face& F,
12202 _EdgesOnShape& eos,
12203 SMESH_MesherHelper& helper )
12206 return false; // already at the target position
12208 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
12210 if ( eos.SWOLType() == TopAbs_FACE )
12212 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
12213 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
12214 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
12215 const double uvLen = tgtUV.Distance( curUV );
12216 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
12218 // Select shrinking step such that not to make faces with wrong orientation.
12219 double stepSize = 1e100;
12220 for ( size_t i = 0; i < _simplices.size(); ++i )
12222 if ( !_simplices[i]._nPrev->isMarked() ||
12223 !_simplices[i]._nNext->isMarked() )
12224 continue; // simplex of quadrangle created by addBoundaryElements()
12226 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
12227 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev, tgtNode );
12228 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext, tgtNode );
12229 gp_XY dirN = uvN2 - uvN1;
12230 double det = uvDir.Crossed( dirN );
12231 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
12232 gp_XY dirN2Cur = curUV - uvN1;
12233 double step = dirN.Crossed( dirN2Cur ) / det;
12235 stepSize = Min( step, stepSize );
12238 if ( uvLen <= stepSize )
12244 else if ( stepSize > 0 )
12246 newUV = curUV + uvDir.XY() * stepSize * kSafe;
12252 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
12253 pos->SetUParameter( newUV.X() );
12254 pos->SetVParameter( newUV.Y() );
12257 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12258 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12259 dumpMove( tgtNode );
12261 if ( surface.IsNull() ) {}
12264 else // _sWOL is TopAbs_EDGE
12266 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
12267 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
12268 SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
12270 const double u2 = helper.GetNodeU( E, n2, tgtNode );
12271 const double uSrc = _pos[0].Coord( U_SRC );
12272 const double lenTgt = _pos[0].Coord( LEN_TGT );
12274 double newU = _pos[0].Coord( U_TGT );
12275 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
12277 Set( _LayerEdge::SHRUNK );
12282 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
12284 tgtPos->SetUParameter( newU );
12286 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
12287 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12288 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12289 dumpMove( tgtNode );
12296 //================================================================================
12298 * \brief Perform smooth on the FACE
12299 * \retval bool - true if the node has been moved
12301 //================================================================================
12303 bool _SmoothNode::Smooth(int& nbBad,
12304 Handle(Geom_Surface)& surface,
12305 SMESH_MesherHelper& helper,
12306 const double refSign,
12310 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
12312 // get uv of surrounding nodes
12313 vector<gp_XY> uv( _simplices.size() );
12314 for ( size_t i = 0; i < _simplices.size(); ++i )
12315 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
12317 // compute new UV for the node
12318 gp_XY newPos (0,0);
12319 if ( how == TFI && _simplices.size() == 4 )
12322 for ( size_t i = 0; i < _simplices.size(); ++i )
12323 if ( _simplices[i]._nOpp )
12324 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
12326 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
12328 newPos = helper.calcTFI ( 0.5, 0.5,
12329 corners[0], corners[1], corners[2], corners[3],
12330 uv[1], uv[2], uv[3], uv[0] );
12332 else if ( how == ANGULAR )
12334 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
12336 else if ( how == CENTROIDAL && _simplices.size() > 3 )
12338 // average centers of diagonals wieghted with their reciprocal lengths
12339 if ( _simplices.size() == 4 )
12341 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
12342 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
12343 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
12347 double sumWeight = 0;
12348 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
12349 for ( int i = 0; i < nb; ++i )
12352 int iTo = i + _simplices.size() - 1;
12353 for ( int j = iFrom; j < iTo; ++j )
12355 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
12356 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
12358 newPos += w * ( uv[i]+uv[i2] );
12361 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
12366 // Laplacian smooth
12367 for ( size_t i = 0; i < _simplices.size(); ++i )
12369 newPos /= _simplices.size();
12372 // count quality metrics (orientation) of triangles around the node
12373 int nbOkBefore = 0;
12374 gp_XY tgtUV = helper.GetNodeUV( face, _node );
12375 for ( size_t i = 0; i < _simplices.size(); ++i )
12376 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
12379 for ( size_t i = 0; i < _simplices.size(); ++i )
12380 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
12382 if ( nbOkAfter < nbOkBefore )
12384 nbBad += _simplices.size() - nbOkBefore;
12388 SMDS_FacePositionPtr pos = _node->GetPosition();
12389 pos->SetUParameter( newPos.X() );
12390 pos->SetVParameter( newPos.Y() );
12397 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
12398 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
12402 nbBad += _simplices.size() - nbOkAfter;
12403 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
12406 //================================================================================
12408 * \brief Computes new UV using angle based smoothing technique
12410 //================================================================================
12412 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12413 const gp_XY& uvToFix,
12414 const double refSign)
12416 uv.push_back( uv.front() );
12418 vector< gp_XY > edgeDir ( uv.size() );
12419 vector< double > edgeSize( uv.size() );
12420 for ( size_t i = 1; i < edgeDir.size(); ++i )
12422 edgeDir [i-1] = uv[i] - uv[i-1];
12423 edgeSize[i-1] = edgeDir[i-1].Modulus();
12424 if ( edgeSize[i-1] < numeric_limits<double>::min() )
12425 edgeDir[i-1].SetX( 100 );
12427 edgeDir[i-1] /= edgeSize[i-1] * refSign;
12429 edgeDir.back() = edgeDir.front();
12430 edgeSize.back() = edgeSize.front();
12434 for ( size_t i = 1; i < edgeDir.size(); ++i )
12436 const int i1 = i-1;
12437 if ( edgeDir[i1].X() > 1. ) continue;
12438 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12439 if ( i == edgeDir.size() ) break;
12441 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12442 gp_XY norm2( -edgeDir[i ].Y(), edgeDir[i ].X() );
12443 gp_XY bisec = norm1 + norm2;
12444 double bisecSize = bisec.Modulus();
12445 if ( bisecSize < numeric_limits<double>::min() )
12447 bisec = -edgeDir[i1] + edgeDir[i];
12448 bisecSize = bisec.Modulus();
12450 bisec /= bisecSize;
12452 gp_XY dirToN = uvToFix - p;
12453 double distToN = bisec * dirToN;
12454 if ( bisec * dirToN < 0 )
12455 distToN = -distToN;
12457 double wgt = edgeSize[i1] + edgeSize[i];
12458 newPos += ( p + bisec * distToN ) * wgt;
12465 //================================================================================
12467 * \brief Keep a _LayerEdge inflated along the EDGE
12469 //================================================================================
12471 void _Shrinker1D::AddEdge( const _LayerEdge* e,
12472 _EdgesOnShape& eos,
12473 SMESH_MesherHelper& helper )
12476 if ( _nodes.empty() )
12478 _edges[0] = _edges[1] = 0;
12481 // check _LayerEdge
12482 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12484 if ( eos.SWOLType() != TopAbs_EDGE )
12485 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12486 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12487 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12489 // store _LayerEdge
12490 _geomEdge = TopoDS::Edge( eos._sWOL );
12492 BRep_Tool::Range( _geomEdge, f,l );
12493 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12494 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12496 // Check if the nodes are already shrunk by another SOLID
12498 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12499 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12501 _done = (( tgtNode0 && tgtNode0->NbInverseElements( SMDSAbs_Edge ) == 2 ) ||
12502 ( tgtNode1 && tgtNode1->NbInverseElements( SMDSAbs_Edge ) == 2 ));
12504 _nodes.resize( 1, nullptr );
12508 if ( _nodes.empty() )
12510 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12511 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12513 TopLoc_Location loc;
12514 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12515 GeomAdaptor_Curve aCurve(C, f,l);
12516 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12518 smIdType nbExpectNodes = eSubMesh->NbNodes();
12519 _initU .reserve( nbExpectNodes );
12520 _normPar.reserve( nbExpectNodes );
12521 _nodes .reserve( nbExpectNodes );
12522 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12523 while ( nIt->more() )
12525 const SMDS_MeshNode* node = nIt->next();
12527 // skip refinement nodes
12528 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12529 node == tgtNode0 || node == tgtNode1 )
12531 bool hasMarkedFace = false;
12532 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12533 while ( fIt->more() && !hasMarkedFace )
12534 hasMarkedFace = fIt->next()->isMarked();
12535 if ( !hasMarkedFace )
12538 _nodes.push_back( node );
12539 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12540 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12541 _normPar.push_back( len / totLen );
12546 // remove target node of the _LayerEdge from _nodes
12547 size_t nbFound = 0;
12548 for ( size_t i = 0; i < _nodes.size(); ++i )
12549 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12550 _nodes[i] = 0, nbFound++;
12551 if ( nbFound == _nodes.size() )
12556 //================================================================================
12558 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12560 //================================================================================
12562 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12564 if ( _done || _nodes.empty())
12566 const _LayerEdge* e = _edges[0];
12567 if ( !e ) e = _edges[1];
12570 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12571 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12574 if ( set3D || _done )
12576 dumpFunction(SMESH_Comment("shrink1D_E") << helper.GetMeshDS()->ShapeToIndex( _geomEdge )<<
12577 "_F" << helper.GetSubShapeID() );
12578 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12579 GeomAdaptor_Curve aCurve(C, f,l);
12582 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12584 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12585 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12587 for ( size_t i = 0; i < _nodes.size(); ++i )
12589 if ( !_nodes[i] ) continue;
12590 double len = totLen * _normPar[i];
12591 GCPnts_AbscissaPoint discret( aCurve, len, f );
12592 if ( !discret.IsDone() )
12593 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12594 double u = discret.Parameter();
12595 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12596 pos->SetUParameter( u );
12597 gp_Pnt p = C->Value( u );
12598 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12599 dumpMove( _nodes[i] );
12605 BRep_Tool::Range( _geomEdge, f,l );
12607 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12609 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12611 for ( size_t i = 0; i < _nodes.size(); ++i )
12613 if ( !_nodes[i] ) continue;
12614 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12615 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12616 pos->SetUParameter( u );
12621 //================================================================================
12623 * \brief Restore initial parameters of nodes on EDGE
12625 //================================================================================
12627 void _Shrinker1D::RestoreParams()
12630 for ( size_t i = 0; i < _nodes.size(); ++i )
12632 if ( !_nodes[i] ) continue;
12633 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12634 pos->SetUParameter( _initU[i] );
12639 //================================================================================
12641 * \brief Replace source nodes by target nodes in shrunk mesh edges
12643 //================================================================================
12645 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12647 const SMDS_MeshNode* nodes[3];
12648 for ( int i = 0; i < 2; ++i )
12650 if ( !_edges[i] ) continue;
12652 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12653 if ( !eSubMesh ) return;
12654 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12655 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12656 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12657 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12658 while ( eIt->more() )
12660 const SMDS_MeshElement* e = eIt->next();
12661 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12663 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12664 for ( int iN = 0; iN < e->NbNodes(); ++iN )
12666 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12667 nodes[iN] = ( n == srcNode ? tgtNode : n );
12669 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12674 //================================================================================
12676 * \brief Setup quadPoints
12678 //================================================================================
12680 _Mapper2D::_Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap )
12682 size_t i, iSize = _quadPoints.iSize = param2ColumnMap.size();
12683 size_t j, jSize = _quadPoints.jSize = param2ColumnMap.begin()->second.size();
12684 if ( _quadPoints.iSize < 3 ||
12685 _quadPoints.jSize < 3 )
12687 _quadPoints.uv_grid.resize( iSize * jSize );
12691 for ( auto & u_columnNodes : param2ColumnMap )
12693 for ( j = 0; j < u_columnNodes.second.size(); ++j )
12694 _quadPoints.UVPt( i, j ).node = u_columnNodes.second[ j ];
12698 // compute x parameter on borders
12699 uvPnt( 0, 0 ).x = 0;
12700 uvPnt( 0, jSize-1 ).x = 0;
12701 gp_Pnt p0, pPrev0 = SMESH_NodeXYZ( uvPnt( 0, 0 ).node );
12702 gp_Pnt p1, pPrev1 = SMESH_NodeXYZ( uvPnt( 0, jSize-1 ).node );
12703 for ( i = 1; i < iSize; ++i )
12705 p0 = SMESH_NodeXYZ( uvPnt( i, 0 ).node );
12706 p1 = SMESH_NodeXYZ( uvPnt( i, jSize-1 ).node );
12707 uvPnt( i, 0 ).x = uvPnt( i-1, 0 ).x + p0.Distance( pPrev0 );
12708 uvPnt( i, jSize-1 ).x = uvPnt( i-1, jSize-1 ).x + p1.Distance( pPrev1 );
12712 for ( i = 1; i < iSize-1; ++i )
12714 uvPnt( i, 0 ).x /= uvPnt( iSize-1, 0 ).x;
12715 uvPnt( i, jSize-1 ).x /= uvPnt( iSize-1, jSize-1 ).x;
12716 uvPnt( i, 0 ).y = 0;
12717 uvPnt( i, jSize-1 ).y = 1;
12720 // compute y parameter on borders
12721 uvPnt( 0, 0 ).y = 0;
12722 uvPnt( iSize-1, 0 ).y = 0;
12723 pPrev0 = SMESH_NodeXYZ( uvPnt( 0, 0 ).node );
12724 pPrev1 = SMESH_NodeXYZ( uvPnt( iSize-1, 0 ).node );
12725 for ( j = 1; j < jSize; ++j )
12727 p0 = SMESH_NodeXYZ( uvPnt( 0, j ).node );
12728 p1 = SMESH_NodeXYZ( uvPnt( iSize-1, j ).node );
12729 uvPnt( 0, j ).y = uvPnt( 0, j-1 ).y + p0.Distance( pPrev0 );
12730 uvPnt( iSize-1, j ).y = uvPnt( iSize-1, j-1 ).y + p1.Distance( pPrev1 );
12734 for ( j = 1; j < jSize-1; ++j )
12736 uvPnt( 0, j ).y /= uvPnt( 0, jSize-1 ).y;
12737 uvPnt( iSize-1, j ).y /= uvPnt( iSize-1, jSize-1 ).y;
12738 uvPnt( 0, j ).x = 0;
12739 uvPnt( iSize-1, j ).x = 1;
12742 // compute xy of internal nodes
12743 for ( i = 1; i < iSize-1; ++i )
12745 const double x0 = uvPnt( i, 0 ).x;
12746 const double x1 = uvPnt( i, jSize-1 ).x;
12747 for ( j = 1; j < jSize-1; ++j )
12749 const double y0 = uvPnt( 0, j ).y;
12750 const double y1 = uvPnt( iSize-1, j ).y;
12751 double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
12752 double y = y0 + x * (y1 - y0);
12753 uvPnt( i, j ).x = x;
12754 uvPnt( i, j ).y = y;
12758 // replace base nodes with target ones
12759 for ( i = 0; i < iSize; ++i )
12760 for ( j = 0; j < jSize; ++j )
12762 auto n2e = n2eMap.find( uvPnt( i, j ).node );
12763 uvPnt( i, j ).node = n2e->second->_nodes.back();
12769 //================================================================================
12771 * \brief Compute positions of nodes of 2D structured mesh using TFI
12773 //================================================================================
12775 bool _Mapper2D::ComputeNodePositions()
12777 if ( _quadPoints.uv_grid.empty() )
12780 size_t i, iSize = _quadPoints.iSize;
12781 size_t j, jSize = _quadPoints.jSize;
12783 SMESH_NodeXYZ a0 ( uvPnt( 0, 0 ).node );
12784 SMESH_NodeXYZ a1 ( uvPnt( iSize-1, 0 ).node );
12785 SMESH_NodeXYZ a2 ( uvPnt( iSize-1, jSize-1 ).node );
12786 SMESH_NodeXYZ a3 ( uvPnt( 0, jSize-1 ).node );
12788 for ( i = 1; i < iSize-1; ++i )
12790 SMESH_NodeXYZ p0 ( uvPnt( i, 0 ).node );
12791 SMESH_NodeXYZ p2 ( uvPnt( i, jSize-1 ).node );
12792 for ( j = 1; j < jSize-1; ++j )
12794 SMESH_NodeXYZ p1 ( uvPnt( iSize-1, j ).node );
12795 SMESH_NodeXYZ p3 ( uvPnt( 0, j ).node );
12796 double x = uvPnt( i, j ).x;
12797 double y = uvPnt( i, j ).y;
12799 gp_XYZ p = SMESH_MesherHelper::calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
12800 const_cast< SMDS_MeshNode* >( uvPnt( i, j ).node )->setXYZ( p.X(), p.Y(), p.Z() );
12802 dumpMove( uvPnt( i, j ).node );
12808 //================================================================================
12810 * \brief Creates 2D and 1D elements on boundaries of new prisms
12812 //================================================================================
12814 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12816 SMESH_MesherHelper helper( *_mesh );
12818 vector< const SMDS_MeshNode* > faceNodes;
12820 //for ( size_t i = 0; i < _sdVec.size(); ++i )
12822 //_SolidData& data = _sdVec[i];
12823 TopTools_IndexedMapOfShape geomEdges;
12824 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12825 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12827 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12828 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12829 if ( data._noShrinkShapes.count( edgeID ))
12832 // Get _LayerEdge's based on E
12834 map< double, const SMDS_MeshNode* > u2nodes;
12835 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12838 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12839 TNode2Edge & n2eMap = data._n2eMap;
12840 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12842 //check if 2D elements are needed on E
12843 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12844 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12845 ledges.push_back( n2e->second );
12847 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12848 continue; // no layers on E
12849 ledges.push_back( n2eMap[ u2n->second ]);
12851 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12852 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12853 int nbSharedPyram = 0;
12854 SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12855 while ( vIt->more() )
12857 const SMDS_MeshElement* v = vIt->next();
12858 nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12860 if ( nbSharedPyram > 1 )
12861 continue; // not free border of the pyramid
12864 faceNodes.push_back( ledges[0]->_nodes[0] );
12865 faceNodes.push_back( ledges[1]->_nodes[0] );
12866 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12867 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12869 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12870 continue; // faces already created
12872 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12873 ledges.push_back( n2eMap[ u2n->second ]);
12875 // Find out orientation and type of face to create
12877 bool reverse = false, isOnFace;
12880 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12881 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12883 F = e2f->second.Oriented( TopAbs_FORWARD );
12884 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12885 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12886 reverse = !reverse, F.Reverse();
12887 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12888 reverse = !reverse;
12890 else if ( !data._ignoreFaceIds.count( e2f->first ))
12892 // find FACE with layers sharing E
12893 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12895 F = *( fIt->next() );
12897 // Find the sub-mesh to add new faces
12898 SMESHDS_SubMesh* sm = 0;
12900 sm = getMeshDS()->MeshElements( F );
12902 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12904 return error("error in addBoundaryElements()", data._index);
12906 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12907 // faces for 3D meshing (PAL23414)
12908 SMESHDS_SubMesh* adjSM = 0;
12911 const TGeomID faceID = sm->GetID();
12912 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12913 while ( const TopoDS_Shape* solid = soIt->next() )
12914 if ( !solid->IsSame( data._solid ))
12916 size_t iData = _solids.FindIndex( *solid ) - 1;
12917 if ( iData < _sdVec.size() &&
12918 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12919 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12921 SMESH_ProxyMesh::SubMesh* proxySub =
12922 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12923 if ( proxySub && proxySub->NbElements() > 0 )
12930 const int dj1 = reverse ? 0 : 1;
12931 const int dj2 = reverse ? 1 : 0;
12932 vector< const SMDS_MeshElement*> ff; // new faces row
12933 SMESHDS_Mesh* m = getMeshDS();
12934 for ( size_t j = 1; j < ledges.size(); ++j )
12936 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
12937 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
12938 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12939 if ( nn1.size() == nn2.size() )
12942 for ( size_t z = 1; z < nn1.size(); ++z )
12943 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12945 for ( size_t z = 1; z < nn1.size(); ++z )
12946 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12948 else if ( nn1.size() == 1 )
12951 for ( size_t z = 1; z < nn2.size(); ++z )
12952 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12954 for ( size_t z = 1; z < nn2.size(); ++z )
12955 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12960 for ( size_t z = 1; z < nn1.size(); ++z )
12961 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12963 for ( size_t z = 1; z < nn1.size(); ++z )
12964 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12967 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12969 for ( size_t z = 0; z < ff.size(); ++z )
12971 adjSM->AddElement( ff[ z ]);
12977 for ( int isFirst = 0; isFirst < 2; ++isFirst )
12979 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12980 _EdgesOnShape* eos = data.GetShapeEdges( edge );
12981 if ( eos && eos->SWOLType() == TopAbs_EDGE )
12983 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
12984 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12986 helper.SetSubShape( eos->_sWOL );
12987 helper.SetElementsOnShape( true );
12988 for ( size_t z = 1; z < nn.size(); ++z )
12989 helper.AddEdge( nn[z-1], nn[z] );
12993 } // loop on EDGE's
12994 } // loop on _SolidData's