1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
109 //================================================================================
114 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
116 const double theMinSmoothCosin = 0.1;
117 const double theSmoothThickToElemSizeRatio = 0.3;
118 const double theMinSmoothTriaAngle = 30;
119 const double theMinSmoothQuadAngle = 45;
121 // what part of thickness is allowed till intersection
122 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123 const double theThickToIntersection = 1.5;
125 bool needSmoothing( double cosin, double tgtThick, double elemSize )
127 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
129 double getSmoothingThickness( double cosin, double elemSize )
131 return theSmoothThickToElemSizeRatio * elemSize / cosin;
135 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
138 struct _MeshOfSolid : public SMESH_ProxyMesh,
139 public SMESH_subMeshEventListenerData
141 bool _n2nMapComputed;
142 SMESH_ComputeErrorPtr _warning;
144 _MeshOfSolid( SMESH_Mesh* mesh)
145 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
147 SMESH_ProxyMesh::setMesh( *mesh );
150 // returns submesh for a geom face
151 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
153 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
156 void setNode2Node(const SMDS_MeshNode* srcNode,
157 const SMDS_MeshNode* proxyNode,
158 const SMESH_ProxyMesh::SubMesh* subMesh)
160 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
163 //--------------------------------------------------------------------------------
165 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166 * It is used to clear an inferior dim sub-meshes modified by viscous layers
168 class _ShrinkShapeListener : SMESH_subMeshEventListener
170 _ShrinkShapeListener()
171 : SMESH_subMeshEventListener(/*isDeletable=*/false,
172 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
174 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175 virtual void ProcessEvent(const int event,
177 SMESH_subMesh* solidSM,
178 SMESH_subMeshEventListenerData* data,
179 const SMESH_Hypothesis* hyp)
181 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
183 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
187 //--------------------------------------------------------------------------------
189 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191 * delete the data as soon as it has been used
193 class _ViscousListener : SMESH_subMeshEventListener
196 SMESH_subMeshEventListener(/*isDeletable=*/false,
197 "StdMeshers_ViscousLayers::_ViscousListener") {}
198 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
200 virtual void ProcessEvent(const int event,
202 SMESH_subMesh* subMesh,
203 SMESH_subMeshEventListenerData* data,
204 const SMESH_Hypothesis* hyp)
206 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
207 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208 SMESH_subMesh::SUBMESH_COMPUTED != event ))
210 // delete SMESH_ProxyMesh containing temporary faces
211 subMesh->DeleteEventListener( this );
214 // Finds or creates proxy mesh of the solid
215 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
216 const TopoDS_Shape& solid,
219 if ( !mesh ) return 0;
220 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222 if ( !data && toCreate )
224 data = new _MeshOfSolid(mesh);
225 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226 sm->SetEventListener( Get(), data, sm );
230 // Removes proxy mesh of the solid
231 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
233 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
237 //================================================================================
239 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240 * the main shape when sub-mesh of the main shape is cleared,
241 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
244 //================================================================================
246 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
248 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249 SMESH_subMeshEventListenerData* data =
250 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
253 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254 data->mySubMeshes.end())
255 data->mySubMeshes.push_back( sub );
259 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
264 //--------------------------------------------------------------------------------
266 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268 * The class is used to check validity of face or volumes around a smoothed node;
269 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
273 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275 _Simplex(const SMDS_MeshNode* nPrev=0,
276 const SMDS_MeshNode* nNext=0,
277 const SMDS_MeshNode* nOpp=0)
278 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
281 const double M[3][3] =
282 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285 vol = ( + M[0][0] * M[1][1] * M[2][2]
286 + M[0][1] * M[1][2] * M[2][0]
287 + M[0][2] * M[1][0] * M[2][1]
288 - M[0][0] * M[1][2] * M[2][1]
289 - M[0][1] * M[1][0] * M[2][2]
290 - M[0][2] * M[1][1] * M[2][0]);
293 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
295 SMESH_TNodeXYZ pSrc( nSrc );
296 return IsForward( &pSrc, &pTgt, vol );
298 bool IsForward(const gp_XY& tgtUV,
299 const SMDS_MeshNode* smoothedNode,
300 const TopoDS_Face& face,
301 SMESH_MesherHelper& helper,
302 const double refSign) const
304 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
308 return d*refSign > 1e-100;
310 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
312 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313 if ( !_nOpp ) // triangle
315 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316 double tp2 = tp.SquareMagnitude();
317 double pn2 = pn.SquareMagnitude();
318 double nt2 = nt.SquareMagnitude();
320 if ( tp2 < pn2 && tp2 < nt2 )
321 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322 else if ( pn2 < nt2 )
323 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
325 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
327 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329 return minAngle < theMaxCos2;
333 SMESH_TNodeXYZ pOpp( _nOpp );
334 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335 double tp2 = tp.SquareMagnitude();
336 double po2 = po.SquareMagnitude();
337 double on2 = on.SquareMagnitude();
338 double nt2 = nt.SquareMagnitude();
339 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
344 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346 return minAngle < theMaxCos2;
349 bool IsNeighbour(const _Simplex& other) const
351 return _nPrev == other._nNext || _nNext == other._nPrev;
353 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354 static void GetSimplices( const SMDS_MeshNode* node,
355 vector<_Simplex>& simplices,
356 const set<TGeomID>& ingnoreShapes,
357 const _SolidData* dataToCheckOri = 0,
358 const bool toSort = false);
359 static void SortSimplices(vector<_Simplex>& simplices);
361 //--------------------------------------------------------------------------------
363 * Structure used to take into account surface curvature while smoothing
368 double _k; // factor to correct node smoothed position
369 double _h2lenRatio; // avgNormProj / (2*avgDist)
370 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
372 static _Curvature* New( double avgNormProj, double avgDist )
375 if ( fabs( avgNormProj / avgDist ) > 1./200 )
378 c->_r = avgDist * avgDist / avgNormProj;
379 c->_k = avgDist * avgDist / c->_r / c->_r;
380 //c->_k = avgNormProj / c->_r;
381 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
384 c->_uv.SetCoord( 0., 0. );
388 double lenDelta(double len) const { return _k * ( _r + len ); }
389 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
391 //--------------------------------------------------------------------------------
395 struct _EdgesOnShape;
397 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
399 //--------------------------------------------------------------------------------
401 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402 * and a node of the most internal layer (_nodes.back())
406 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
408 vector< const SMDS_MeshNode*> _nodes;
410 gp_XYZ _normal; // to boundary of solid
411 vector<gp_XYZ> _pos; // points computed during inflation
412 double _len; // length achived with the last inflation step
413 double _maxLen; // maximal possible length
414 double _cosin; // of angle (_normal ^ surface)
415 double _minAngle; // of _simplices
416 double _lenFactor; // to compute _len taking _cosin into account
419 // simplices connected to the source node (_nodes[0]);
420 // used for smoothing and quality check of _LayerEdge's based on the FACE
421 vector<_Simplex> _simplices;
422 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423 PSmooFun _smooFunction; // smoothing function
424 _Curvature* _curvature;
425 // data for smoothing of _LayerEdge's based on the EDGE
426 _2NearEdges* _2neibors;
428 enum EFlags { TO_SMOOTH = 0x0000001,
429 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
430 SMOOTHED = 0x0000004, // set by this->Smooth()
431 DIFFICULT = 0x0000008, // near concave VERTEX
432 ON_CONCAVE_FACE = 0x0000010,
433 BLOCKED = 0x0000020, // not to inflate any more
434 INTERSECTED = 0x0000040, // close intersection with a face found
435 NORMAL_UPDATED = 0x0000080,
436 MARKED = 0x0000100, // local usage
437 MULTI_NORMAL = 0x0000200, // a normal is invisible by some of surrounding faces
438 NEAR_BOUNDARY = 0x0000400, // is near FACE boundary forcing smooth
439 SMOOTHED_C1 = 0x0000800, // is on _eosC1
440 DISTORTED = 0x0001000, // was bad before smoothing
441 RISKY_SWOL = 0x0002000, // SWOL is parallel to a source FACE
442 SHRUNK = 0x0004000, // target node reached a tgt position while shrink()
443 UNUSED_FLAG = 0x0100000
445 bool Is ( int flag ) const { return _flags & flag; }
446 void Set ( int flag ) { _flags |= flag; }
447 void Unset( int flag ) { _flags &= ~flag; }
449 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
450 bool SetNewLength2d( Handle(Geom_Surface)& surface,
451 const TopoDS_Face& F,
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 ) const;
500 bool IsOnEdge() const { return _2neibors; }
501 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
502 void SetCosin( double cosin );
503 void SetNormal( const gp_XYZ& n ) { _normal = n; }
504 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
505 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
506 void SetSmooLen( double len ) { // set _len at which smoothing is needed
507 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
509 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
511 gp_XYZ smoothLaplacian();
512 gp_XYZ smoothAngular();
513 gp_XYZ smoothLengthWeighted();
514 gp_XYZ smoothCentroidal();
515 gp_XYZ smoothNefPolygon();
517 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
518 static const int theNbSmooFuns = FUN_NB;
519 static PSmooFun _funs[theNbSmooFuns];
520 static const char* _funNames[theNbSmooFuns+1];
521 int smooFunID( PSmooFun fun=0) const;
523 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
524 &_LayerEdge::smoothLengthWeighted,
525 &_LayerEdge::smoothCentroidal,
526 &_LayerEdge::smoothNefPolygon,
527 &_LayerEdge::smoothAngular };
528 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
536 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
538 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
539 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
542 //--------------------------------------------------------------------------------
544 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
548 gp_XY _pos, _dir, _inNorm;
549 bool IsOut( const gp_XY p, const double tol ) const
551 return _inNorm * ( p - _pos ) < -tol;
553 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
555 //const double eps = 1e-10;
556 double D = _dir.Crossed( hp._dir );
557 if ( fabs(D) < std::numeric_limits<double>::min())
559 gp_XY vec21 = _pos - hp._pos;
560 double u = hp._dir.Crossed( vec21 ) / D;
561 intPnt = _pos + _dir * u;
565 //--------------------------------------------------------------------------------
567 * Structure used to smooth a _LayerEdge based on an EDGE.
571 double _wgt [2]; // weights of _nodes
572 _LayerEdge* _edges[2];
574 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
577 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
578 const SMDS_MeshNode* tgtNode(bool is2nd) {
579 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
581 const SMDS_MeshNode* srcNode(bool is2nd) {
582 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
585 std::swap( _wgt [0], _wgt [1] );
586 std::swap( _edges[0], _edges[1] );
588 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
589 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
591 bool include( const _LayerEdge* e ) {
592 return ( _edges[0] == e || _edges[1] == e );
597 //--------------------------------------------------------------------------------
599 * \brief Layers parameters got by averaging several hypotheses
603 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
604 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
608 void Add( const StdMeshers_ViscousLayers* hyp )
613 _nbLayers = hyp->GetNumberLayers();
614 //_thickness += hyp->GetTotalThickness();
615 _thickness = Max( _thickness, hyp->GetTotalThickness() );
616 _stretchFactor += hyp->GetStretchFactor();
617 _method = hyp->GetMethod();
620 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
621 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
622 int GetNumberLayers() const { return _nbLayers; }
623 int GetMethod() const { return _method; }
625 bool UseSurfaceNormal() const
626 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
627 bool ToSmooth() const
628 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
629 bool IsOffsetMethod() const
630 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
633 int _nbLayers, _nbHyps, _method;
634 double _thickness, _stretchFactor;
637 //--------------------------------------------------------------------------------
639 * \brief _LayerEdge's on a shape and other shape data
643 vector< _LayerEdge* > _edges;
647 SMESH_subMesh * _subMesh;
648 // face or edge w/o layer along or near which _edges are inflated
650 bool _isRegularSWOL; // w/o singularities
651 // averaged StdMeshers_ViscousLayers parameters
654 _Smoother1D* _edgeSmoother;
655 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
656 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
658 vector< gp_XYZ > _faceNormals; // if _shape is FACE
659 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
661 Handle(ShapeAnalysis_Surface) _offsetSurf;
662 _LayerEdge* _edgeForOffset;
664 _SolidData* _data; // parent SOLID
666 TopAbs_ShapeEnum ShapeType() const
667 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
668 TopAbs_ShapeEnum SWOLType() const
669 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
670 bool HasC1( const _EdgesOnShape* other ) const
671 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
672 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
673 _SolidData& GetData() const { return *_data; }
675 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
678 //--------------------------------------------------------------------------------
680 * \brief Convex FACE whose radius of curvature is less than the thickness of
681 * layers. It is used to detect distortion of prisms based on a convex
682 * FACE and to update normals to enable further increasing the thickness
688 // edges whose _simplices are used to detect prism distortion
689 vector< _LayerEdge* > _simplexTestEdges;
691 // map a sub-shape to _SolidData::_edgesOnShape
692 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
696 bool GetCenterOfCurvature( _LayerEdge* ledge,
697 BRepLProp_SLProps& surfProp,
698 SMESH_MesherHelper& helper,
699 gp_Pnt & center ) const;
700 bool CheckPrisms() const;
703 //--------------------------------------------------------------------------------
705 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
706 * at inflation up to the full thickness. A detected collision
707 * is fixed in updateNormals()
709 struct _CollisionEdges
712 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
713 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
714 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
717 //--------------------------------------------------------------------------------
719 * \brief Data of a SOLID
723 typedef const StdMeshers_ViscousLayers* THyp;
725 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
726 TGeomID _index; // SOLID id
727 _MeshOfSolid* _proxyMesh;
729 list< TopoDS_Shape > _hypShapes;
730 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
731 set< TGeomID > _reversedFaceIds;
732 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
734 double _stepSize, _stepSizeCoeff, _geomSize;
735 const SMDS_MeshNode* _stepSizeNodes[2];
737 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
739 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
740 map< TGeomID, TNode2Edge* > _s2neMap;
741 // _LayerEdge's with underlying shapes
742 vector< _EdgesOnShape > _edgesOnShape;
744 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
745 // layers and a FACE w/o layers
746 // value: the shape (FACE or EDGE) to shrink mesh on.
747 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
748 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
750 // Convex FACEs whose radius of curvature is less than the thickness of layers
751 map< TGeomID, _ConvexFace > _convexFaces;
753 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
754 // the adjacent SOLID
755 set< TGeomID > _noShrinkShapes;
757 int _nbShapesToSmooth;
759 //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
761 vector< _CollisionEdges > _collisionEdges;
762 set< TGeomID > _concaveFaces;
764 double _maxThickness; // of all _hyps
765 double _minThickness; // of all _hyps
767 double _epsilon; // precision for SegTriaInter()
769 SMESH_MesherHelper* _helper;
771 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
773 :_solid(s), _proxyMesh(m), _helper(0) {}
776 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
777 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
779 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
780 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
781 return id2face == _convexFaces.end() ? 0 : & id2face->second;
783 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
784 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
785 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
786 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
788 SMESH_MesherHelper& GetHelper() const { return *_helper; }
790 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
791 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
792 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
793 _edgesOnShape[i]._edges[j]->Unset( flag );
795 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
796 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
798 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
800 //--------------------------------------------------------------------------------
802 * \brief Offset plane used in getNormalByOffset()
808 int _faceIndexNext[2];
809 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
812 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
814 void ComputeIntersectionLine( _OffsetPlane& pln,
815 const TopoDS_Edge& E,
816 const TopoDS_Vertex& V );
817 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
818 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
820 //--------------------------------------------------------------------------------
822 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
824 struct _CentralCurveOnEdge
827 vector< gp_Pnt > _curvaCenters;
828 vector< _LayerEdge* > _ledges;
829 vector< gp_XYZ > _normals; // new normal for each of _ledges
830 vector< double > _segLength2;
833 TopoDS_Face _adjFace;
834 bool _adjFaceToSmooth;
836 void Append( const gp_Pnt& center, _LayerEdge* ledge )
838 if ( _curvaCenters.size() > 0 )
839 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
840 _curvaCenters.push_back( center );
841 _ledges.push_back( ledge );
842 _normals.push_back( ledge->_normal );
844 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
845 void SetShapes( const TopoDS_Edge& edge,
846 const _ConvexFace& convFace,
848 SMESH_MesherHelper& helper);
850 //--------------------------------------------------------------------------------
852 * \brief Data of node on a shrinked FACE
856 const SMDS_MeshNode* _node;
857 vector<_Simplex> _simplices; // for quality check
859 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
861 bool Smooth(int& badNb,
862 Handle(Geom_Surface)& surface,
863 SMESH_MesherHelper& helper,
864 const double refSign,
868 gp_XY computeAngularPos(vector<gp_XY>& uv,
869 const gp_XY& uvToFix,
870 const double refSign );
872 //--------------------------------------------------------------------------------
874 * \brief Builder of viscous layers
876 class _ViscousBuilder
881 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
882 const TopoDS_Shape& shape);
883 // check validity of hypotheses
884 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
885 const TopoDS_Shape& shape );
887 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
888 void RestoreListeners();
890 // computes SMESH_ProxyMesh::SubMesh::_n2n;
891 bool MakeN2NMap( _MeshOfSolid* pm );
895 bool findSolidsWithLayers();
896 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
897 bool findFacesWithLayers(const bool onlyWith=false);
898 void getIgnoreFaces(const TopoDS_Shape& solid,
899 const StdMeshers_ViscousLayers* hyp,
900 const TopoDS_Shape& hypShape,
901 set<TGeomID>& ignoreFaces);
902 bool makeLayer(_SolidData& data);
903 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
904 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
905 SMESH_MesherHelper& helper, _SolidData& data);
906 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
907 const TopoDS_Face& face,
908 SMESH_MesherHelper& helper,
910 bool shiftInside=false);
911 bool getFaceNormalAtSingularity(const gp_XY& uv,
912 const TopoDS_Face& face,
913 SMESH_MesherHelper& helper,
915 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
916 gp_XYZ getNormalByOffset( _LayerEdge* edge,
917 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
919 bool lastNoOffset = false);
920 bool findNeiborsOnEdge(const _LayerEdge* edge,
921 const SMDS_MeshNode*& n1,
922 const SMDS_MeshNode*& n2,
925 void findSimplexTestEdges( _SolidData& data,
926 vector< vector<_LayerEdge*> >& edgesByGeom);
927 void computeGeomSize( _SolidData& data );
928 bool findShapesToSmooth( _SolidData& data);
929 void limitStepSizeByCurvature( _SolidData& data );
930 void limitStepSize( _SolidData& data,
931 const SMDS_MeshElement* face,
932 const _LayerEdge* maxCosinEdge );
933 void limitStepSize( _SolidData& data, const double minSize);
934 bool inflate(_SolidData& data);
935 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
936 int invalidateBadSmooth( _SolidData& data,
937 SMESH_MesherHelper& helper,
938 vector< _LayerEdge* >& badSmooEdges,
939 vector< _EdgesOnShape* >& eosC1,
941 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
942 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
943 vector< _EdgesOnShape* >& eosC1,
944 int smooStep=0, bool moveAll=false );
945 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
946 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
947 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
948 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
949 SMESH_MesherHelper& helper );
950 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
951 bool updateNormalsOfConvexFaces( _SolidData& data,
952 SMESH_MesherHelper& helper,
954 void updateNormalsOfC1Vertices( _SolidData& data );
955 bool updateNormalsOfSmoothed( _SolidData& data,
956 SMESH_MesherHelper& helper,
958 const double stepSize );
959 bool isNewNormalOk( _SolidData& data,
961 const gp_XYZ& newNormal);
962 bool refine(_SolidData& data);
963 bool shrink(_SolidData& data);
964 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
965 SMESH_MesherHelper& helper,
966 const SMESHDS_SubMesh* faceSubMesh );
967 void restoreNoShrink( _LayerEdge& edge ) const;
968 void fixBadFaces(const TopoDS_Face& F,
969 SMESH_MesherHelper& helper,
972 set<const SMDS_MeshNode*> * involvedNodes=NULL);
973 bool addBoundaryElements(_SolidData& data);
975 bool error( const string& text, int solidID=-1 );
976 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
979 void makeGroupOfLE();
982 SMESH_ComputeErrorPtr _error;
984 vector< _SolidData > _sdVec;
985 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
986 TopTools_MapOfShape _shrinkedFaces;
990 //--------------------------------------------------------------------------------
992 * \brief Shrinker of nodes on the EDGE
996 TopoDS_Edge _geomEdge;
997 vector<double> _initU;
998 vector<double> _normPar;
999 vector<const SMDS_MeshNode*> _nodes;
1000 const _LayerEdge* _edges[2];
1003 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1004 void Compute(bool set3D, SMESH_MesherHelper& helper);
1005 void RestoreParams();
1006 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1007 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1008 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1009 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1010 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1011 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1013 //--------------------------------------------------------------------------------
1015 * \brief Smoother of _LayerEdge's on EDGE.
1019 struct OffPnt // point of the offsetted EDGE
1021 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1022 double _len; // length reached at previous inflation step
1023 double _param; // on EDGE
1024 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1025 gp_XYZ _edgeDir;// EDGE tangent at _param
1026 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1028 vector< OffPnt > _offPoints;
1029 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1030 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1031 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1032 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1033 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1034 _EdgesOnShape& _eos;
1035 double _curveLen; // length of the EDGE
1037 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1039 SMESH_MesherHelper& helper);
1041 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1042 _EdgesOnShape& eos )
1043 : _anaCurve( curveForSmooth ), _eos( eos )
1046 bool Perform(_SolidData& data,
1047 Handle(ShapeAnalysis_Surface)& surface,
1048 const TopoDS_Face& F,
1049 SMESH_MesherHelper& helper )
1051 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1055 return smoothAnalyticEdge( data, surface, F, helper );
1057 return smoothComplexEdge ( data, surface, F, helper );
1059 void prepare(_SolidData& data );
1061 bool smoothAnalyticEdge( _SolidData& data,
1062 Handle(ShapeAnalysis_Surface)& surface,
1063 const TopoDS_Face& F,
1064 SMESH_MesherHelper& helper);
1066 bool smoothComplexEdge( _SolidData& data,
1067 Handle(ShapeAnalysis_Surface)& surface,
1068 const TopoDS_Face& F,
1069 SMESH_MesherHelper& helper);
1071 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1072 const gp_XYZ& edgeDir);
1074 _LayerEdge* getLEdgeOnV( bool is2nd )
1076 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1078 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1080 //--------------------------------------------------------------------------------
1082 * \brief Class of temporary mesh face.
1083 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1084 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1086 struct _TmpMeshFace : public SMDS_MeshElement
1088 vector<const SMDS_MeshNode* > _nn;
1089 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1090 int id, int faceID=-1, int idInFace=-1):
1091 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1092 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1093 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1094 virtual vtkIdType GetVtkType() const { return -1; }
1095 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1096 virtual SMDSAbs_GeometryType GetGeomType() const
1097 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1098 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1099 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1101 //--------------------------------------------------------------------------------
1103 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1105 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1107 _LayerEdge *_le1, *_le2;
1108 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1109 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1111 _nn[0]=_le1->_nodes[0];
1112 _nn[1]=_le1->_nodes.back();
1113 _nn[2]=_le2->_nodes.back();
1114 _nn[3]=_le2->_nodes[0];
1116 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1118 SMESH_TNodeXYZ p0s( _nn[0] );
1119 SMESH_TNodeXYZ p0t( _nn[1] );
1120 SMESH_TNodeXYZ p1t( _nn[2] );
1121 SMESH_TNodeXYZ p1s( _nn[3] );
1122 gp_XYZ v0 = p0t - p0s;
1123 gp_XYZ v1 = p1t - p1s;
1124 gp_XYZ v01 = p1s - p0s;
1125 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1130 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1132 _nn[0]=le1->_nodes[0];
1133 _nn[1]=le1->_nodes.back();
1134 _nn[2]=le2->_nodes.back();
1135 _nn[3]=le2->_nodes[0];
1139 //--------------------------------------------------------------------------------
1141 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1142 * \warning Location of a surface is ignored
1144 struct _NodeCoordHelper
1146 SMESH_MesherHelper& _helper;
1147 const TopoDS_Face& _face;
1148 Handle(Geom_Surface) _surface;
1149 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1151 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1152 : _helper( helper ), _face( F )
1156 TopLoc_Location loc;
1157 _surface = BRep_Tool::Surface( _face, loc );
1159 if ( _surface.IsNull() )
1160 _fun = & _NodeCoordHelper::direct;
1162 _fun = & _NodeCoordHelper::byUV;
1164 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1167 gp_XYZ direct(const SMDS_MeshNode* n) const
1169 return SMESH_TNodeXYZ( n );
1171 gp_XYZ byUV (const SMDS_MeshNode* n) const
1173 gp_XY uv = _helper.GetNodeUV( _face, n );
1174 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1178 //================================================================================
1180 * \brief Check angle between vectors
1182 //================================================================================
1184 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1186 double dot = v1 * v2; // cos * |v1| * |v2|
1187 double l1 = v1.SquareMagnitude();
1188 double l2 = v2.SquareMagnitude();
1189 return (( dot * cos >= 0 ) &&
1190 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1193 } // namespace VISCOUS_3D
1197 //================================================================================
1198 // StdMeshers_ViscousLayers hypothesis
1200 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1201 :SMESH_Hypothesis(hypId, studyId, gen),
1202 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1203 _method( SURF_OFFSET_SMOOTH )
1205 _name = StdMeshers_ViscousLayers::GetHypType();
1206 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1207 } // --------------------------------------------------------------------------------
1208 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1210 if ( faceIds != _shapeIds )
1211 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1212 if ( _isToIgnoreShapes != toIgnore )
1213 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1214 } // --------------------------------------------------------------------------------
1215 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1217 if ( thickness != _thickness )
1218 _thickness = thickness, NotifySubMeshesHypothesisModification();
1219 } // --------------------------------------------------------------------------------
1220 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1222 if ( _nbLayers != nb )
1223 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1224 } // --------------------------------------------------------------------------------
1225 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1227 if ( _stretchFactor != factor )
1228 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1229 } // --------------------------------------------------------------------------------
1230 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1232 if ( _method != method )
1233 _method = method, NotifySubMeshesHypothesisModification();
1234 } // --------------------------------------------------------------------------------
1235 SMESH_ProxyMesh::Ptr
1236 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1237 const TopoDS_Shape& theShape,
1238 const bool toMakeN2NMap) const
1240 using namespace VISCOUS_3D;
1241 _ViscousBuilder builder;
1242 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1243 if ( err && !err->IsOK() )
1244 return SMESH_ProxyMesh::Ptr();
1246 vector<SMESH_ProxyMesh::Ptr> components;
1247 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1248 for ( ; exp.More(); exp.Next() )
1250 if ( _MeshOfSolid* pm =
1251 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1253 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1254 if ( !builder.MakeN2NMap( pm ))
1255 return SMESH_ProxyMesh::Ptr();
1256 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1257 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1259 if ( pm->_warning && !pm->_warning->IsOK() )
1261 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1262 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1263 if ( !smError || smError->IsOK() )
1264 smError = pm->_warning;
1267 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1269 switch ( components.size() )
1273 case 1: return components[0];
1275 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1277 return SMESH_ProxyMesh::Ptr();
1278 } // --------------------------------------------------------------------------------
1279 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1281 save << " " << _nbLayers
1282 << " " << _thickness
1283 << " " << _stretchFactor
1284 << " " << _shapeIds.size();
1285 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1286 save << " " << _shapeIds[i];
1287 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1288 save << " " << _method;
1290 } // --------------------------------------------------------------------------------
1291 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1293 int nbFaces, faceID, shapeToTreat, method;
1294 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1295 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1296 _shapeIds.push_back( faceID );
1297 if ( load >> shapeToTreat ) {
1298 _isToIgnoreShapes = !shapeToTreat;
1299 if ( load >> method )
1300 _method = (ExtrusionMethod) method;
1303 _isToIgnoreShapes = true; // old behavior
1306 } // --------------------------------------------------------------------------------
1307 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1308 const TopoDS_Shape& theShape)
1312 } // --------------------------------------------------------------------------------
1313 SMESH_ComputeErrorPtr
1314 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1315 const TopoDS_Shape& theShape,
1316 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1318 VISCOUS_3D::_ViscousBuilder builder;
1319 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1320 if ( err && !err->IsOK() )
1321 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1323 theStatus = SMESH_Hypothesis::HYP_OK;
1327 // --------------------------------------------------------------------------------
1328 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1331 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1332 return IsToIgnoreShapes() ? !isIn : isIn;
1334 // END StdMeshers_ViscousLayers hypothesis
1335 //================================================================================
1337 namespace VISCOUS_3D
1339 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1343 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1344 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1345 gp_Pnt p = BRep_Tool::Pnt( fromV );
1346 double distF = p.SquareDistance( c->Value( f ));
1347 double distL = p.SquareDistance( c->Value( l ));
1348 c->D1(( distF < distL ? f : l), p, dir );
1349 if ( distL < distF ) dir.Reverse();
1352 //--------------------------------------------------------------------------------
1353 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1354 SMESH_MesherHelper& helper)
1357 double f,l; gp_Pnt p;
1358 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1359 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1360 double u = helper.GetNodeU( E, atNode );
1364 //--------------------------------------------------------------------------------
1365 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1366 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1368 //--------------------------------------------------------------------------------
1369 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1370 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1373 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1376 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1377 return getFaceDir( F, v, node, helper, ok );
1379 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1380 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1381 gp_Pnt p; gp_Vec du, dv, norm;
1382 surface->D1( uv.X(),uv.Y(), p, du,dv );
1385 double u = helper.GetNodeU( fromE, node, 0, &ok );
1387 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1388 if ( o == TopAbs_REVERSED )
1391 gp_Vec dir = norm ^ du;
1393 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1394 helper.IsClosedEdge( fromE ))
1396 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1397 else c->D1( f, p, dv );
1398 if ( o == TopAbs_REVERSED )
1400 gp_Vec dir2 = norm ^ dv;
1401 dir = dir.Normalized() + dir2.Normalized();
1405 //--------------------------------------------------------------------------------
1406 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1407 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1408 bool& ok, double* cosin)
1410 TopoDS_Face faceFrw = F;
1411 faceFrw.Orientation( TopAbs_FORWARD );
1412 //double f,l; TopLoc_Location loc;
1413 TopoDS_Edge edges[2]; // sharing a vertex
1416 TopoDS_Vertex VV[2];
1417 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1418 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1420 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1421 if ( SMESH_Algo::isDegenerated( e )) continue;
1422 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1423 if ( VV[1].IsSame( fromV )) {
1424 nbEdges += edges[ 0 ].IsNull();
1427 else if ( VV[0].IsSame( fromV )) {
1428 nbEdges += edges[ 1 ].IsNull();
1433 gp_XYZ dir(0,0,0), edgeDir[2];
1436 // get dirs of edges going fromV
1438 for ( size_t i = 0; i < nbEdges && ok; ++i )
1440 edgeDir[i] = getEdgeDir( edges[i], fromV );
1441 double size2 = edgeDir[i].SquareModulus();
1442 if (( ok = size2 > numeric_limits<double>::min() ))
1443 edgeDir[i] /= sqrt( size2 );
1445 if ( !ok ) return dir;
1447 // get angle between the 2 edges
1449 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1450 if ( Abs( angle ) < 5 * M_PI/180 )
1452 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1456 dir = edgeDir[0] + edgeDir[1];
1461 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1462 *cosin = Cos( angle );
1465 else if ( nbEdges == 1 )
1467 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1468 if ( cosin ) *cosin = 1.;
1478 //================================================================================
1480 * \brief Finds concave VERTEXes of a FACE
1482 //================================================================================
1484 bool getConcaveVertices( const TopoDS_Face& F,
1485 SMESH_MesherHelper& helper,
1486 set< TGeomID >* vertices = 0)
1488 // check angles at VERTEXes
1490 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1491 for ( size_t iW = 0; iW < wires.size(); ++iW )
1493 const int nbEdges = wires[iW]->NbEdges();
1494 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1496 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1498 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1499 int iE2 = ( iE1 + 1 ) % nbEdges;
1500 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1501 iE2 = ( iE2 + 1 ) % nbEdges;
1502 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1503 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1504 wires[iW]->Edge( iE2 ), F, V );
1505 if ( angle < -5. * M_PI / 180. )
1509 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1513 return vertices ? !vertices->empty() : false;
1516 //================================================================================
1518 * \brief Returns true if a FACE is bound by a concave EDGE
1520 //================================================================================
1522 bool isConcave( const TopoDS_Face& F,
1523 SMESH_MesherHelper& helper,
1524 set< TGeomID >* vertices = 0 )
1526 bool isConcv = false;
1527 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1529 gp_Vec2d drv1, drv2;
1531 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1532 for ( ; eExp.More(); eExp.Next() )
1534 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1535 if ( SMESH_Algo::isDegenerated( E )) continue;
1536 // check if 2D curve is concave
1537 BRepAdaptor_Curve2d curve( E, F );
1538 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1539 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1540 curve.Intervals( intervals, GeomAbs_C2 );
1541 bool isConvex = true;
1542 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1544 double u1 = intervals( i );
1545 double u2 = intervals( i+1 );
1546 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1547 double cross = drv1 ^ drv2;
1548 if ( E.Orientation() == TopAbs_REVERSED )
1550 isConvex = ( cross > -1e-9 ); // 0.1 );
1554 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1563 // check angles at VERTEXes
1564 if ( getConcaveVertices( F, helper, vertices ))
1570 //================================================================================
1572 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1573 * \param [in] face - the mesh face to treat
1574 * \param [in] nodeOnEdge - a node on the EDGE
1575 * \param [out] faceSize - the computed distance
1576 * \return bool - true if faceSize computed
1578 //================================================================================
1580 bool getDistFromEdge( const SMDS_MeshElement* face,
1581 const SMDS_MeshNode* nodeOnEdge,
1584 faceSize = Precision::Infinite();
1587 int nbN = face->NbCornerNodes();
1588 int iOnE = face->GetNodeIndex( nodeOnEdge );
1589 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1590 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1591 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1592 face->GetNode( iNext[1] ) };
1593 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1594 double segLen = -1.;
1595 // look for two neighbor not in-FACE nodes of face
1596 for ( int i = 0; i < 2; ++i )
1598 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1599 nNext[i]->GetID() < nodeOnEdge->GetID() )
1601 // look for an in-FACE node
1602 for ( int iN = 0; iN < nbN; ++iN )
1604 if ( iN == iOnE || iN == iNext[i] )
1606 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1607 gp_XYZ v = pInFace - segEnd;
1610 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1611 segLen = segVec.Modulus();
1613 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1614 faceSize = Min( faceSize, distToSeg );
1622 //================================================================================
1624 * \brief Return direction of axis or revolution of a surface
1626 //================================================================================
1628 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1631 switch ( surface.GetType() ) {
1634 gp_Cone cone = surface.Cone();
1635 axis = cone.Axis().Direction();
1638 case GeomAbs_Sphere:
1640 gp_Sphere sphere = surface.Sphere();
1641 axis = sphere.Position().Direction();
1644 case GeomAbs_SurfaceOfRevolution:
1646 axis = surface.AxeOfRevolution().Direction();
1649 //case GeomAbs_SurfaceOfExtrusion:
1650 case GeomAbs_OffsetSurface:
1652 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1653 return getRovolutionAxis( base->Surface(), axis );
1655 default: return false;
1660 //--------------------------------------------------------------------------------
1661 // DEBUG. Dump intermediate node positions into a python script
1662 // HOWTO use: run python commands written in a console to see
1663 // construction steps of viscous layers
1668 PyDump(SMESH_Mesh& m) {
1669 int tag = 3 + m.GetId();
1670 const char* fname = "/tmp/viscous.py";
1671 cout << "execfile('"<<fname<<"')"<<endl;
1672 py = new ofstream(fname);
1673 *py << "import SMESH" << endl
1674 << "from salome.smesh import smeshBuilder" << endl
1675 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1676 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1677 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1682 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1683 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1684 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1685 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1689 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1691 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1692 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1693 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1694 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1695 void _dumpFunction(const string& fun, int ln)
1696 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1697 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1698 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1699 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1700 void _dumpCmd(const string& txt, int ln)
1701 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1702 void dumpFunctionEnd()
1703 { if (py) *py<< " return"<< endl; }
1704 void dumpChangeNodes( const SMDS_MeshElement* f )
1705 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1706 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1707 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1708 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1712 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1713 #define dumpFunction(f) f
1715 #define dumpMoveComm(n,txt)
1716 #define dumpCmd(txt)
1717 #define dumpFunctionEnd()
1718 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1719 #define debugMsg( txt ) {}
1724 using namespace VISCOUS_3D;
1726 //================================================================================
1728 * \brief Constructor of _ViscousBuilder
1730 //================================================================================
1732 _ViscousBuilder::_ViscousBuilder()
1734 _error = SMESH_ComputeError::New(COMPERR_OK);
1738 //================================================================================
1740 * \brief Stores error description and returns false
1742 //================================================================================
1744 bool _ViscousBuilder::error(const string& text, int solidId )
1746 const string prefix = string("Viscous layers builder: ");
1747 _error->myName = COMPERR_ALGO_FAILED;
1748 _error->myComment = prefix + text;
1751 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1752 if ( !sm && !_sdVec.empty() )
1753 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1754 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1756 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1757 if ( smError && smError->myAlgo )
1758 _error->myAlgo = smError->myAlgo;
1760 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1762 // set KO to all solids
1763 for ( size_t i = 0; i < _sdVec.size(); ++i )
1765 if ( _sdVec[i]._index == solidId )
1767 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1768 if ( !sm->IsEmpty() )
1770 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1771 if ( !smError || smError->IsOK() )
1773 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1774 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1778 makeGroupOfLE(); // debug
1783 //================================================================================
1785 * \brief At study restoration, restore event listeners used to clear an inferior
1786 * dim sub-mesh modified by viscous layers
1788 //================================================================================
1790 void _ViscousBuilder::RestoreListeners()
1795 //================================================================================
1797 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1799 //================================================================================
1801 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1803 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1804 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1805 for ( ; fExp.More(); fExp.Next() )
1807 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1808 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1810 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1812 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1815 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1816 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1818 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1819 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1820 while( prxIt->more() )
1822 const SMDS_MeshElement* fSrc = srcIt->next();
1823 const SMDS_MeshElement* fPrx = prxIt->next();
1824 if ( fSrc->NbNodes() != fPrx->NbNodes())
1825 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1826 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1827 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1830 pm->_n2nMapComputed = true;
1834 //================================================================================
1836 * \brief Does its job
1838 //================================================================================
1840 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1841 const TopoDS_Shape& theShape)
1845 // check if proxy mesh already computed
1846 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1848 return error("No SOLID's in theShape"), _error;
1850 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1851 return SMESH_ComputeErrorPtr(); // everything already computed
1853 PyDump debugDump( theMesh );
1855 // TODO: ignore already computed SOLIDs
1856 if ( !findSolidsWithLayers())
1859 if ( !findFacesWithLayers() )
1862 for ( size_t i = 0; i < _sdVec.size(); ++i )
1865 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1866 if ( _sdVec[iSD]._before.IsEmpty() &&
1867 _sdVec[iSD]._n2eMap.empty() )
1870 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1873 if ( _sdVec[iSD]._n2eMap.size() == 0 )
1876 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
1879 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
1882 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
1885 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1887 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1888 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1889 _sdVec[iSD]._before.Remove( solid );
1892 makeGroupOfLE(); // debug
1898 //================================================================================
1900 * \brief Check validity of hypotheses
1902 //================================================================================
1904 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1905 const TopoDS_Shape& shape )
1909 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1910 return SMESH_ComputeErrorPtr(); // everything already computed
1913 findSolidsWithLayers();
1914 bool ok = findFacesWithLayers( true );
1916 // remove _MeshOfSolid's of _SolidData's
1917 for ( size_t i = 0; i < _sdVec.size(); ++i )
1918 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1923 return SMESH_ComputeErrorPtr();
1926 //================================================================================
1928 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1930 //================================================================================
1932 bool _ViscousBuilder::findSolidsWithLayers()
1935 TopTools_IndexedMapOfShape allSolids;
1936 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1937 _sdVec.reserve( allSolids.Extent());
1939 SMESH_HypoFilter filter;
1940 for ( int i = 1; i <= allSolids.Extent(); ++i )
1942 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1943 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1944 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1945 continue; // solid is already meshed
1946 SMESH_Algo* algo = sm->GetAlgo();
1947 if ( !algo ) continue;
1948 // TODO: check if algo is hidden
1949 const list <const SMESHDS_Hypothesis *> & allHyps =
1950 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1951 _SolidData* soData = 0;
1952 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1953 const StdMeshers_ViscousLayers* viscHyp = 0;
1954 for ( ; hyp != allHyps.end(); ++hyp )
1955 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1957 TopoDS_Shape hypShape;
1958 filter.Init( filter.Is( viscHyp ));
1959 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1963 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1966 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1967 soData = & _sdVec.back();
1968 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1969 soData->_helper = new SMESH_MesherHelper( *_mesh );
1970 soData->_helper->SetSubShape( allSolids(i) );
1971 _solids.Add( allSolids(i) );
1973 soData->_hyps.push_back( viscHyp );
1974 soData->_hypShapes.push_back( hypShape );
1977 if ( _sdVec.empty() )
1979 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1984 //================================================================================
1986 * \brief Set a _SolidData to be computed before another
1988 //================================================================================
1990 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1992 // check possibility to set this order; get all solids before solidBefore
1993 TopTools_IndexedMapOfShape allSolidsBefore;
1994 allSolidsBefore.Add( solidBefore._solid );
1995 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1997 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2000 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2001 for ( ; soIt.More(); soIt.Next() )
2002 allSolidsBefore.Add( soIt.Value() );
2005 if ( allSolidsBefore.Contains( solidAfter._solid ))
2008 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2009 solidAfter._before.Add( allSolidsBefore(i) );
2014 //================================================================================
2018 //================================================================================
2020 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2022 SMESH_MesherHelper helper( *_mesh );
2023 TopExp_Explorer exp;
2025 // collect all faces-to-ignore defined by hyp
2026 for ( size_t i = 0; i < _sdVec.size(); ++i )
2028 // get faces-to-ignore defined by each hyp
2029 typedef const StdMeshers_ViscousLayers* THyp;
2030 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2031 list< TFacesOfHyp > ignoreFacesOfHyps;
2032 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2033 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2034 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2036 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2037 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2040 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2041 const int nbHyps = _sdVec[i]._hyps.size();
2044 // check if two hypotheses define different parameters for the same FACE
2045 list< TFacesOfHyp >::iterator igFacesOfHyp;
2046 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2048 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2050 igFacesOfHyp = ignoreFacesOfHyps.begin();
2051 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2052 if ( ! igFacesOfHyp->first.count( faceID ))
2055 return error(SMESH_Comment("Several hypotheses define "
2056 "Viscous Layers on the face #") << faceID );
2057 hyp = igFacesOfHyp->second;
2060 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2062 _sdVec[i]._ignoreFaceIds.insert( faceID );
2065 // check if two hypotheses define different number of viscous layers for
2066 // adjacent faces of a solid
2067 set< int > nbLayersSet;
2068 igFacesOfHyp = ignoreFacesOfHyps.begin();
2069 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2071 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2073 if ( nbLayersSet.size() > 1 )
2075 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2077 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2078 THyp hyp1 = 0, hyp2 = 0;
2079 while( const TopoDS_Shape* face = fIt->next() )
2081 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2082 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2083 if ( f2h != _sdVec[i]._face2hyp.end() )
2085 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2088 if ( hyp1 && hyp2 &&
2089 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2091 return error("Two hypotheses define different number of "
2092 "viscous layers on adjacent faces");
2096 } // if ( nbHyps > 1 )
2099 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2103 if ( onlyWith ) // is called to check hypotheses compatibility only
2106 // fill _SolidData::_reversedFaceIds
2107 for ( size_t i = 0; i < _sdVec.size(); ++i )
2109 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2110 for ( ; exp.More(); exp.Next() )
2112 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2113 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2114 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2115 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2116 helper.IsReversedSubMesh( face ))
2118 _sdVec[i]._reversedFaceIds.insert( faceID );
2123 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2124 TopTools_IndexedMapOfShape shapes;
2125 std::string structAlgoName = "Hexa_3D";
2126 for ( size_t i = 0; i < _sdVec.size(); ++i )
2129 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2130 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2132 const TopoDS_Shape& edge = shapes(iE);
2133 // find 2 FACEs sharing an EDGE
2135 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2136 while ( fIt->more())
2138 const TopoDS_Shape* f = fIt->next();
2139 FF[ int( !FF[0].IsNull()) ] = *f;
2141 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2143 // check presence of layers on them
2145 for ( int j = 0; j < 2; ++j )
2146 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2147 if ( ignore[0] == ignore[1] )
2148 continue; // nothing interesting
2149 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2152 if ( !fWOL.IsNull())
2154 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2155 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2160 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2162 for ( size_t i = 0; i < _sdVec.size(); ++i )
2165 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2166 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2168 const TopoDS_Shape& vertex = shapes(iV);
2169 // find faces WOL sharing the vertex
2170 vector< TopoDS_Shape > facesWOL;
2171 size_t totalNbFaces = 0;
2172 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2173 while ( fIt->more())
2175 const TopoDS_Shape* f = fIt->next();
2177 const int fID = getMeshDS()->ShapeToIndex( *f );
2178 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2179 facesWOL.push_back( *f );
2181 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2182 continue; // no layers at this vertex or no WOL
2183 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2184 switch ( facesWOL.size() )
2188 helper.SetSubShape( facesWOL[0] );
2189 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2191 TopoDS_Shape seamEdge;
2192 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2193 while ( eIt->more() && seamEdge.IsNull() )
2195 const TopoDS_Shape* e = eIt->next();
2196 if ( helper.IsRealSeam( *e ) )
2199 if ( !seamEdge.IsNull() )
2201 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2205 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2210 // find an edge shared by 2 faces
2211 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2212 while ( eIt->more())
2214 const TopoDS_Shape* e = eIt->next();
2215 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2216 helper.IsSubShape( *e, facesWOL[1]))
2218 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2224 return error("Not yet supported case", _sdVec[i]._index);
2229 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2230 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2231 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2232 for ( size_t i = 0; i < _sdVec.size(); ++i )
2234 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2235 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2237 const TopoDS_Shape& fWOL = e2f->second;
2238 const TGeomID edgeID = e2f->first;
2239 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2240 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2241 if ( edge.ShapeType() != TopAbs_EDGE )
2242 continue; // shrink shape is VERTEX
2245 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2246 while ( soIt->more() && solid.IsNull() )
2248 const TopoDS_Shape* so = soIt->next();
2249 if ( !so->IsSame( _sdVec[i]._solid ))
2252 if ( solid.IsNull() )
2255 bool noShrinkE = false;
2256 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2257 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2258 size_t iSolid = _solids.FindIndex( solid ) - 1;
2259 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2261 // the adjacent SOLID has NO layers on fWOL;
2262 // shrink allowed if
2263 // - there are layers on the EDGE in the adjacent SOLID
2264 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2265 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2266 bool shrinkAllowed = (( hasWLAdj ) ||
2267 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2268 noShrinkE = !shrinkAllowed;
2270 else if ( iSolid < _sdVec.size() )
2272 // the adjacent SOLID has layers on fWOL;
2273 // check if SOLID's mesh is unstructured and then try to set it
2274 // to be computed after the i-th solid
2275 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2276 noShrinkE = true; // don't shrink fWOL
2280 // the adjacent SOLID has NO layers at all
2281 noShrinkE = isStructured;
2286 _sdVec[i]._noShrinkShapes.insert( edgeID );
2288 // check if there is a collision with to-shrink-from EDGEs in iSolid
2289 // if ( iSolid < _sdVec.size() )
2292 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2293 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2295 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2296 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2297 // if ( eID == edgeID ||
2298 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2299 // _sdVec[i]._noShrinkShapes.count( eID ))
2301 // for ( int is1st = 0; is1st < 2; ++is1st )
2303 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2304 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2306 // return error("No way to make a conformal mesh with "
2307 // "the given set of faces with layers", _sdVec[i]._index);
2314 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2315 // _shrinkShape2Shape is different in the adjacent SOLID
2316 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2318 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2319 bool noShrinkV = false;
2321 if ( iSolid < _sdVec.size() )
2323 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2325 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2326 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2327 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2328 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2329 noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2331 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2335 noShrinkV = noShrinkE;
2340 // the adjacent SOLID has NO layers at all
2341 noShrinkV = ( isStructured ||
2342 _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2345 _sdVec[i]._noShrinkShapes.insert( vID );
2348 } // loop on _sdVec[i]._shrinkShape2Shape
2349 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2352 // add FACEs of other SOLIDs to _ignoreFaceIds
2353 for ( size_t i = 0; i < _sdVec.size(); ++i )
2356 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2358 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2360 if ( !shapes.Contains( exp.Current() ))
2361 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2368 //================================================================================
2370 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2372 //================================================================================
2374 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2375 const StdMeshers_ViscousLayers* hyp,
2376 const TopoDS_Shape& hypShape,
2377 set<TGeomID>& ignoreFaceIds)
2379 TopExp_Explorer exp;
2381 vector<TGeomID> ids = hyp->GetBndShapes();
2382 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2384 for ( size_t ii = 0; ii < ids.size(); ++ii )
2386 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2387 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2388 ignoreFaceIds.insert( ids[ii] );
2391 else // FACEs with layers are given
2393 exp.Init( solid, TopAbs_FACE );
2394 for ( ; exp.More(); exp.Next() )
2396 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2397 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2398 ignoreFaceIds.insert( faceInd );
2402 // ignore internal FACEs if inlets and outlets are specified
2403 if ( hyp->IsToIgnoreShapes() )
2405 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2406 TopExp::MapShapesAndAncestors( hypShape,
2407 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2409 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2411 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2412 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2415 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2417 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2422 //================================================================================
2424 * \brief Create the inner surface of the viscous layer and prepare data for infation
2426 //================================================================================
2428 bool _ViscousBuilder::makeLayer(_SolidData& data)
2430 // get all sub-shapes to make layers on
2431 set<TGeomID> subIds, faceIds;
2432 subIds = data._noShrinkShapes;
2433 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2434 for ( ; exp.More(); exp.Next() )
2436 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2437 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2438 faceIds.insert( fSubM->GetId() );
2441 // make a map to find new nodes on sub-shapes shared with other SOLID
2442 map< TGeomID, TNode2Edge* >::iterator s2ne;
2443 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2444 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2446 TGeomID shapeInd = s2s->first;
2447 for ( size_t i = 0; i < _sdVec.size(); ++i )
2449 if ( _sdVec[i]._index == data._index ) continue;
2450 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2451 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2452 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2454 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2460 // Create temporary faces and _LayerEdge's
2462 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2464 data._stepSize = Precision::Infinite();
2465 data._stepSizeNodes[0] = 0;
2467 SMESH_MesherHelper helper( *_mesh );
2468 helper.SetSubShape( data._solid );
2469 helper.SetElementsOnShape( true );
2471 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2472 TNode2Edge::iterator n2e2;
2474 // collect _LayerEdge's of shapes they are based on
2475 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2476 const int nbShapes = getMeshDS()->MaxShapeIndex();
2477 edgesByGeom.resize( nbShapes+1 );
2479 // set data of _EdgesOnShape's
2480 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2482 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2483 while ( smIt->more() )
2486 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2487 !faceIds.count( sm->GetId() ))
2489 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2492 // make _LayerEdge's
2493 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2495 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2496 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2497 SMESH_ProxyMesh::SubMesh* proxySub =
2498 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2500 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2501 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2503 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2504 while ( eIt->more() )
2506 const SMDS_MeshElement* face = eIt->next();
2507 double faceMaxCosin = -1;
2508 _LayerEdge* maxCosinEdge = 0;
2509 int nbDegenNodes = 0;
2511 newNodes.resize( face->NbCornerNodes() );
2512 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2514 const SMDS_MeshNode* n = face->GetNode( i );
2515 const int shapeID = n->getshapeId();
2516 const bool onDegenShap = helper.IsDegenShape( shapeID );
2517 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2522 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2523 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2524 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2525 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2535 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2536 if ( !(*n2e).second )
2539 _LayerEdge* edge = new _LayerEdge();
2540 edge->_nodes.push_back( n );
2542 edgesByGeom[ shapeID ]._edges.push_back( edge );
2543 const bool noShrink = data._noShrinkShapes.count( shapeID );
2545 SMESH_TNodeXYZ xyz( n );
2547 // set edge data or find already refined _LayerEdge and get data from it
2548 if (( !noShrink ) &&
2549 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2550 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2551 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2553 _LayerEdge* foundEdge = (*n2e2).second;
2554 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2555 foundEdge->_pos.push_back( lastPos );
2556 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2557 const_cast< SMDS_MeshNode* >
2558 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2564 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2566 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2569 if ( edge->_nodes.size() < 2 )
2570 edge->Block( data );
2571 //data._noShrinkShapes.insert( shapeID );
2573 dumpMove(edge->_nodes.back());
2575 if ( edge->_cosin > faceMaxCosin )
2577 faceMaxCosin = edge->_cosin;
2578 maxCosinEdge = edge;
2581 newNodes[ i ] = n2e->second->_nodes.back();
2584 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2586 if ( newNodes.size() - nbDegenNodes < 2 )
2589 // create a temporary face
2590 const SMDS_MeshElement* newFace =
2591 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2592 proxySub->AddElement( newFace );
2594 // compute inflation step size by min size of element on a convex surface
2595 if ( faceMaxCosin > theMinSmoothCosin )
2596 limitStepSize( data, face, maxCosinEdge );
2598 } // loop on 2D elements on a FACE
2599 } // loop on FACEs of a SOLID to create _LayerEdge's
2602 // Set _LayerEdge::_neibors
2603 TNode2Edge::iterator n2e;
2604 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2606 _EdgesOnShape& eos = data._edgesOnShape[iS];
2607 for ( size_t i = 0; i < eos._edges.size(); ++i )
2609 _LayerEdge* edge = eos._edges[i];
2610 TIDSortedNodeSet nearNodes;
2611 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2612 while ( fIt->more() )
2614 const SMDS_MeshElement* f = fIt->next();
2615 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2616 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2618 nearNodes.erase( edge->_nodes[0] );
2619 edge->_neibors.reserve( nearNodes.size() );
2620 TIDSortedNodeSet::iterator node = nearNodes.begin();
2621 for ( ; node != nearNodes.end(); ++node )
2622 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2623 edge->_neibors.push_back( n2e->second );
2627 data._epsilon = 1e-7;
2628 if ( data._stepSize < 1. )
2629 data._epsilon *= data._stepSize;
2631 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2634 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2635 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2637 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2638 const SMDS_MeshNode* nn[2];
2639 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2641 _EdgesOnShape& eos = data._edgesOnShape[iS];
2642 for ( size_t i = 0; i < eos._edges.size(); ++i )
2644 _LayerEdge* edge = eos._edges[i];
2645 if ( edge->IsOnEdge() )
2647 // get neighbor nodes
2648 bool hasData = ( edge->_2neibors->_edges[0] );
2649 if ( hasData ) // _LayerEdge is a copy of another one
2651 nn[0] = edge->_2neibors->srcNode(0);
2652 nn[1] = edge->_2neibors->srcNode(1);
2654 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2658 // set neighbor _LayerEdge's
2659 for ( int j = 0; j < 2; ++j )
2661 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2662 return error("_LayerEdge not found by src node", data._index);
2663 edge->_2neibors->_edges[j] = n2e->second;
2666 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2669 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2671 _Simplex& s = edge->_simplices[j];
2672 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2673 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2676 // For an _LayerEdge on a degenerated EDGE, copy some data from
2677 // a corresponding _LayerEdge on a VERTEX
2678 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2679 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2681 // Generally we should not get here
2682 if ( eos.ShapeType() != TopAbs_EDGE )
2684 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2685 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2686 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2688 const _LayerEdge* vEdge = n2e->second;
2689 edge->_normal = vEdge->_normal;
2690 edge->_lenFactor = vEdge->_lenFactor;
2691 edge->_cosin = vEdge->_cosin;
2694 } // loop on data._edgesOnShape._edges
2695 } // loop on data._edgesOnShape
2697 // fix _LayerEdge::_2neibors on EDGEs to smooth
2698 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2699 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2700 // if ( !e2c->second.IsNull() )
2702 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2703 // data.Sort2NeiborsOnEdge( eos->_edges );
2710 //================================================================================
2712 * \brief Compute inflation step size by min size of element on a convex surface
2714 //================================================================================
2716 void _ViscousBuilder::limitStepSize( _SolidData& data,
2717 const SMDS_MeshElement* face,
2718 const _LayerEdge* maxCosinEdge )
2721 double minSize = 10 * data._stepSize;
2722 const int nbNodes = face->NbCornerNodes();
2723 for ( int i = 0; i < nbNodes; ++i )
2725 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2726 const SMDS_MeshNode* curN = face->GetNode( i );
2727 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2728 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2730 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2731 if ( dist < minSize )
2732 minSize = dist, iN = i;
2735 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2736 if ( newStep < data._stepSize )
2738 data._stepSize = newStep;
2739 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2740 data._stepSizeNodes[0] = face->GetNode( iN );
2741 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2745 //================================================================================
2747 * \brief Compute inflation step size by min size of element on a convex surface
2749 //================================================================================
2751 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2753 if ( minSize < data._stepSize )
2755 data._stepSize = minSize;
2756 if ( data._stepSizeNodes[0] )
2759 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2760 data._stepSizeCoeff = data._stepSize / dist;
2765 //================================================================================
2767 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2769 //================================================================================
2771 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2773 SMESH_MesherHelper helper( *_mesh );
2775 const int nbTestPnt = 5; // on a FACE sub-shape
2777 BRepLProp_SLProps surfProp( 2, 1e-6 );
2778 data._convexFaces.clear();
2780 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2782 _EdgesOnShape& eof = data._edgesOnShape[iS];
2783 if ( eof.ShapeType() != TopAbs_FACE ||
2784 data._ignoreFaceIds.count( eof._shapeID ))
2787 TopoDS_Face F = TopoDS::Face( eof._shape );
2788 SMESH_subMesh * sm = eof._subMesh;
2789 const TGeomID faceID = eof._shapeID;
2791 BRepAdaptor_Surface surface( F, false );
2792 surfProp.SetSurface( surface );
2794 bool isTooCurved = false;
2796 _ConvexFace cnvFace;
2797 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2798 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2799 while ( smIt->more() )
2802 const TGeomID subID = sm->GetId();
2803 // find _LayerEdge's of a sub-shape
2805 if (( eos = data.GetShapeEdges( subID )))
2806 cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2809 // check concavity and curvature and limit data._stepSize
2810 const double minCurvature =
2811 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2812 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2813 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2815 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2816 surfProp.SetParameters( uv.X(), uv.Y() );
2817 if ( !surfProp.IsCurvatureDefined() )
2819 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2821 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2824 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2826 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2830 } // loop on sub-shapes of the FACE
2832 if ( !isTooCurved ) continue;
2834 _ConvexFace & convFace =
2835 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2838 convFace._normalsFixed = false;
2840 // skip a closed surface (data._convexFaces is useful anyway)
2841 bool isClosedF = false;
2842 helper.SetSubShape( F );
2843 if ( helper.HasRealSeam() )
2845 // in the closed surface there must be a closed EDGE
2846 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2847 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2851 // limit _LayerEdge::_maxLen on the FACE
2852 const double minCurvature =
2853 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2854 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2855 if ( id2eos != cnvFace._subIdToEOS.end() )
2857 _EdgesOnShape& eos = * id2eos->second;
2858 for ( size_t i = 0; i < eos._edges.size(); ++i )
2860 _LayerEdge* ledge = eos._edges[ i ];
2861 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2862 surfProp.SetParameters( uv.X(), uv.Y() );
2863 if ( !surfProp.IsCurvatureDefined() )
2866 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2867 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2869 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2870 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2876 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2877 // prism distortion.
2878 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2879 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2881 // there are _LayerEdge's on the FACE it-self;
2882 // select _LayerEdge's near EDGEs
2883 _EdgesOnShape& eos = * id2eos->second;
2884 for ( size_t i = 0; i < eos._edges.size(); ++i )
2886 _LayerEdge* ledge = eos._edges[ i ];
2887 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2888 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2890 convFace._simplexTestEdges.push_back( ledge );
2897 // where there are no _LayerEdge's on a _ConvexFace,
2898 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2899 // so that collision of viscous internal faces is not detected by check of
2900 // intersection of _LayerEdge's with the viscous internal faces.
2902 set< const SMDS_MeshNode* > usedNodes;
2904 // look for _LayerEdge's with null _sWOL
2905 id2eos = convFace._subIdToEOS.begin();
2906 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2908 _EdgesOnShape& eos = * id2eos->second;
2909 if ( !eos._sWOL.IsNull() )
2911 for ( size_t i = 0; i < eos._edges.size(); ++i )
2913 _LayerEdge* ledge = eos._edges[ i ];
2914 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2915 if ( !usedNodes.insert( srcNode ).second ) continue;
2917 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2919 usedNodes.insert( ledge->_simplices[i]._nPrev );
2920 usedNodes.insert( ledge->_simplices[i]._nNext );
2922 convFace._simplexTestEdges.push_back( ledge );
2926 } // loop on FACEs of data._solid
2929 //================================================================================
2931 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2933 //================================================================================
2935 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2937 // define allowed thickness
2938 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2940 data._maxThickness = 0;
2941 data._minThickness = 1e100;
2942 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2943 for ( ; hyp != data._hyps.end(); ++hyp )
2945 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2946 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2948 //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2950 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2951 // boundry inclined to the shape at a sharp angle
2953 //list< TGeomID > shapesToSmooth;
2954 TopTools_MapOfShape edgesOfSmooFaces;
2956 SMESH_MesherHelper helper( *_mesh );
2959 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2960 data._nbShapesToSmooth = 0;
2962 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2964 _EdgesOnShape& eos = edgesByGeom[iS];
2965 eos._toSmooth = false;
2966 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2969 double tgtThick = eos._hyp.GetTotalThickness();
2970 TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2971 for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2973 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2974 vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2975 if ( eE.empty() ) continue;
2978 for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2979 if ( eE[i]->_cosin > theMinSmoothCosin )
2981 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2982 while ( fIt->more() && !eos._toSmooth )
2984 const SMDS_MeshElement* face = fIt->next();
2985 if ( face->getshapeId() == eos._shapeID &&
2986 getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2988 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2993 if ( eos._toSmooth )
2995 for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2996 edgesOfSmooFaces.Add( eExp.Current() );
2998 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3000 data._nbShapesToSmooth += eos._toSmooth;
3004 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3006 _EdgesOnShape& eos = edgesByGeom[iS];
3007 eos._edgeSmoother = NULL;
3008 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3009 if ( !eos._hyp.ToSmooth() ) continue;
3011 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3012 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3015 double tgtThick = eos._hyp.GetTotalThickness();
3016 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3018 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3019 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3020 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3021 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3022 double angle = eDir.Angle( eV[0]->_normal );
3023 double cosin = Cos( angle );
3024 double cosinAbs = Abs( cosin );
3025 if ( cosinAbs > theMinSmoothCosin )
3027 // always smooth analytic EDGEs
3028 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3029 eos._toSmooth = ! curve.IsNull();
3031 // compare tgtThick with the length of an end segment
3032 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3033 while ( eIt->more() && !eos._toSmooth )
3035 const SMDS_MeshElement* endSeg = eIt->next();
3036 if ( endSeg->getshapeId() == (int) iS )
3039 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3040 eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3043 if ( eos._toSmooth )
3045 eos._edgeSmoother = new _Smoother1D( curve, eos );
3047 for ( size_t i = 0; i < eos._edges.size(); ++i )
3048 eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3052 data._nbShapesToSmooth += eos._toSmooth;
3056 // Reset _cosin if no smooth is allowed by the user
3057 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3059 _EdgesOnShape& eos = edgesByGeom[iS];
3060 if ( eos._edges.empty() ) continue;
3062 if ( !eos._hyp.ToSmooth() )
3063 for ( size_t i = 0; i < eos._edges.size(); ++i )
3064 eos._edges[i]->SetCosin( 0 );
3068 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3070 TopTools_MapOfShape c1VV;
3072 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3074 _EdgesOnShape& eos = edgesByGeom[iS];
3075 if ( eos._edges.empty() ||
3076 eos.ShapeType() != TopAbs_FACE ||
3080 // check EDGEs of a FACE
3081 TopTools_MapOfShape checkedEE, allVV;
3082 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3083 while ( !smQueue.empty() )
3085 SMESH_subMesh* sm = smQueue.front();
3086 smQueue.pop_front();
3087 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3088 while ( smIt->more() )
3091 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3092 allVV.Add( sm->GetSubShape() );
3093 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3094 !checkedEE.Add( sm->GetSubShape() ))
3097 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3098 vector<_LayerEdge*>& eE = eoe->_edges;
3099 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3102 bool isC1 = true; // check continuity along an EDGE
3103 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3104 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3108 // check that mesh faces are C1 as well
3110 gp_XYZ norm1, norm2;
3111 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3112 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3113 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3115 while ( fIt->more() && isC1 )
3116 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3117 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3122 // add the EDGE and an adjacent FACE to _eosC1
3123 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3124 while ( const TopoDS_Shape* face = fIt->next() )
3126 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3127 if ( !eof ) continue; // other solid
3128 if ( !eos.HasC1( eoe ))
3130 eos._eosC1.push_back( eoe );
3131 eoe->_toSmooth = false;
3132 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3134 if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof ))
3136 eos._eosC1.push_back( eof );
3137 eof->_toSmooth = false;
3138 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3139 smQueue.push_back( eof->_subMesh );
3144 if ( eos._eosC1.empty() )
3147 // check VERTEXes of C1 FACEs
3148 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3149 for ( ; vIt.More(); vIt.Next() )
3151 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3152 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3155 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3156 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3157 while ( const TopoDS_Shape* face = fIt->next() )
3159 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3160 if ( !eof ) continue; // other solid
3161 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3167 eos._eosC1.push_back( eov );
3168 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3169 c1VV.Add( eov->_shape );
3173 } // fill _eosC1 of FACEs
3178 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3180 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3182 _EdgesOnShape& eov = edgesByGeom[iS];
3183 if ( eov._edges.empty() ||
3184 eov.ShapeType() != TopAbs_VERTEX ||
3185 c1VV.Contains( eov._shape ))
3187 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3189 // get directions of surrounding EDGEs
3191 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3192 while ( const TopoDS_Shape* e = fIt->next() )
3194 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3195 if ( !eoe ) continue; // other solid
3196 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3197 if ( !Precision::IsInfinite( eDir.X() ))
3198 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3201 // find EDGEs with C1 directions
3202 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3203 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3204 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3206 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3207 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3210 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3211 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3212 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3213 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3214 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3215 dirOfEdges[i].first = 0;
3216 dirOfEdges[j].first = 0;
3219 } // fill _eosC1 of VERTEXes
3226 //================================================================================
3228 * \brief initialize data of _EdgesOnShape
3230 //================================================================================
3232 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3236 if ( !eos._shape.IsNull() ||
3237 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3240 SMESH_MesherHelper helper( *_mesh );
3243 eos._shapeID = sm->GetId();
3244 eos._shape = sm->GetSubShape();
3245 if ( eos.ShapeType() == TopAbs_FACE )
3246 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3247 eos._toSmooth = false;
3251 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3252 data._shrinkShape2Shape.find( eos._shapeID );
3253 if ( s2s != data._shrinkShape2Shape.end() )
3254 eos._sWOL = s2s->second;
3256 eos._isRegularSWOL = true;
3257 if ( eos.SWOLType() == TopAbs_FACE )
3259 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3260 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3261 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3265 if ( data._hyps.size() == 1 )
3267 eos._hyp = data._hyps.back();
3271 // compute average StdMeshers_ViscousLayers parameters
3272 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3273 if ( eos.ShapeType() == TopAbs_FACE )
3275 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3276 eos._hyp = f2hyp->second;
3280 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3281 while ( const TopoDS_Shape* face = fIt->next() )
3283 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3284 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3285 eos._hyp.Add( f2hyp->second );
3291 if ( ! eos._hyp.UseSurfaceNormal() )
3293 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3295 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3296 eos._faceNormals.resize( smDS->NbElements() );
3298 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3299 for ( int iF = 0; eIt->more(); ++iF )
3301 const SMDS_MeshElement* face = eIt->next();
3302 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3303 eos._faceNormals[iF].SetCoord( 0,0,0 );
3306 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3307 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3308 eos._faceNormals[iF].Reverse();
3310 else // find EOS of adjacent FACEs
3312 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3313 while ( const TopoDS_Shape* face = fIt->next() )
3315 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3316 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3317 if ( eos._faceEOS.back()->_shape.IsNull() )
3318 // avoid using uninitialised _shapeID in GetNormal()
3319 eos._faceEOS.back()->_shapeID = faceID;
3325 //================================================================================
3327 * \brief Returns normal of a face
3329 //================================================================================
3331 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3334 const _EdgesOnShape* eos = 0;
3336 if ( face->getshapeId() == _shapeID )
3342 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3343 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3344 eos = _faceEOS[ iF ];
3348 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3350 norm = eos->_faceNormals[ face->getIdInShape() ];
3354 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3355 << " on _shape #" << _shapeID );
3361 //================================================================================
3363 * \brief Set data of _LayerEdge needed for smoothing
3365 //================================================================================
3367 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3369 SMESH_MesherHelper& helper,
3372 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3375 edge._maxLen = Precision::Infinite();
3378 edge._curvature = 0;
3381 // --------------------------
3382 // Compute _normal and _cosin
3383 // --------------------------
3386 edge._lenFactor = 1.;
3387 edge._normal.SetCoord(0,0,0);
3388 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3390 int totalNbFaces = 0;
3392 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3396 const bool onShrinkShape = !eos._sWOL.IsNull();
3397 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3398 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3400 // get geom FACEs the node lies on
3401 //if ( useGeometry )
3403 set<TGeomID> faceIds;
3404 if ( eos.ShapeType() == TopAbs_FACE )
3406 faceIds.insert( eos._shapeID );
3410 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3411 while ( fIt->more() )
3412 faceIds.insert( fIt->next()->getshapeId() );
3414 set<TGeomID>::iterator id = faceIds.begin();
3415 for ( ; id != faceIds.end(); ++id )
3417 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3418 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3420 F = TopoDS::Face( s );
3421 face2Norm[ totalNbFaces ].first = F;
3429 bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3430 eos.SWOLType() == TopAbs_FACE &&
3433 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3435 if ( eos.SWOLType() == TopAbs_EDGE )
3437 // inflate from VERTEX along EDGE
3438 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3440 else if ( eos.ShapeType() == TopAbs_VERTEX )
3442 // inflate from VERTEX along FACE
3443 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3444 node, helper, normOK, &edge._cosin);
3448 // inflate from EDGE along FACE
3449 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3450 node, helper, normOK);
3453 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3456 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3459 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3461 F = face2Norm[ iF ].first;
3462 geomNorm = getFaceNormal( node, F, helper, normOK );
3463 if ( !normOK ) continue;
3466 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3468 face2Norm[ iF ].second = geomNorm.XYZ();
3469 edge._normal += geomNorm.XYZ();
3471 if ( nbOkNorms == 0 )
3472 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3474 if ( totalNbFaces >= 3 )
3476 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3479 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3481 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3482 edge._normal.SetCoord( 0,0,0 );
3483 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3485 const TopoDS_Face& F = face2Norm[iF].first;
3486 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3487 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3490 face2Norm[ iF ].second = geomNorm.XYZ();
3491 edge._normal += face2Norm[ iF ].second;
3496 else // !useGeometry - get _normal using surrounding mesh faces
3498 edge._normal = getWeigthedNormal( &edge );
3500 // set<TGeomID> faceIds;
3502 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3503 // while ( fIt->more() )
3505 // const SMDS_MeshElement* face = fIt->next();
3506 // if ( eos.GetNormal( face, geomNorm ))
3508 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3509 // continue; // use only one mesh face on FACE
3510 // edge._normal += geomNorm.XYZ();
3517 //if ( eos._hyp.UseSurfaceNormal() )
3519 switch ( eos.ShapeType() )
3526 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3527 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3528 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3529 edge._cosin = Cos( angle );
3532 case TopAbs_VERTEX: {
3533 //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3535 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3536 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3537 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3538 edge._cosin = Cos( angle );
3539 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3540 for ( int iF = totalNbFaces-2; iF >=0; --iF )
3542 F = face2Norm[ iF ].first;
3543 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3545 double angle = inFaceDir.Angle( edge._normal );
3546 double cosin = Cos( angle );
3547 if ( Abs( cosin ) > Abs( edge._cosin ))
3548 edge._cosin = cosin;
3555 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3559 double normSize = edge._normal.SquareModulus();
3560 if ( normSize < numeric_limits<double>::min() )
3561 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3563 edge._normal /= sqrt( normSize );
3565 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3567 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3568 edge._nodes.resize( 1 );
3569 edge._normal.SetCoord( 0,0,0 );
3573 // Set the rest data
3574 // --------------------
3576 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3578 if ( onShrinkShape )
3580 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3581 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3582 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3584 // set initial position which is parameters on _sWOL in this case
3585 if ( eos.SWOLType() == TopAbs_EDGE )
3587 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3588 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3589 if ( edge._nodes.size() > 1 )
3590 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3592 else // eos.SWOLType() == TopAbs_FACE
3594 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3595 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3596 if ( edge._nodes.size() > 1 )
3597 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3600 if ( edge._nodes.size() > 1 )
3602 // check if an angle between a FACE with layers and SWOL is sharp,
3603 // else the edge should not inflate
3605 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3606 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3607 F = face2Norm[iF].first;
3610 geomNorm = getFaceNormal( node, F, helper, normOK );
3611 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3612 geomNorm.Reverse(); // inside the SOLID
3613 if ( geomNorm * edge._normal < -0.001 )
3615 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3616 edge._nodes.resize( 1 );
3618 else if ( edge._lenFactor > 3 )
3620 edge._lenFactor = 2;
3621 edge.Set( _LayerEdge::RISKY_SWOL );
3628 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3630 if ( eos.ShapeType() == TopAbs_FACE )
3633 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3635 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3636 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3641 // Set neighbor nodes for a _LayerEdge based on EDGE
3643 if ( eos.ShapeType() == TopAbs_EDGE /*||
3644 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3646 edge._2neibors = new _2NearEdges;
3647 // target nodes instead of source ones will be set later
3653 //================================================================================
3655 * \brief Return normal to a FACE at a node
3656 * \param [in] n - node
3657 * \param [in] face - FACE
3658 * \param [in] helper - helper
3659 * \param [out] isOK - true or false
3660 * \param [in] shiftInside - to find normal at a position shifted inside the face
3661 * \return gp_XYZ - normal
3663 //================================================================================
3665 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3666 const TopoDS_Face& face,
3667 SMESH_MesherHelper& helper,
3674 // get a shifted position
3675 gp_Pnt p = SMESH_TNodeXYZ( node );
3676 gp_XYZ shift( 0,0,0 );
3677 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3678 switch ( S.ShapeType() ) {
3681 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3686 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3694 p.Translate( shift * 1e-5 );
3696 TopLoc_Location loc;
3697 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3699 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3701 projector.Perform( p );
3702 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3707 Quantity_Parameter U,V;
3708 projector.LowerDistanceParameters(U,V);
3713 uv = helper.GetNodeUV( face, node, 0, &isOK );
3719 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3721 if ( !shiftInside &&
3722 helper.IsDegenShape( node->getshapeId() ) &&
3723 getFaceNormalAtSingularity( uv, face, helper, normal ))
3726 return normal.XYZ();
3729 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3730 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3732 if ( pointKind == IMPOSSIBLE &&
3733 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3735 // probably NormEstim() failed due to a too high tolerance
3736 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3737 isOK = ( pointKind < IMPOSSIBLE );
3739 if ( pointKind < IMPOSSIBLE )
3741 if ( pointKind != REGULAR &&
3743 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3745 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3746 if ( normShift * normal.XYZ() < 0. )
3752 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3754 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3756 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3757 while ( fIt->more() )
3759 const SMDS_MeshElement* f = fIt->next();
3760 if ( f->getshapeId() == faceID )
3762 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3765 TopoDS_Face ff = face;
3766 ff.Orientation( TopAbs_FORWARD );
3767 if ( helper.IsReversedSubMesh( ff ))
3774 return normal.XYZ();
3777 //================================================================================
3779 * \brief Try to get normal at a singularity of a surface basing on it's nature
3781 //================================================================================
3783 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3784 const TopoDS_Face& face,
3785 SMESH_MesherHelper& helper,
3788 BRepAdaptor_Surface surface( face );
3790 if ( !getRovolutionAxis( surface, axis ))
3793 double f,l, d, du, dv;
3794 f = surface.FirstUParameter();
3795 l = surface.LastUParameter();
3796 d = ( uv.X() - f ) / ( l - f );
3797 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3798 f = surface.FirstVParameter();
3799 l = surface.LastVParameter();
3800 d = ( uv.Y() - f ) / ( l - f );
3801 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3804 gp_Pnt2d testUV = uv;
3805 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3807 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3808 for ( int iLoop = 0; true ; ++iLoop )
3810 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3811 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3818 if ( axis * refDir < 0. )
3826 //================================================================================
3828 * \brief Return a normal at a node weighted with angles taken by faces
3830 //================================================================================
3832 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3834 const SMDS_MeshNode* n = edge->_nodes[0];
3836 gp_XYZ resNorm(0,0,0);
3837 SMESH_TNodeXYZ p0( n ), pP, pN;
3838 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3840 pP.Set( edge->_simplices[i]._nPrev );
3841 pN.Set( edge->_simplices[i]._nNext );
3842 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3843 double l0P = v0P.SquareMagnitude();
3844 double l0N = v0N.SquareMagnitude();
3845 double lPN = vPN.SquareMagnitude();
3846 if ( l0P < std::numeric_limits<double>::min() ||
3847 l0N < std::numeric_limits<double>::min() ||
3848 lPN < std::numeric_limits<double>::min() )
3850 double lNorm = norm.SquareMagnitude();
3851 double sin2 = lNorm / l0P / l0N;
3852 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3854 double weight = sin2 * angle / lPN;
3855 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3861 //================================================================================
3863 * \brief Return a normal at a node by getting a common point of offset planes
3864 * defined by the FACE normals
3866 //================================================================================
3868 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3869 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3873 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3875 gp_XYZ resNorm(0,0,0);
3876 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3877 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3879 for ( int i = 0; i < nbFaces; ++i )
3880 resNorm += f2Normal[i].second;
3884 // prepare _OffsetPlane's
3885 vector< _OffsetPlane > pln( nbFaces );
3886 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3888 pln[i]._faceIndex = i;
3889 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3893 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3894 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3897 // intersect neighboring OffsetPlane's
3898 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3899 while ( const TopoDS_Shape* edge = edgeIt->next() )
3901 int f1 = -1, f2 = -1;
3902 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3903 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3904 (( f1 < 0 ) ? f1 : f2 ) = i;
3907 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3910 // get a common point
3911 gp_XYZ commonPnt( 0, 0, 0 );
3914 for ( int i = 0; i < nbFaces; ++i )
3916 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3917 nbPoints += isPointFound;
3919 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3920 if ( nbPoints == 0 )
3923 commonPnt /= nbPoints;
3924 resNorm = commonPnt - p0;
3928 // choose the best among resNorm and wgtNorm
3929 resNorm.Normalize();
3930 wgtNorm.Normalize();
3931 double resMinDot = std::numeric_limits<double>::max();
3932 double wgtMinDot = std::numeric_limits<double>::max();
3933 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3935 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3936 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3939 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3941 edge->Set( _LayerEdge::MULTI_NORMAL );
3944 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3947 //================================================================================
3949 * \brief Compute line of intersection of 2 planes
3951 //================================================================================
3953 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3954 const TopoDS_Edge& E,
3955 const TopoDS_Vertex& V )
3957 int iNext = bool( _faceIndexNext[0] >= 0 );
3958 _faceIndexNext[ iNext ] = pln._faceIndex;
3960 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3961 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3963 gp_XYZ lineDir = n1 ^ n2;
3965 double x = Abs( lineDir.X() );
3966 double y = Abs( lineDir.Y() );
3967 double z = Abs( lineDir.Z() );
3969 int cooMax; // max coordinate
3971 if (x > z) cooMax = 1;
3975 if (y > z) cooMax = 2;
3980 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3982 // parallel planes - intersection is an offset of the common EDGE
3983 gp_Pnt p = BRep_Tool::Pnt( V );
3984 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3985 lineDir = getEdgeDir( E, V );
3989 // the constants in the 2 plane equations
3990 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
3991 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3996 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3997 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4000 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4002 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4005 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4006 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4010 gp_Lin& line = _lines[ iNext ];
4011 line.SetDirection( lineDir );
4012 line.SetLocation ( linePos );
4014 _isLineOK[ iNext ] = true;
4017 iNext = bool( pln._faceIndexNext[0] >= 0 );
4018 pln._lines [ iNext ] = line;
4019 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4020 pln._isLineOK [ iNext ] = true;
4023 //================================================================================
4025 * \brief Computes intersection point of two _lines
4027 //================================================================================
4029 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4030 const TopoDS_Vertex & V) const
4035 if ( NbLines() == 2 )
4037 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4038 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4039 if ( Abs( dot01 ) > 0.05 )
4041 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4042 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4043 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4048 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4049 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4050 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4051 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4052 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4060 //================================================================================
4062 * \brief Find 2 neigbor nodes of a node on EDGE
4064 //================================================================================
4066 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4067 const SMDS_MeshNode*& n1,
4068 const SMDS_MeshNode*& n2,
4072 const SMDS_MeshNode* node = edge->_nodes[0];
4073 const int shapeInd = eos._shapeID;
4074 SMESHDS_SubMesh* edgeSM = 0;
4075 if ( eos.ShapeType() == TopAbs_EDGE )
4077 edgeSM = eos._subMesh->GetSubMeshDS();
4078 if ( !edgeSM || edgeSM->NbElements() == 0 )
4079 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4083 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4084 while ( eIt->more() && !n2 )
4086 const SMDS_MeshElement* e = eIt->next();
4087 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4088 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4091 if (!edgeSM->Contains(e)) continue;
4095 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4096 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4098 ( iN++ ? n2 : n1 ) = nNeibor;
4101 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4105 //================================================================================
4107 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4109 //================================================================================
4111 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4112 const SMDS_MeshNode* n2,
4113 const _EdgesOnShape& eos,
4114 SMESH_MesherHelper& helper)
4116 if ( eos.ShapeType() != TopAbs_EDGE )
4119 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4120 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4121 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4125 double sumLen = vec1.Modulus() + vec2.Modulus();
4126 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4127 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4128 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4129 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4130 if ( _curvature ) delete _curvature;
4131 _curvature = _Curvature::New( avgNormProj, avgLen );
4132 // if ( _curvature )
4133 // debugMsg( _nodes[0]->GetID()
4134 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4135 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4136 // << _curvature->lenDelta(0) );
4140 if ( eos._sWOL.IsNull() )
4142 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4143 // if ( SMESH_Algo::isDegenerated( E ))
4145 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4146 gp_XYZ plnNorm = dirE ^ _normal;
4147 double proj0 = plnNorm * vec1;
4148 double proj1 = plnNorm * vec2;
4149 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4151 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4152 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4157 //================================================================================
4159 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4160 * this and other _LayerEdge's are inflated along a FACE or an EDGE
4162 //================================================================================
4164 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4166 SMESH_MesherHelper& helper )
4168 _nodes = other._nodes;
4169 _normal = other._normal;
4171 _lenFactor = other._lenFactor;
4172 _cosin = other._cosin;
4173 _2neibors = other._2neibors;
4174 _curvature = 0; std::swap( _curvature, other._curvature );
4175 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4177 gp_XYZ lastPos( 0,0,0 );
4178 if ( eos.SWOLType() == TopAbs_EDGE )
4180 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4181 _pos.push_back( gp_XYZ( u, 0, 0));
4183 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4188 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4189 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4191 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4192 lastPos.SetX( uv.X() );
4193 lastPos.SetY( uv.Y() );
4198 //================================================================================
4200 * \brief Set _cosin and _lenFactor
4202 //================================================================================
4204 void _LayerEdge::SetCosin( double cosin )
4207 cosin = Abs( _cosin );
4208 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4209 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4212 //================================================================================
4214 * \brief Check if another _LayerEdge is a neighbor on EDGE
4216 //================================================================================
4218 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4220 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4221 ( edge->_2neibors && edge->_2neibors->include( this )));
4224 //================================================================================
4226 * \brief Fills a vector<_Simplex >
4228 //================================================================================
4230 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4231 vector<_Simplex>& simplices,
4232 const set<TGeomID>& ingnoreShapes,
4233 const _SolidData* dataToCheckOri,
4237 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4238 while ( fIt->more() )
4240 const SMDS_MeshElement* f = fIt->next();
4241 const TGeomID shapeInd = f->getshapeId();
4242 if ( ingnoreShapes.count( shapeInd )) continue;
4243 const int nbNodes = f->NbCornerNodes();
4244 const int srcInd = f->GetNodeIndex( node );
4245 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4246 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4247 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4248 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4249 std::swap( nPrev, nNext );
4250 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4254 SortSimplices( simplices );
4257 //================================================================================
4259 * \brief Set neighbor simplices side by side
4261 //================================================================================
4263 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4265 vector<_Simplex> sortedSimplices( simplices.size() );
4266 sortedSimplices[0] = simplices[0];
4268 for ( size_t i = 1; i < simplices.size(); ++i )
4270 for ( size_t j = 1; j < simplices.size(); ++j )
4271 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4273 sortedSimplices[i] = simplices[j];
4278 if ( nbFound == simplices.size() - 1 )
4279 simplices.swap( sortedSimplices );
4282 //================================================================================
4284 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4286 //================================================================================
4288 void _ViscousBuilder::makeGroupOfLE()
4291 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4293 if ( _sdVec[i]._n2eMap.empty() ) continue;
4295 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4296 TNode2Edge::iterator n2e;
4297 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4299 _LayerEdge* le = n2e->second;
4300 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4301 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4302 // << ", " << le->_nodes[iN]->GetID() <<"])");
4304 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4305 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4310 dumpFunction( SMESH_Comment("makeNormals") << i );
4311 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4313 _LayerEdge* edge = n2e->second;
4314 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4315 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4316 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4317 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4321 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4322 dumpCmd( "faceId1 = mesh.NbElements()" );
4323 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4324 for ( ; fExp.More(); fExp.Next() )
4326 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4328 if ( sm->NbElements() == 0 ) continue;
4329 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4330 while ( fIt->more())
4332 const SMDS_MeshElement* e = fIt->next();
4333 SMESH_Comment cmd("mesh.AddFace([");
4334 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4335 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4340 dumpCmd( "faceId2 = mesh.NbElements()" );
4341 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4342 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4343 << "'%s-%s' % (faceId1+1, faceId2))");
4349 //================================================================================
4351 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4353 //================================================================================
4355 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4357 data._geomSize = Precision::Infinite();
4358 double intersecDist;
4359 const SMDS_MeshElement* face;
4360 SMESH_MesherHelper helper( *_mesh );
4362 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4363 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4364 data._proxyMesh->GetFaces( data._solid )));
4366 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4368 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4369 if ( eos._edges.empty() )
4371 // get neighbor faces intersection with which should not be considered since
4372 // collisions are avoided by means of smoothing
4373 set< TGeomID > neighborFaces;
4374 if ( eos._hyp.ToSmooth() )
4376 SMESH_subMeshIteratorPtr subIt =
4377 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4378 while ( subIt->more() )
4380 SMESH_subMesh* sm = subIt->next();
4381 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4382 while ( const TopoDS_Shape* face = fIt->next() )
4383 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4386 // find intersections
4387 double thinkness = eos._hyp.GetTotalThickness();
4388 for ( size_t i = 0; i < eos._edges.size(); ++i )
4390 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4391 eos._edges[i]->_maxLen = thinkness;
4392 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4393 if ( intersecDist > 0 && face )
4395 data._geomSize = Min( data._geomSize, intersecDist );
4396 if ( !neighborFaces.count( face->getshapeId() ))
4397 eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4403 //================================================================================
4405 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4407 //================================================================================
4409 bool _ViscousBuilder::inflate(_SolidData& data)
4411 SMESH_MesherHelper helper( *_mesh );
4413 // Limit inflation step size by geometry size found by itersecting
4414 // normals of _LayerEdge's with mesh faces
4415 if ( data._stepSize > 0.3 * data._geomSize )
4416 limitStepSize( data, 0.3 * data._geomSize );
4418 const double tgtThick = data._maxThickness;
4419 if ( data._stepSize > data._minThickness )
4420 limitStepSize( data, data._minThickness );
4422 if ( data._stepSize < 1. )
4423 data._epsilon = data._stepSize * 1e-7;
4425 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4427 findCollisionEdges( data, helper );
4429 limitMaxLenByCurvature( data, helper );
4431 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4432 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4433 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4434 data._edgesOnShape[i]._edges.size() > 0 &&
4435 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4437 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4438 data._edgesOnShape[i]._edges[0]->Block( data );
4441 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4443 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4444 int nbSteps = 0, nbRepeats = 0;
4445 while ( avgThick < 0.99 )
4447 // new target length
4448 double prevThick = curThick;
4449 curThick += data._stepSize;
4450 if ( curThick > tgtThick )
4452 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4456 double stepSize = curThick - prevThick;
4457 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4459 // Elongate _LayerEdge's
4460 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4461 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4463 _EdgesOnShape& eos = data._edgesOnShape[iS];
4464 if ( eos._edges.empty() ) continue;
4466 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4467 for ( size_t i = 0; i < eos._edges.size(); ++i )
4469 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4474 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4477 // Improve and check quality
4478 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4482 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4483 debugMsg("NOT INVALIDATED STEP!");
4484 return error("Smoothing failed", data._index);
4486 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4487 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4489 _EdgesOnShape& eos = data._edgesOnShape[iS];
4490 for ( size_t i = 0; i < eos._edges.size(); ++i )
4491 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4495 break; // no more inflating possible
4499 // Evaluate achieved thickness
4501 int nbActiveEdges = 0;
4502 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4504 _EdgesOnShape& eos = data._edgesOnShape[iS];
4505 if ( eos._edges.empty() ) continue;
4507 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4508 for ( size_t i = 0; i < eos._edges.size(); ++i )
4510 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4511 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4514 avgThick /= data._n2eMap.size();
4515 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4517 #ifdef BLOCK_INFLATION
4518 if ( nbActiveEdges == 0 )
4520 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4524 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4526 debugMsg( "-- Stop inflation since "
4527 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4528 << tgtThick * avgThick << " ) * " << safeFactor );
4533 limitStepSize( data, 0.25 * distToIntersection );
4534 if ( data._stepSizeNodes[0] )
4535 data._stepSize = data._stepSizeCoeff *
4536 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4538 } // while ( avgThick < 0.99 )
4541 return error("failed at the very first inflation step", data._index);
4543 if ( avgThick < 0.99 )
4545 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4547 data._proxyMesh->_warning.reset
4548 ( new SMESH_ComputeError (COMPERR_WARNING,
4549 SMESH_Comment("Thickness ") << tgtThick <<
4550 " of viscous layers not reached,"
4551 " average reached thickness is " << avgThick*tgtThick));
4555 // Restore position of src nodes moved by inflation on _noShrinkShapes
4556 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4557 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4559 _EdgesOnShape& eos = data._edgesOnShape[iS];
4560 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4561 for ( size_t i = 0; i < eos._edges.size(); ++i )
4563 restoreNoShrink( *eos._edges[ i ] );
4568 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4571 //================================================================================
4573 * \brief Improve quality of layer inner surface and check intersection
4575 //================================================================================
4577 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4579 double & distToIntersection)
4581 if ( data._nbShapesToSmooth == 0 )
4582 return true; // no shapes needing smoothing
4584 bool moved, improved;
4586 vector< _LayerEdge* > movedEdges, badEdges;
4587 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4588 vector< bool > isConcaveFace;
4590 SMESH_MesherHelper helper(*_mesh);
4591 Handle(ShapeAnalysis_Surface) surface;
4594 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4596 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4598 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4600 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4601 if ( !eos._toSmooth ||
4602 eos.ShapeType() != shapeType ||
4603 eos._edges.empty() )
4606 // already smoothed?
4607 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4608 // if ( !toSmooth ) continue;
4610 if ( !eos._hyp.ToSmooth() )
4612 // smooth disabled by the user; check validy only
4613 if ( !isFace ) continue;
4615 for ( size_t i = 0; i < eos._edges.size(); ++i )
4617 _LayerEdge* edge = eos._edges[i];
4618 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4619 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4621 // debugMsg( "-- Stop inflation. Bad simplex ("
4622 // << " "<< edge->_nodes[0]->GetID()
4623 // << " "<< edge->_nodes.back()->GetID()
4624 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4625 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4627 badEdges.push_back( edge );
4630 if ( !badEdges.empty() )
4634 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4638 continue; // goto the next EDGE or FACE
4642 if ( eos.SWOLType() == TopAbs_FACE )
4644 if ( !F.IsSame( eos._sWOL )) {
4645 F = TopoDS::Face( eos._sWOL );
4646 helper.SetSubShape( F );
4647 surface = helper.GetSurface( F );
4652 F.Nullify(); surface.Nullify();
4654 const TGeomID sInd = eos._shapeID;
4656 // perform smoothing
4658 if ( eos.ShapeType() == TopAbs_EDGE )
4660 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4662 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4664 // smooth on EDGE's (normally we should not get here)
4668 for ( size_t i = 0; i < eos._edges.size(); ++i )
4670 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4672 dumpCmd( SMESH_Comment("# end step ")<<step);
4674 while ( moved && step++ < 5 );
4679 else // smooth on FACE
4682 eosC1.push_back( & eos );
4683 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4686 isConcaveFace.resize( eosC1.size() );
4687 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4689 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4690 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4691 for ( size_t i = 0; i < edges.size(); ++i )
4692 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4693 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4694 movedEdges.push_back( edges[i] );
4696 makeOffsetSurface( *eosC1[ iEOS ], helper );
4699 int step = 0, stepLimit = 5, nbBad = 0;
4700 while (( ++step <= stepLimit ) || improved )
4702 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4703 <<"_InfStep"<<infStep<<"_"<<step); // debug
4704 int oldBadNb = nbBad;
4707 #ifdef INCREMENTAL_SMOOTH
4708 bool findBest = false; // ( step == stepLimit );
4709 for ( size_t i = 0; i < movedEdges.size(); ++i )
4711 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4712 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4713 badEdges.push_back( movedEdges[i] );
4716 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4717 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4719 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4720 for ( size_t i = 0; i < edges.size(); ++i )
4722 edges[i]->Unset( _LayerEdge::SMOOTHED );
4723 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4724 badEdges.push_back( eos._edges[i] );
4728 nbBad = badEdges.size();
4731 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4733 if ( !badEdges.empty() && step >= stepLimit / 2 )
4735 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4738 // resolve hard smoothing situation around concave VERTEXes
4739 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4741 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4742 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4743 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4746 // look for the best smooth of _LayerEdge's neighboring badEdges
4748 for ( size_t i = 0; i < badEdges.size(); ++i )
4750 _LayerEdge* ledge = badEdges[i];
4751 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4753 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4754 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4756 ledge->Unset( _LayerEdge::SMOOTHED );
4757 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4759 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4762 if ( nbBad == oldBadNb &&
4764 step < stepLimit ) // smooth w/o chech of validity
4767 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4768 <<"_InfStep"<<infStep<<"_"<<step); // debug
4769 for ( size_t i = 0; i < movedEdges.size(); ++i )
4771 movedEdges[i]->SmoothWoCheck();
4773 if ( stepLimit < 9 )
4777 improved = ( nbBad < oldBadNb );
4781 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4782 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4784 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4787 } // smoothing steps
4789 // project -- to prevent intersections or fix bad simplices
4790 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4792 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4793 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4796 //if ( !badEdges.empty() )
4799 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4801 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4803 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4805 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4806 edge->CheckNeiborsOnBoundary( & badEdges );
4807 if (( nbBad > 0 ) ||
4808 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4810 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4811 gp_XYZ prevXYZ = edge->PrevCheckPos();
4812 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4813 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4815 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4816 << " "<< tgtXYZ._node->GetID()
4817 << " "<< edge->_simplices[j]._nPrev->GetID()
4818 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4819 badEdges.push_back( edge );
4826 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4827 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4833 } // // smooth on FACE's
4835 } // smooth on [ EDGEs, FACEs ]
4837 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4839 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4841 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4842 if ( eos.ShapeType() == TopAbs_FACE ||
4843 eos._edges.empty() ||
4844 !eos._sWOL.IsNull() )
4848 for ( size_t i = 0; i < eos._edges.size(); ++i )
4850 _LayerEdge* edge = eos._edges[i];
4851 if ( edge->_nodes.size() < 2 ) continue;
4852 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4853 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4854 //const gp_XYZ& prevXYZ = edge->PrevPos();
4855 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4856 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4858 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4859 << " "<< tgtXYZ._node->GetID()
4860 << " "<< edge->_simplices[j]._nPrev->GetID()
4861 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4862 badEdges.push_back( edge );
4867 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4869 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4875 // Check if the last segments of _LayerEdge intersects 2D elements;
4876 // checked elements are either temporary faces or faces on surfaces w/o the layers
4878 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4879 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4880 data._proxyMesh->GetFaces( data._solid )) );
4882 #ifdef BLOCK_INFLATION
4883 const bool toBlockInfaltion = true;
4885 const bool toBlockInfaltion = false;
4887 distToIntersection = Precision::Infinite();
4889 const SMDS_MeshElement* intFace = 0;
4890 const SMDS_MeshElement* closestFace = 0;
4892 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4894 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4895 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4897 for ( size_t i = 0; i < eos._edges.size(); ++i )
4899 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4900 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4902 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4905 // commented due to "Illegal hash-positionPosition" error in NETGEN
4906 // on Debian60 on viscous_layers_01/B2 case
4907 // Collision; try to deflate _LayerEdge's causing it
4908 // badEdges.clear();
4909 // badEdges.push_back( eos._edges[i] );
4910 // eosC1[0] = & eos;
4911 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4915 // badEdges.clear();
4916 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4918 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4920 // const SMDS_MeshElement* srcFace =
4921 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4922 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4923 // while ( nIt->more() )
4925 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4926 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4927 // if ( n2e != data._n2eMap.end() )
4928 // badEdges.push_back( n2e->second );
4931 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4936 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4943 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4948 const bool isShorterDist = ( distToIntersection > dist );
4949 if ( toBlockInfaltion || isShorterDist )
4951 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4952 // lying on this _ConvexFace
4953 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4954 if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4957 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4958 // ( avoid limiting the thickness on the case of issue 22576)
4959 if ( intFace->getshapeId() == eos._shapeID )
4962 // ignore intersection with intFace of an adjacent FACE
4965 bool toIgnore = false;
4966 if ( eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4968 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4969 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4971 TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4972 for ( ; !toIgnore && edge.More(); edge.Next() )
4973 // is adjacent - has a common EDGE
4974 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4976 if ( toIgnore ) // check angle between normals
4979 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4980 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
4984 if ( !toIgnore ) // check if the edge is a neighbor of intFace
4986 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
4988 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4989 toIgnore = ( nInd >= 0 );
4996 // intersection not ignored
4998 if ( toBlockInfaltion &&
4999 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5001 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5002 eos._edges[i]->Block( data ); // not to inflate
5004 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5006 // block _LayerEdge's, on top of which intFace is
5007 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5009 const SMDS_MeshElement* srcFace =
5010 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5011 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5012 while ( nIt->more() )
5014 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5015 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5016 if ( n2e != data._n2eMap.end() )
5017 n2e->second->Block( data );
5023 if ( isShorterDist )
5025 distToIntersection = dist;
5027 closestFace = intFace;
5030 } // if ( toBlockInfaltion || isShorterDist )
5031 } // loop on eos._edges
5032 } // loop on data._edgesOnShape
5034 if ( closestFace && le )
5037 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5038 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5039 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5040 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5041 << ") distance = " << distToIntersection<< endl;
5048 //================================================================================
5050 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5051 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5052 * \return int - resulting nb of bad _LayerEdge's
5054 //================================================================================
5056 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5057 SMESH_MesherHelper& helper,
5058 vector< _LayerEdge* >& badSmooEdges,
5059 vector< _EdgesOnShape* >& eosC1,
5062 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5064 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5067 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5068 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5069 ADDED = _LayerEdge::UNUSED_FLAG * 4
5071 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5074 bool haveInvalidated = true;
5075 while ( haveInvalidated )
5077 haveInvalidated = false;
5078 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5080 _LayerEdge* edge = badSmooEdges[i];
5081 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5083 bool invalidated = false;
5084 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5086 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5087 edge->Block( data );
5088 edge->Set( INVALIDATED );
5089 edge->Unset( TO_INVALIDATE );
5091 haveInvalidated = true;
5094 // look for _LayerEdge's of bad _simplices
5096 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5097 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5098 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5099 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5101 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5102 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5106 _LayerEdge* ee[2] = { 0,0 };
5107 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5108 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5109 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5111 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5112 while ( maxNbSteps > edge->NbSteps() && isBad )
5115 for ( int iE = 0; iE < 2; ++iE )
5117 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5118 ee[ iE ]->NbSteps() > 1 )
5120 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5121 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5122 ee[ iE ]->Block( data );
5123 ee[ iE ]->Set( INVALIDATED );
5124 haveInvalidated = true;
5127 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5128 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5132 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5133 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5134 ee[0]->Set( ADDED );
5135 ee[1]->Set( ADDED );
5138 ee[0]->Set( TO_INVALIDATE );
5139 ee[1]->Set( TO_INVALIDATE );
5143 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5145 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5146 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5147 edge->Block( data );
5148 edge->Set( INVALIDATED );
5149 edge->Unset( TO_INVALIDATE );
5150 haveInvalidated = true;
5152 } // loop on badSmooEdges
5153 } // while ( haveInvalidated )
5155 // re-smooth on analytical EDGEs
5156 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5158 _LayerEdge* edge = badSmooEdges[i];
5159 if ( !edge->Is( INVALIDATED )) continue;
5161 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5162 if ( eos->ShapeType() == TopAbs_VERTEX )
5164 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5165 while ( const TopoDS_Shape* e = eIt->next() )
5166 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5167 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5169 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5170 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5171 // F = TopoDS::Face( eoe->_sWOL );
5172 // surface = helper.GetSurface( F );
5174 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5175 eoe->_edgeSmoother->_anaCurve.Nullify();
5181 // check result of invalidation
5184 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5186 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5188 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5189 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5190 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5191 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5192 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5193 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5196 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5197 << " "<< tgtXYZ._node->GetID()
5198 << " "<< edge->_simplices[j]._nPrev->GetID()
5199 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5208 //================================================================================
5210 * \brief Create an offset surface
5212 //================================================================================
5214 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5216 if ( eos._offsetSurf.IsNull() ||
5217 eos._edgeForOffset == 0 ||
5218 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5221 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5224 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5225 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5226 double offset = baseSurface->Gap();
5228 eos._offsetSurf.Nullify();
5232 BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5233 if ( !offsetMaker.IsDone() ) return;
5235 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5236 if ( !fExp.More() ) return;
5238 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5239 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5240 if ( surf.IsNull() ) return;
5242 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5244 catch ( Standard_Failure )
5249 //================================================================================
5251 * \brief Put nodes of a curved FACE to its offset surface
5253 //================================================================================
5255 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5257 vector< _EdgesOnShape* >& eosC1,
5261 _EdgesOnShape * eof = & eos;
5262 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5265 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5267 if ( eosC1[i]->_offsetSurf.IsNull() ||
5268 eosC1[i]->ShapeType() != TopAbs_FACE ||
5269 eosC1[i]->_edgeForOffset == 0 ||
5270 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5272 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5277 eof->_offsetSurf.IsNull() ||
5278 eof->ShapeType() != TopAbs_FACE ||
5279 eof->_edgeForOffset == 0 ||
5280 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5283 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5284 for ( size_t i = 0; i < eos._edges.size(); ++i )
5286 _LayerEdge* edge = eos._edges[i];
5287 edge->Unset( _LayerEdge::MARKED );
5288 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5290 if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5293 int nbBlockedAround = 0;
5294 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5295 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5296 if ( nbBlockedAround > 1 )
5299 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5300 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5301 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5302 edge->_curvature->_uv = uv;
5303 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5305 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5306 gp_XYZ prevP = edge->PrevCheckPos();
5309 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5311 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5315 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5316 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5317 edge->_pos.back() = newP;
5319 edge->Set( _LayerEdge::MARKED );
5324 // dumpMove() for debug
5326 for ( ; i < eos._edges.size(); ++i )
5327 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5329 if ( i < eos._edges.size() )
5331 dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5332 << "_InfStep" << infStep << "_" << smooStep );
5333 for ( ; i < eos._edges.size(); ++i )
5335 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5336 dumpMove( eos._edges[i]->_nodes.back() );
5343 //================================================================================
5345 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5346 * _LayerEdge's to be in a consequent order
5348 //================================================================================
5350 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5352 SMESH_MesherHelper& helper)
5354 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5356 TopLoc_Location loc; double f,l;
5358 Handle(Geom_Line) line;
5359 Handle(Geom_Circle) circle;
5360 bool isLine, isCirc;
5361 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5363 // check if the EDGE is a line
5364 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5365 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5366 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5368 line = Handle(Geom_Line)::DownCast( curve );
5369 circle = Handle(Geom_Circle)::DownCast( curve );
5370 isLine = (!line.IsNull());
5371 isCirc = (!circle.IsNull());
5373 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5375 isLine = SMESH_Algo::IsStraight( E );
5378 line = new Geom_Line( gp::OX() ); // only type does matter
5380 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5385 else //////////////////////////////////////////////////////////////////////// 2D case
5387 if ( !eos._isRegularSWOL ) // 23190
5390 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5392 // check if the EDGE is a line
5393 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5394 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5395 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5397 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5398 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5399 isLine = (!line2d.IsNull());
5400 isCirc = (!circle2d.IsNull());
5402 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5405 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5406 while ( nIt->more() )
5407 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5408 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5410 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5411 for ( int i = 0; i < 2 && !isLine; ++i )
5412 isLine = ( size.Coord( i+1 ) <= lineTol );
5414 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5420 line = new Geom_Line( gp::OX() ); // only type does matter
5424 gp_Pnt2d p = circle2d->Location();
5425 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5426 circle = new Geom_Circle( ax, 1.); // only center position does matter
5435 return Handle(Geom_Curve)();
5438 //================================================================================
5440 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5442 //================================================================================
5444 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5445 Handle(ShapeAnalysis_Surface)& surface,
5446 const TopoDS_Face& F,
5447 SMESH_MesherHelper& helper)
5449 if ( !isAnalytic() ) return false;
5451 const size_t iFrom = 0, iTo = _eos._edges.size();
5453 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5455 if ( F.IsNull() ) // 3D
5457 SMESH_TNodeXYZ p0 ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5458 SMESH_TNodeXYZ p1 ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5459 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5460 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5461 gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5462 _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5463 _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5464 bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5465 vLE0->Is( _LayerEdge::BLOCKED ) ||
5466 vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5467 vLE1->Is( _LayerEdge::BLOCKED ));
5468 for ( size_t i = iFrom; i < iTo; ++i )
5470 _LayerEdge* edge = _eos._edges[i];
5471 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5472 newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5474 if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5476 gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5477 double shift = ( lineDir * ( newPos - pSrc0 ) -
5478 lineDir * ( curPos - pSrc0 ));
5479 newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5481 if ( edge->Is( _LayerEdge::BLOCKED ))
5483 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5484 double curThick = pSrc.SquareDistance( tgtNode );
5485 double newThink = ( pSrc - newPos ).SquareModulus();
5486 if ( newThink > curThick )
5489 edge->_pos.back() = newPos;
5490 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5491 dumpMove( tgtNode );
5496 _LayerEdge* e0 = getLEdgeOnV( 0 );
5497 _LayerEdge* e1 = getLEdgeOnV( 1 );
5498 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5499 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5500 if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5502 int iPeriodic = helper.GetPeriodicIndex();
5503 if ( iPeriodic == 1 || iPeriodic == 2 )
5505 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5506 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5507 std::swap( uv0, uv1 );
5510 const gp_XY rangeUV = uv1 - uv0;
5511 for ( size_t i = iFrom; i < iTo; ++i )
5513 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5514 gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5515 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5517 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5518 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5519 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5520 dumpMove( tgtNode );
5522 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5523 pos->SetUParameter( newUV.X() );
5524 pos->SetVParameter( newUV.Y() );
5530 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5532 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5533 gp_Pnt center3D = circle->Location();
5535 if ( F.IsNull() ) // 3D
5537 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5538 return true; // closed EDGE - nothing to do
5540 // circle is a real curve of EDGE
5541 gp_Circ circ = circle->Circ();
5543 // new center is shifted along its axis
5544 const gp_Dir& axis = circ.Axis().Direction();
5545 _LayerEdge* e0 = getLEdgeOnV(0);
5546 _LayerEdge* e1 = getLEdgeOnV(1);
5547 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5548 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5549 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5550 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5551 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5553 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5555 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5556 gp_Circ newCirc( newAxis, newRadius );
5557 gp_Vec vecC1 ( newCenter, p1 );
5559 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5563 for ( size_t i = iFrom; i < iTo; ++i )
5565 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5566 double u = uLast * _leParams[i];
5567 gp_Pnt p = ElCLib::Value( u, newCirc );
5568 _eos._edges[i]->_pos.back() = p.XYZ();
5570 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5571 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5572 dumpMove( tgtNode );
5578 const gp_XY center( center3D.X(), center3D.Y() );
5580 _LayerEdge* e0 = getLEdgeOnV(0);
5581 _LayerEdge* eM = _eos._edges[ 0 ];
5582 _LayerEdge* e1 = getLEdgeOnV(1);
5583 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5584 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5585 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5586 gp_Vec2d vec0( center, uv0 );
5587 gp_Vec2d vecM( center, uvM );
5588 gp_Vec2d vec1( center, uv1 );
5589 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5590 double uMidl = vec0.Angle( vecM );
5591 if ( uLast * uMidl <= 0. )
5592 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5593 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5595 gp_Ax2d axis( center, vec0 );
5596 gp_Circ2d circ( axis, radius );
5597 for ( size_t i = iFrom; i < iTo; ++i )
5599 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5600 double newU = uLast * _leParams[i];
5601 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5602 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5604 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5605 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5606 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5607 dumpMove( tgtNode );
5609 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5610 pos->SetUParameter( newUV.X() );
5611 pos->SetVParameter( newUV.Y() );
5620 //================================================================================
5622 * \brief smooth _LayerEdge's on a an EDGE
5624 //================================================================================
5626 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5627 Handle(ShapeAnalysis_Surface)& surface,
5628 const TopoDS_Face& F,
5629 SMESH_MesherHelper& helper)
5631 if ( _offPoints.empty() )
5634 // move _offPoints along normals of _LayerEdge's
5636 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5637 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5638 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5639 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5640 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5641 _leOnV[0]._len = e[0]->_len;
5642 _leOnV[1]._len = e[1]->_len;
5643 for ( size_t i = 0; i < _offPoints.size(); i++ )
5645 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5646 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5647 const double w0 = _offPoints[i]._2edges._wgt[0];
5648 const double w1 = _offPoints[i]._2edges._wgt[1];
5649 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5650 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5651 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5652 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5653 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5654 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5656 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5657 _offPoints[i]._len = avgLen;
5661 if ( !surface.IsNull() ) // project _offPoints to the FACE
5663 fTol = 100 * BRep_Tool::Tolerance( F );
5664 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5666 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5667 //if ( surface->Gap() < 0.5 * segLen )
5668 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5670 for ( size_t i = 1; i < _offPoints.size(); ++i )
5672 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5673 //if ( surface->Gap() < 0.5 * segLen )
5674 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5678 // project tgt nodes of extreme _LayerEdge's to the offset segments
5680 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5681 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5683 gp_Pnt pExtreme[2], pProj[2];
5684 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5686 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5687 int i = _iSeg[ is2nd ];
5688 int di = is2nd ? -1 : +1;
5689 bool projected = false;
5690 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5693 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5694 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5695 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5696 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5697 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5698 if ( dist < distMin || projected )
5701 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5704 else if ( dist > distPrev )
5706 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5712 while ( !projected &&
5713 i >= 0 && i+1 < (int)_offPoints.size() );
5717 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5720 _iSeg[1] = _offPoints.size()-2;
5721 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5726 if ( _iSeg[0] > _iSeg[1] )
5728 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5732 // adjust length of extreme LE (test viscous_layers_01/B7)
5733 gp_Vec vDiv0( pExtreme[0], pProj[0] );
5734 gp_Vec vDiv1( pExtreme[1], pProj[1] );
5735 double d0 = vDiv0.Magnitude();
5736 double d1 = vDiv1.Magnitude();
5737 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5738 else e[0]->_len -= d0;
5739 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5740 else e[1]->_len -= d1;
5742 // compute normalized length of the offset segments located between the projections
5744 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5745 vector< double > len( nbSeg + 1 );
5747 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5748 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5750 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5752 len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5754 // d0 *= e[0]->_lenFactor;
5755 // d1 *= e[1]->_lenFactor;
5756 double fullLen = len.back() - d0 - d1;
5757 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5758 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5760 // temporary replace extreme _offPoints by pExtreme
5761 gp_XYZ op[2] = { _offPoints[ _iSeg[0] ]._xyz,
5762 _offPoints[ _iSeg[1]+1 ]._xyz };
5763 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
5764 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5766 // distribute tgt nodes of _LayerEdge's between the projections
5769 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5771 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5772 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5774 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5775 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
5776 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5778 if ( surface.IsNull() )
5780 _eos._edges[i]->_pos.back() = p;
5782 else // project a new node position to a FACE
5784 gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5785 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5787 p = surface->Value( uv2 ).XYZ();
5788 _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5790 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5791 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5792 dumpMove( tgtNode );
5795 _offPoints[ _iSeg[0] ]._xyz = op[0];
5796 _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5801 //================================================================================
5803 * \brief Prepare for smoothing
5805 //================================================================================
5807 void _Smoother1D::prepare(_SolidData& data)
5809 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5810 _curveLen = SMESH_Algo::EdgeLength( E );
5812 // sort _LayerEdge's by position on the EDGE
5813 data.SortOnEdge( E, _eos._edges );
5815 // compute normalized param of _eos._edges on EDGE
5816 _leParams.resize( _eos._edges.size() + 1 );
5819 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5821 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5823 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5824 curLen = p.Distance( pPrev );
5825 _leParams[i+1] = _leParams[i] + curLen;
5828 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5829 for ( size_t i = 0; i < _leParams.size()-1; ++i )
5830 _leParams[i] = _leParams[i+1] / fullLen;
5836 // divide E to have offset segments with low deflection
5837 BRepAdaptor_Curve c3dAdaptor( E );
5838 const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5839 const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5840 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5841 if ( discret.NbPoints() <= 2 )
5843 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5847 const double u0 = c3dAdaptor.FirstParameter();
5848 gp_Pnt p; gp_Vec tangent;
5849 _offPoints.resize( discret.NbPoints() );
5850 for ( size_t i = 0; i < _offPoints.size(); i++ )
5852 double u = discret.Parameter( i+1 );
5853 c3dAdaptor.D1( u, p, tangent );
5854 _offPoints[i]._xyz = p.XYZ();
5855 _offPoints[i]._edgeDir = tangent.XYZ();
5856 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5859 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5862 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5863 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5864 _2NearEdges tmp2edges;
5865 tmp2edges._edges[1] = _eos._edges[0];
5866 _leOnV[0]._2neibors = & tmp2edges;
5867 _leOnV[0]._nodes = leOnV[0]->_nodes;
5868 _leOnV[1]._nodes = leOnV[1]->_nodes;
5869 _LayerEdge* eNext, *ePrev = & _leOnV[0];
5870 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5872 // find _LayerEdge's located before and after an offset point
5873 // (_eos._edges[ iLE ] is next after ePrev)
5874 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5875 ePrev = _eos._edges[ iLE++ ];
5876 eNext = ePrev->_2neibors->_edges[1];
5878 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5879 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5880 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5881 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5884 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5885 for ( size_t i = 0; i < _offPoints.size(); i++ )
5886 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5887 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5889 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5890 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5891 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5894 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5896 int iLBO = _offPoints.size() - 2; // last but one
5898 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5899 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5901 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5902 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5903 _leOnV[ 0 ]._len = 0;
5904 _leOnV[ 1 ]._len = 0;
5905 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
5906 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5909 _iSeg[1] = _offPoints.size()-2;
5911 // initialize OffPnt::_len
5912 for ( size_t i = 0; i < _offPoints.size(); ++i )
5913 _offPoints[i]._len = 0;
5915 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5917 _leOnV[0]._len = leOnV[0]->_len;
5918 _leOnV[1]._len = leOnV[1]->_len;
5919 for ( size_t i = 0; i < _offPoints.size(); i++ )
5921 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5922 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5923 const double w0 = _offPoints[i]._2edges._wgt[0];
5924 const double w1 = _offPoints[i]._2edges._wgt[1];
5925 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5926 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5927 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5928 _offPoints[i]._xyz = avgXYZ;
5929 _offPoints[i]._len = avgLen;
5934 //================================================================================
5936 * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5938 //================================================================================
5940 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5941 const gp_XYZ& edgeDir)
5943 gp_XYZ cross = normal ^ edgeDir;
5944 gp_XYZ norm = edgeDir ^ cross;
5945 double size = norm.Modulus();
5950 //================================================================================
5952 * \brief Sort _LayerEdge's by a parameter on a given EDGE
5954 //================================================================================
5956 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
5957 vector< _LayerEdge* >& edges)
5959 map< double, _LayerEdge* > u2edge;
5960 for ( size_t i = 0; i < edges.size(); ++i )
5961 u2edge.insert( u2edge.end(),
5962 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5964 ASSERT( u2edge.size() == edges.size() );
5965 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5966 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5967 edges[i] = u2e->second;
5969 Sort2NeiborsOnEdge( edges );
5972 //================================================================================
5974 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5976 //================================================================================
5978 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5980 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5982 for ( size_t i = 0; i < edges.size()-1; ++i )
5983 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5984 edges[i]->_2neibors->reverse();
5986 const size_t iLast = edges.size() - 1;
5987 if ( edges.size() > 1 &&
5988 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5989 edges[iLast]->_2neibors->reverse();
5992 //================================================================================
5994 * \brief Return _EdgesOnShape* corresponding to the shape
5996 //================================================================================
5998 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6000 if ( shapeID < (int)_edgesOnShape.size() &&
6001 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6002 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6004 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6005 if ( _edgesOnShape[i]._shapeID == shapeID )
6006 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6011 //================================================================================
6013 * \brief Return _EdgesOnShape* corresponding to the shape
6015 //================================================================================
6017 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6019 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6020 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6023 //================================================================================
6025 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6027 //================================================================================
6029 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6031 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6033 set< TGeomID > vertices;
6035 if ( eos->ShapeType() == TopAbs_FACE )
6037 // check FACE concavity and get concave VERTEXes
6038 F = TopoDS::Face( eos->_shape );
6039 if ( isConcave( F, helper, &vertices ))
6040 _concaveFaces.insert( eos->_shapeID );
6042 // set eos._eosConcaVer
6043 eos->_eosConcaVer.clear();
6044 eos->_eosConcaVer.reserve( vertices.size() );
6045 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6047 _EdgesOnShape* eov = GetShapeEdges( *v );
6048 if ( eov && eov->_edges.size() == 1 )
6050 eos->_eosConcaVer.push_back( eov );
6051 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6052 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6056 // SetSmooLen() to _LayerEdge's on FACE
6057 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6059 eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6061 SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6062 while ( smIt->more() ) // loop on sub-shapes of the FACE
6064 _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6065 if ( !eoe ) continue;
6067 vector<_LayerEdge*>& eE = eoe->_edges;
6068 for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6070 if ( eE[iE]->_cosin <= theMinSmoothCosin )
6073 SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6074 while ( segIt->more() )
6076 const SMDS_MeshElement* seg = segIt->next();
6077 if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6079 if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6080 continue; // not to check a seg twice
6081 for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6083 _LayerEdge* eN = eE[iE]->_neibors[iN];
6084 if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6086 double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6087 double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6088 eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6089 eN->Set( _LayerEdge::NEAR_BOUNDARY );
6094 } // if ( eos->ShapeType() == TopAbs_FACE )
6096 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6098 eos->_edges[i]->_smooFunction = 0;
6099 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6101 bool isCurved = false;
6102 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6104 _LayerEdge* edge = eos->_edges[i];
6106 // get simplices sorted
6107 _Simplex::SortSimplices( edge->_simplices );
6109 // smoothing function
6110 edge->ChooseSmooFunction( vertices, _n2eMap );
6113 double avgNormProj = 0, avgLen = 0;
6114 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6116 _Simplex& s = edge->_simplices[iS];
6118 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6119 avgNormProj += edge->_normal * vec;
6120 avgLen += vec.Modulus();
6121 if ( substituteSrcNodes )
6123 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6124 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6127 avgNormProj /= edge->_simplices.size();
6128 avgLen /= edge->_simplices.size();
6129 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6132 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6134 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6135 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6137 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6141 // prepare for putOnOffsetSurface()
6142 if (( eos->ShapeType() == TopAbs_FACE ) &&
6143 ( isCurved || !eos->_eosConcaVer.empty() ))
6145 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6146 eos->_edgeForOffset = 0;
6148 double maxCosin = -1;
6149 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6151 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6152 if ( !eoe || eoe->_edges.empty() ) continue;
6154 vector<_LayerEdge*>& eE = eoe->_edges;
6155 _LayerEdge* e = eE[ eE.size() / 2 ];
6156 if ( e->_cosin > maxCosin )
6158 eos->_edgeForOffset = e;
6159 maxCosin = e->_cosin;
6165 //================================================================================
6167 * \brief Add faces for smoothing
6169 //================================================================================
6171 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6172 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6174 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6175 for ( ; eos != eosToSmooth.end(); ++eos )
6177 if ( !*eos || (*eos)->_toSmooth ) continue;
6179 (*eos)->_toSmooth = true;
6181 if ( (*eos)->ShapeType() == TopAbs_FACE )
6183 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6184 (*eos)->_toSmooth = true;
6188 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6189 if ( edgesNoAnaSmooth )
6190 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6192 if ( (*eos)->_edgeSmoother )
6193 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6197 //================================================================================
6199 * \brief Limit _LayerEdge::_maxLen according to local curvature
6201 //================================================================================
6203 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6205 // find intersection of neighbor _LayerEdge's to limit _maxLen
6206 // according to local curvature (IPAL52648)
6208 // This method must be called after findCollisionEdges() where _LayerEdge's
6209 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6211 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6213 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6214 if ( eosI._edges.empty() ) continue;
6215 if ( !eosI._hyp.ToSmooth() )
6217 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6219 _LayerEdge* eI = eosI._edges[i];
6220 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6222 _LayerEdge* eN = eI->_neibors[iN];
6223 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6225 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6226 limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6231 else if ( eosI.ShapeType() == TopAbs_EDGE )
6233 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6234 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6236 _LayerEdge* e0 = eosI._edges[0];
6237 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6239 _LayerEdge* eI = eosI._edges[i];
6240 limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6247 //================================================================================
6249 * \brief Limit _LayerEdge::_maxLen according to local curvature
6251 //================================================================================
6253 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6255 _EdgesOnShape& eos1,
6256 _EdgesOnShape& eos2,
6257 SMESH_MesherHelper& helper )
6259 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6260 double norSize = plnNorm.SquareModulus();
6261 if ( norSize < std::numeric_limits<double>::min() )
6262 return; // parallel normals
6264 // find closest points of skew _LayerEdge's
6265 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6266 gp_XYZ dir12 = src2 - src1;
6267 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6268 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6269 double dot1 = perp2 * e1->_normal;
6270 double dot2 = perp1 * e2->_normal;
6271 double u1 = ( perp2 * dir12 ) / dot1;
6272 double u2 = - ( perp1 * dir12 ) / dot2;
6273 if ( u1 > 0 && u2 > 0 )
6275 double ovl = ( u1 * e1->_normal * dir12 -
6276 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6277 if ( ovl > theSmoothThickToElemSizeRatio )
6279 e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6280 e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6285 //================================================================================
6287 * \brief Fill data._collisionEdges
6289 //================================================================================
6291 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6293 data._collisionEdges.clear();
6295 // set the full thickness of the layers to LEs
6296 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6298 _EdgesOnShape& eos = data._edgesOnShape[iS];
6299 if ( eos._edges.empty() ) continue;
6300 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6302 for ( size_t i = 0; i < eos._edges.size(); ++i )
6304 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6305 double maxLen = eos._edges[i]->_maxLen;
6306 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6307 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6308 eos._edges[i]->_maxLen = maxLen;
6312 // make temporary quadrangles got by extrusion of
6313 // mesh edges along _LayerEdge._normal's
6315 vector< const SMDS_MeshElement* > tmpFaces;
6317 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6319 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6320 if ( eos.ShapeType() != TopAbs_EDGE )
6322 if ( eos._edges.empty() )
6324 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6325 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6326 while ( smIt->more() )
6327 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6328 if ( eov->_edges.size() == 1 )
6329 edge[ bool( edge[0]) ] = eov->_edges[0];
6333 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6334 tmpFaces.push_back( f );
6337 for ( size_t i = 0; i < eos._edges.size(); ++i )
6339 _LayerEdge* edge = eos._edges[i];
6340 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6342 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6343 if ( src2->GetPosition()->GetDim() > 0 &&
6344 src2->GetID() < edge->_nodes[0]->GetID() )
6345 continue; // avoid using same segment twice
6347 // a _LayerEdge containg tgt2
6348 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6350 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6351 tmpFaces.push_back( f );
6356 // Find _LayerEdge's intersecting tmpFaces.
6358 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6360 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6361 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6363 double dist1, dist2, segLen, eps = 0.5;
6364 _CollisionEdges collEdges;
6365 vector< const SMDS_MeshElement* > suspectFaces;
6366 const double angle45 = Cos( 45. * M_PI / 180. );
6368 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6370 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6371 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6373 // find sub-shapes whose VL can influence VL on eos
6374 set< TGeomID > neighborShapes;
6375 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6376 while ( const TopoDS_Shape* face = fIt->next() )
6378 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6379 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6381 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6382 while ( subIt->more() )
6383 neighborShapes.insert( subIt->next()->GetId() );
6386 if ( eos.ShapeType() == TopAbs_VERTEX )
6388 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6389 while ( const TopoDS_Shape* edge = eIt->next() )
6390 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6392 // find intersecting _LayerEdge's
6393 for ( size_t i = 0; i < eos._edges.size(); ++i )
6395 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6396 _LayerEdge* edge = eos._edges[i];
6397 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6400 gp_Vec eSegDir0, eSegDir1;
6401 if ( edge->IsOnEdge() )
6403 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6404 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6405 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6407 suspectFaces.clear();
6408 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6409 SMDSAbs_Face, suspectFaces );
6410 collEdges._intEdges.clear();
6411 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6413 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6414 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6415 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6416 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6417 if ( edge->IsOnEdge() ) {
6418 if ( edge->_2neibors->include( f->_le1 ) ||
6419 edge->_2neibors->include( f->_le2 )) continue;
6422 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6423 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6425 dist1 = dist2 = Precision::Infinite();
6426 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6427 dist1 = Precision::Infinite();
6428 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6429 dist2 = Precision::Infinite();
6430 if (( dist1 > segLen ) && ( dist2 > segLen ))
6433 if ( edge->IsOnEdge() )
6435 // skip perpendicular EDGEs
6436 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6437 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6438 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6439 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6440 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6445 // either limit inflation of edges or remember them for updating _normal
6446 // double dot = edge->_normal * f->GetDir();
6449 collEdges._intEdges.push_back( f->_le1 );
6450 collEdges._intEdges.push_back( f->_le2 );
6454 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6455 // edge->_maxLen = Min( shortLen, edge->_maxLen );
6459 if ( !collEdges._intEdges.empty() )
6461 collEdges._edge = edge;
6462 data._collisionEdges.push_back( collEdges );
6467 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6470 // restore the zero thickness
6471 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6473 _EdgesOnShape& eos = data._edgesOnShape[iS];
6474 if ( eos._edges.empty() ) continue;
6475 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6477 for ( size_t i = 0; i < eos._edges.size(); ++i )
6479 eos._edges[i]->InvalidateStep( 1, eos );
6480 eos._edges[i]->_len = 0;
6485 //================================================================================
6487 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6488 * _LayerEdge's on neighbor EDGE's
6490 //================================================================================
6492 bool _ViscousBuilder::updateNormals( _SolidData& data,
6493 SMESH_MesherHelper& helper,
6497 updateNormalsOfC1Vertices( data );
6499 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6502 // map to store new _normal and _cosin for each intersected edge
6503 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6504 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6505 _LayerEdge zeroEdge;
6506 zeroEdge._normal.SetCoord( 0,0,0 );
6507 zeroEdge._maxLen = Precision::Infinite();
6508 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6510 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6512 double segLen, dist1, dist2, dist;
6513 vector< pair< _LayerEdge*, double > > intEdgesDist;
6514 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6516 for ( int iter = 0; iter < 5; ++iter )
6518 edge2newEdge.clear();
6520 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6522 _CollisionEdges& ce = data._collisionEdges[iE];
6523 _LayerEdge* edge1 = ce._edge;
6524 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6525 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6526 if ( !eos1 ) continue;
6528 // detect intersections
6529 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6530 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6532 intEdgesDist.clear();
6533 double minIntDist = Precision::Infinite();
6534 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6536 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6537 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6538 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6540 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6541 double fact = ( 1.1 + dot * dot );
6542 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6543 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6544 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6545 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6546 dist1 = dist2 = Precision::Infinite();
6547 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
6548 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6551 if ( dist > testLen || dist <= 0 )
6554 if ( dist > testLen || dist <= 0 )
6557 // choose a closest edge
6558 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6559 double d1 = intP.SquareDistance( pSrc0 );
6560 double d2 = intP.SquareDistance( pSrc1 );
6561 int iClose = i + ( d2 < d1 );
6562 _LayerEdge* edge2 = ce._intEdges[iClose];
6563 edge2->Unset( _LayerEdge::MARKED );
6565 // choose a closest edge among neighbors
6566 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6567 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6568 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6570 _LayerEdge * edgeJ = intEdgesDist[j].first;
6571 if ( edge2->IsNeiborOnEdge( edgeJ ))
6573 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6574 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6577 intEdgesDist.push_back( make_pair( edge2, dist ));
6578 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6580 // iClose = i + !( d2 < d1 );
6581 // intEdges.push_back( ce._intEdges[iClose] );
6582 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6584 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6589 // compute new _normals
6590 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6592 _LayerEdge* edge2 = intEdgesDist[i].first;
6593 double distWgt = edge1->_len / intEdgesDist[i].second;
6594 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6595 // edge2->Is( _LayerEdge::BLOCKED )) continue;
6596 if ( edge2->Is( _LayerEdge::MARKED )) continue;
6597 edge2->Set( _LayerEdge::MARKED );
6600 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6602 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6603 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6604 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6605 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6606 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6607 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6608 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6609 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6610 newNormal.Normalize();
6614 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6615 if ( cos1 < theMinSmoothCosin )
6617 newCos = cos2 * sgn1;
6619 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6621 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6625 newCos = edge1->_cosin;
6628 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6629 e2neIt->second._normal += distWgt * newNormal;
6630 e2neIt->second._cosin = newCos;
6631 e2neIt->second._maxLen = 0.7 * minIntDist / edge1->_lenFactor;
6632 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6633 e2neIt->second._normal += dir2;
6634 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6635 e2neIt->second._normal += distWgt * newNormal;
6636 e2neIt->second._cosin = edge2->_cosin;
6637 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6638 e2neIt->second._normal += dir1;
6642 if ( edge2newEdge.empty() )
6643 break; //return true;
6645 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6647 // Update data of edges depending on a new _normal
6650 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6652 _LayerEdge* edge = e2neIt->first;
6653 if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6654 _LayerEdge& newEdge = e2neIt->second;
6655 _EdgesOnShape* eos = data.GetShapeEdges( edge );
6657 // Check if a new _normal is OK:
6658 newEdge._normal.Normalize();
6659 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6661 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6663 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6664 edge->_maxLen = newEdge._maxLen;
6665 edge->SetNewLength( newEdge._maxLen, *eos, helper );
6667 continue; // the new _normal is bad
6669 // the new _normal is OK
6671 // find shapes that need smoothing due to change of _normal
6672 if ( edge->_cosin < theMinSmoothCosin &&
6673 newEdge._cosin > theMinSmoothCosin )
6675 if ( eos->_sWOL.IsNull() )
6677 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6678 while ( fIt->more() )
6679 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6681 else // edge inflates along a FACE
6683 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6684 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
6685 while ( const TopoDS_Shape* E = eIt->next() )
6687 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6688 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6689 if ( angle < M_PI / 2 )
6690 shapesToSmooth.insert( data.GetShapeEdges( *E ));
6695 double len = edge->_len;
6696 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6697 edge->SetNormal( newEdge._normal );
6698 edge->SetCosin( newEdge._cosin );
6699 edge->SetNewLength( len, *eos, helper );
6700 edge->Set( _LayerEdge::MARKED );
6701 edge->Set( _LayerEdge::NORMAL_UPDATED );
6702 edgesNoAnaSmooth.insert( eos );
6705 // Update normals and other dependent data of not intersecting _LayerEdge's
6706 // neighboring the intersecting ones
6708 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6710 _LayerEdge* edge1 = e2neIt->first;
6711 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6712 if ( !edge1->Is( _LayerEdge::MARKED ))
6715 if ( edge1->IsOnEdge() )
6717 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6718 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6719 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6722 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6724 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6726 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6727 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6728 continue; // j-th neighbor is also intersected
6729 _LayerEdge* prevEdge = edge1;
6730 const int nbSteps = 10;
6731 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6733 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6734 neighbor->Is( _LayerEdge::MARKED ))
6736 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6737 if ( !eos ) continue;
6738 _LayerEdge* nextEdge = neighbor;
6739 if ( neighbor->_2neibors )
6742 nextEdge = neighbor->_2neibors->_edges[iNext];
6743 if ( nextEdge == prevEdge )
6744 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6746 double r = double(step-1)/nbSteps/(iter+1);
6747 if ( !nextEdge->_2neibors )
6750 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6751 newNorm.Normalize();
6752 if ( !isNewNormalOk( data, *neighbor, newNorm ))
6755 double len = neighbor->_len;
6756 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6757 neighbor->SetNormal( newNorm );
6758 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6759 if ( neighbor->_2neibors )
6760 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6761 neighbor->SetNewLength( len, *eos, helper );
6762 neighbor->Set( _LayerEdge::MARKED );
6763 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6764 edgesNoAnaSmooth.insert( eos );
6766 if ( !neighbor->_2neibors )
6767 break; // neighbor is on VERTEX
6769 // goto the next neighbor
6770 prevEdge = neighbor;
6771 neighbor = nextEdge;
6778 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6783 //================================================================================
6785 * \brief Check if a new normal is OK
6787 //================================================================================
6789 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
6791 const gp_XYZ& newNormal)
6793 // check a min angle between the newNormal and surrounding faces
6794 vector<_Simplex> simplices;
6795 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6796 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6797 double newMinDot = 1, curMinDot = 1;
6798 for ( size_t i = 0; i < simplices.size(); ++i )
6800 n1.Set( simplices[i]._nPrev );
6801 n2.Set( simplices[i]._nNext );
6802 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6803 double normLen2 = normFace.SquareModulus();
6804 if ( normLen2 < std::numeric_limits<double>::min() )
6806 normFace /= Sqrt( normLen2 );
6807 newMinDot = Min( newNormal * normFace, newMinDot );
6808 curMinDot = Min( edge._normal * normFace, curMinDot );
6811 if ( newMinDot < 0.5 )
6813 ok = ( newMinDot >= curMinDot * 0.9 );
6814 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6815 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6816 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6822 //================================================================================
6824 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6826 //================================================================================
6828 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
6829 SMESH_MesherHelper& helper,
6831 const double stepSize )
6833 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6834 return true; // no shapes needing smoothing
6836 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6838 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6839 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
6840 !eos._hyp.ToSmooth() ||
6841 eos.ShapeType() != TopAbs_FACE ||
6842 eos._edges.empty() )
6845 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6846 if ( !toSmooth ) continue;
6848 for ( size_t i = 0; i < eos._edges.size(); ++i )
6850 _LayerEdge* edge = eos._edges[i];
6851 if ( !edge->Is( _LayerEdge::SMOOTHED ))
6853 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6856 const gp_XYZ& pPrev = edge->PrevPos();
6857 const gp_XYZ& pLast = edge->_pos.back();
6858 gp_XYZ stepVec = pLast - pPrev;
6859 double realStepSize = stepVec.Modulus();
6860 if ( realStepSize < numeric_limits<double>::min() )
6863 edge->_lenFactor = realStepSize / stepSize;
6864 edge->_normal = stepVec / realStepSize;
6865 edge->Set( _LayerEdge::NORMAL_UPDATED );
6872 //================================================================================
6874 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6876 //================================================================================
6878 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6880 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6882 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6883 if ( eov._eosC1.empty() ||
6884 eov.ShapeType() != TopAbs_VERTEX ||
6885 eov._edges.empty() )
6888 gp_XYZ newNorm = eov._edges[0]->_normal;
6889 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6890 bool normChanged = false;
6892 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6894 _EdgesOnShape* eoe = eov._eosC1[i];
6895 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6896 const double eLen = SMESH_Algo::EdgeLength( e );
6897 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
6898 if ( oppV.IsSame( eov._shape ))
6899 oppV = SMESH_MesherHelper::IthVertex( 1, e );
6900 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6901 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6902 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6904 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6905 if ( curThickOpp + curThick < eLen )
6908 double wgt = 2. * curThick / eLen;
6909 newNorm += wgt * eovOpp->_edges[0]->_normal;
6914 eov._edges[0]->SetNormal( newNorm.Normalized() );
6915 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6920 //================================================================================
6922 * \brief Modify normals of _LayerEdge's on _ConvexFace's
6924 //================================================================================
6926 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
6927 SMESH_MesherHelper& helper,
6930 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6933 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6934 for ( ; id2face != data._convexFaces.end(); ++id2face )
6936 _ConvexFace & convFace = (*id2face).second;
6937 if ( convFace._normalsFixed )
6938 continue; // already fixed
6939 if ( convFace.CheckPrisms() )
6940 continue; // nothing to fix
6942 convFace._normalsFixed = true;
6944 BRepAdaptor_Surface surface ( convFace._face, false );
6945 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
6947 // check if the convex FACE is of spherical shape
6949 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6953 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6954 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6956 _EdgesOnShape& eos = *(id2eos->second);
6957 if ( eos.ShapeType() == TopAbs_VERTEX )
6959 _LayerEdge* ledge = eos._edges[ 0 ];
6960 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6961 centersBox.Add( center );
6963 for ( size_t i = 0; i < eos._edges.size(); ++i )
6964 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6966 if ( centersBox.IsVoid() )
6968 debugMsg( "Error: centersBox.IsVoid()" );
6971 const bool isSpherical =
6972 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6974 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6975 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6979 // set _LayerEdge::_normal as average of all normals
6981 // WARNING: different density of nodes on EDGEs is not taken into account that
6982 // can lead to an improper new normal
6984 gp_XYZ avgNormal( 0,0,0 );
6986 id2eos = convFace._subIdToEOS.begin();
6987 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6989 _EdgesOnShape& eos = *(id2eos->second);
6990 // set data of _CentralCurveOnEdge
6991 if ( eos.ShapeType() == TopAbs_EDGE )
6993 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6994 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6995 if ( !eos._sWOL.IsNull() )
6996 ceCurve._adjFace.Nullify();
6998 ceCurve._ledges.insert( ceCurve._ledges.end(),
6999 eos._edges.begin(), eos._edges.end());
7001 // summarize normals
7002 for ( size_t i = 0; i < eos._edges.size(); ++i )
7003 avgNormal += eos._edges[ i ]->_normal;
7005 double normSize = avgNormal.SquareModulus();
7006 if ( normSize < 1e-200 )
7008 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7011 avgNormal /= Sqrt( normSize );
7013 // compute new _LayerEdge::_cosin on EDGEs
7014 double avgCosin = 0;
7017 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7019 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7020 if ( ceCurve._adjFace.IsNull() )
7022 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7024 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7025 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7028 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7029 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7030 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7036 avgCosin /= nbCosin;
7038 // set _LayerEdge::_normal = avgNormal
7039 id2eos = convFace._subIdToEOS.begin();
7040 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7042 _EdgesOnShape& eos = *(id2eos->second);
7043 if ( eos.ShapeType() != TopAbs_EDGE )
7044 for ( size_t i = 0; i < eos._edges.size(); ++i )
7045 eos._edges[ i ]->_cosin = avgCosin;
7047 for ( size_t i = 0; i < eos._edges.size(); ++i )
7049 eos._edges[ i ]->SetNormal( avgNormal );
7050 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7054 else // if ( isSpherical )
7056 // We suppose that centers of curvature at all points of the FACE
7057 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7058 // having a common center of curvature we define the same new normal
7059 // as a sum of normals of _LayerEdge's on EDGEs among them.
7061 // get all centers of curvature for each EDGE
7063 helper.SetSubShape( convFace._face );
7064 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7066 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7067 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7069 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7071 // set adjacent FACE
7072 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7074 // get _LayerEdge's of the EDGE
7075 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7076 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7077 if ( !eos || eos->_edges.empty() )
7079 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7080 for ( int iV = 0; iV < 2; ++iV )
7082 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7083 TGeomID vID = meshDS->ShapeToIndex( v );
7084 eos = data.GetShapeEdges( vID );
7085 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7087 edgeLEdge = &vertexLEdges[0];
7088 edgeLEdgeEnd = edgeLEdge + 2;
7090 centerCurves[ iE ]._adjFace.Nullify();
7094 if ( ! eos->_toSmooth )
7095 data.SortOnEdge( edge, eos->_edges );
7096 edgeLEdge = &eos->_edges[ 0 ];
7097 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7098 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7099 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7101 if ( ! eos->_sWOL.IsNull() )
7102 centerCurves[ iE ]._adjFace.Nullify();
7105 // Get curvature centers
7109 if ( edgeLEdge[0]->IsOnEdge() &&
7110 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7112 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7113 centersBox.Add( center );
7115 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7116 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7117 { // EDGE or VERTEXes
7118 centerCurves[ iE ].Append( center, *edgeLEdge );
7119 centersBox.Add( center );
7121 if ( edgeLEdge[-1]->IsOnEdge() &&
7122 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7124 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7125 centersBox.Add( center );
7127 centerCurves[ iE ]._isDegenerated =
7128 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7130 } // loop on EDGES of convFace._face to set up data of centerCurves
7132 // Compute new normals for _LayerEdge's on EDGEs
7134 double avgCosin = 0;
7137 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7139 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7140 if ( ceCurve._isDegenerated )
7142 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7143 vector< gp_XYZ > & newNormals = ceCurve._normals;
7144 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7147 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7150 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7152 if ( isOK && !ceCurve._adjFace.IsNull() )
7154 // compute new _LayerEdge::_cosin
7155 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7156 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7159 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7160 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7161 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7167 // set new normals to _LayerEdge's of NOT degenerated central curves
7168 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7170 if ( centerCurves[ iE ]._isDegenerated )
7172 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7174 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7175 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7178 // set new normals to _LayerEdge's of degenerated central curves
7179 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7181 if ( !centerCurves[ iE ]._isDegenerated ||
7182 centerCurves[ iE ]._ledges.size() < 3 )
7184 // new normal is an average of new normals at VERTEXes that
7185 // was computed on non-degenerated _CentralCurveOnEdge's
7186 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7187 centerCurves[ iE ]._ledges.back ()->_normal );
7188 double sz = newNorm.Modulus();
7192 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7193 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7194 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7196 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7197 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7198 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7202 // Find new normals for _LayerEdge's based on FACE
7205 avgCosin /= nbCosin;
7206 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7207 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7208 if ( id2eos != convFace._subIdToEOS.end() )
7212 _EdgesOnShape& eos = * ( id2eos->second );
7213 for ( size_t i = 0; i < eos._edges.size(); ++i )
7215 _LayerEdge* ledge = eos._edges[ i ];
7216 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7218 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7220 iE = iE % centerCurves.size();
7221 if ( centerCurves[ iE ]._isDegenerated )
7223 newNorm.SetCoord( 0,0,0 );
7224 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7226 ledge->SetNormal( newNorm );
7227 ledge->_cosin = avgCosin;
7228 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7235 } // not a quasi-spherical FACE
7237 // Update _LayerEdge's data according to a new normal
7239 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7240 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7242 id2eos = convFace._subIdToEOS.begin();
7243 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7245 _EdgesOnShape& eos = * ( id2eos->second );
7246 for ( size_t i = 0; i < eos._edges.size(); ++i )
7248 _LayerEdge* & ledge = eos._edges[ i ];
7249 double len = ledge->_len;
7250 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7251 ledge->SetCosin( ledge->_cosin );
7252 ledge->SetNewLength( len, eos, helper );
7254 if ( eos.ShapeType() != TopAbs_FACE )
7255 for ( size_t i = 0; i < eos._edges.size(); ++i )
7257 _LayerEdge* ledge = eos._edges[ i ];
7258 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7260 _LayerEdge* neibor = ledge->_neibors[iN];
7261 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7263 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7264 neibor->Set( _LayerEdge::MOVED );
7265 neibor->SetSmooLen( neibor->_len );
7269 } // loop on sub-shapes of convFace._face
7271 // Find FACEs adjacent to convFace._face that got necessity to smooth
7272 // as a result of normals modification
7274 set< _EdgesOnShape* > adjFacesToSmooth;
7275 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7277 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7278 centerCurves[ iE ]._adjFaceToSmooth )
7280 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7282 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7284 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7289 data.AddShapesToSmooth( adjFacesToSmooth );
7294 } // loop on data._convexFaces
7299 //================================================================================
7301 * \brief Finds a center of curvature of a surface at a _LayerEdge
7303 //================================================================================
7305 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7306 BRepLProp_SLProps& surfProp,
7307 SMESH_MesherHelper& helper,
7308 gp_Pnt & center ) const
7310 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7311 surfProp.SetParameters( uv.X(), uv.Y() );
7312 if ( !surfProp.IsCurvatureDefined() )
7315 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7316 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7317 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7318 if ( surfCurvatureMin > surfCurvatureMax )
7319 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7321 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7326 //================================================================================
7328 * \brief Check that prisms are not distorted
7330 //================================================================================
7332 bool _ConvexFace::CheckPrisms() const
7335 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7337 const _LayerEdge* edge = _simplexTestEdges[i];
7338 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7339 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7340 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7342 debugMsg( "Bad simplex of _simplexTestEdges ("
7343 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7344 << " "<< edge->_simplices[j]._nPrev->GetID()
7345 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7352 //================================================================================
7354 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7355 * stored in this _CentralCurveOnEdge.
7356 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7357 * \param [in,out] newNormal - current normal at this point, to be redefined
7358 * \return bool - true if succeeded.
7360 //================================================================================
7362 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7364 if ( this->_isDegenerated )
7367 // find two centers the given one lies between
7369 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7371 double sl2 = 1.001 * _segLength2[ i ];
7373 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7377 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7378 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7383 double r = d1 / ( d1 + d2 );
7384 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7385 ( r ) * _ledges[ i+1 ]->_normal );
7389 double sz = newNormal.Modulus();
7398 //================================================================================
7400 * \brief Set shape members
7402 //================================================================================
7404 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7405 const _ConvexFace& convFace,
7407 SMESH_MesherHelper& helper)
7411 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7412 while ( const TopoDS_Shape* F = fIt->next())
7413 if ( !convFace._face.IsSame( *F ))
7415 _adjFace = TopoDS::Face( *F );
7416 _adjFaceToSmooth = false;
7417 // _adjFace already in a smoothing queue ?
7418 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7419 _adjFaceToSmooth = eos->_toSmooth;
7424 //================================================================================
7426 * \brief Looks for intersection of it's last segment with faces
7427 * \param distance - returns shortest distance from the last node to intersection
7429 //================================================================================
7431 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7433 const double& epsilon,
7435 const SMDS_MeshElement** intFace)
7437 vector< const SMDS_MeshElement* > suspectFaces;
7439 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7440 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7442 bool segmentIntersected = false;
7443 distance = Precision::Infinite();
7444 int iFace = -1; // intersected face
7445 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7447 const SMDS_MeshElement* face = suspectFaces[j];
7448 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7449 face->GetNodeIndex( _nodes[0] ) >= 0 )
7450 continue; // face sharing _LayerEdge node
7451 const int nbNodes = face->NbCornerNodes();
7452 bool intFound = false;
7454 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7457 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7461 const SMDS_MeshNode* tria[3];
7464 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7467 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7473 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7474 segmentIntersected = true;
7475 if ( distance > dist )
7476 distance = dist, iFace = j;
7479 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7483 if ( segmentIntersected )
7486 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7487 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7488 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7489 << ", intersection with face ("
7490 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7491 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7492 << ") distance = " << distance << endl;
7496 return segmentIntersected;
7499 //================================================================================
7501 * \brief Returns a point used to check orientation of _simplices
7503 //================================================================================
7505 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7507 size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7509 if ( !eos || eos->_sWOL.IsNull() )
7512 if ( eos->SWOLType() == TopAbs_EDGE )
7514 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7516 //else // TopAbs_FACE
7518 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7521 //================================================================================
7523 * \brief Returns size and direction of the last segment
7525 //================================================================================
7527 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7529 // find two non-coincident positions
7530 gp_XYZ orig = _pos.back();
7532 int iPrev = _pos.size() - 2;
7533 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7534 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7535 while ( iPrev >= 0 )
7537 vec = orig - _pos[iPrev];
7538 if ( vec.SquareModulus() > tol*tol )
7548 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7549 segDir.SetDirection( _normal );
7554 gp_Pnt pPrev = _pos[ iPrev ];
7555 if ( !eos._sWOL.IsNull() )
7557 TopLoc_Location loc;
7558 if ( eos.SWOLType() == TopAbs_EDGE )
7561 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7562 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7566 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7567 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7569 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7571 segDir.SetLocation( pPrev );
7572 segDir.SetDirection( vec );
7573 segLen = vec.Modulus();
7579 //================================================================================
7581 * \brief Return the last position of the target node on a FACE.
7582 * \param [in] F - the FACE this _LayerEdge is inflated along
7583 * \return gp_XY - result UV
7585 //================================================================================
7587 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7589 if ( F.IsSame( eos._sWOL )) // F is my FACE
7590 return gp_XY( _pos.back().X(), _pos.back().Y() );
7592 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7593 return gp_XY( 1e100, 1e100 );
7595 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7596 double f, l, u = _pos.back().X();
7597 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7598 if ( !C2d.IsNull() && f <= u && u <= l )
7599 return C2d->Value( u ).XY();
7601 return gp_XY( 1e100, 1e100 );
7604 //================================================================================
7606 * \brief Test intersection of the last segment with a given triangle
7607 * using Moller-Trumbore algorithm
7608 * Intersection is detected if distance to intersection is less than _LayerEdge._len
7610 //================================================================================
7612 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7613 const gp_XYZ& vert0,
7614 const gp_XYZ& vert1,
7615 const gp_XYZ& vert2,
7617 const double& EPSILON) const
7619 const gp_Pnt& orig = lastSegment.Location();
7620 const gp_Dir& dir = lastSegment.Direction();
7622 /* calculate distance from vert0 to ray origin */
7623 //gp_XYZ tvec = orig.XYZ() - vert0;
7625 //if ( tvec * dir > EPSILON )
7626 // intersected face is at back side of the temporary face this _LayerEdge belongs to
7629 gp_XYZ edge1 = vert1 - vert0;
7630 gp_XYZ edge2 = vert2 - vert0;
7632 /* begin calculating determinant - also used to calculate U parameter */
7633 gp_XYZ pvec = dir.XYZ() ^ edge2;
7635 /* if determinant is near zero, ray lies in plane of triangle */
7636 double det = edge1 * pvec;
7638 const double ANGL_EPSILON = 1e-12;
7639 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7642 /* calculate distance from vert0 to ray origin */
7643 gp_XYZ tvec = orig.XYZ() - vert0;
7645 /* calculate U parameter and test bounds */
7646 double u = ( tvec * pvec ) / det;
7647 //if (u < 0.0 || u > 1.0)
7648 if ( u < -EPSILON || u > 1.0 + EPSILON )
7651 /* prepare to test V parameter */
7652 gp_XYZ qvec = tvec ^ edge1;
7654 /* calculate V parameter and test bounds */
7655 double v = (dir.XYZ() * qvec) / det;
7656 //if ( v < 0.0 || u + v > 1.0 )
7657 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7660 /* calculate t, ray intersects triangle */
7661 t = (edge2 * qvec) / det;
7667 //================================================================================
7669 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7670 * neighbor _LayerEdge's by it's own inflation vector.
7671 * \param [in] eov - EOS of the VERTEX
7672 * \param [in] eos - EOS of the FACE
7673 * \param [in] step - inflation step
7674 * \param [in,out] badSmooEdges - not untangled _LayerEdge's
7676 //================================================================================
7678 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
7679 const _EdgesOnShape* eos,
7681 vector< _LayerEdge* > & badSmooEdges )
7683 // check if any of _neibors is in badSmooEdges
7684 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7685 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7688 // get all edges to move
7690 set< _LayerEdge* > edges;
7692 // find a distance between _LayerEdge on VERTEX and its neighbors
7693 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
7695 for ( size_t i = 0; i < _neibors.size(); ++i )
7697 _LayerEdge* nEdge = _neibors[i];
7698 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7700 edges.insert( nEdge );
7701 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7704 // add _LayerEdge's close to curPosV
7708 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7710 _LayerEdge* edgeF = *e;
7711 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7713 _LayerEdge* nEdge = edgeF->_neibors[i];
7714 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7715 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7716 edges.insert( nEdge );
7720 while ( nbE < edges.size() );
7722 // move the target node of the got edges
7724 gp_XYZ prevPosV = PrevPos();
7725 if ( eov->SWOLType() == TopAbs_EDGE )
7727 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7728 prevPosV = curve.Value( prevPosV.X() ).XYZ();
7730 else if ( eov->SWOLType() == TopAbs_FACE )
7732 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7733 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7736 SMDS_FacePosition* fPos;
7737 //double r = 1. - Min( 0.9, step / 10. );
7738 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7740 _LayerEdge* edgeF = *e;
7741 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
7742 const gp_XYZ newPosF = curPosV + prevVF;
7743 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7744 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7745 edgeF->_pos.back() = newPosF;
7746 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7748 // set _curvature to make edgeF updated by putOnOffsetSurface()
7749 if ( !edgeF->_curvature )
7750 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7752 edgeF->_curvature = new _Curvature;
7753 edgeF->_curvature->_r = 0;
7754 edgeF->_curvature->_k = 0;
7755 edgeF->_curvature->_h2lenRatio = 0;
7756 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7759 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7760 // SMESH_TNodeXYZ( _nodes[0] ));
7761 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7763 // _LayerEdge* edgeF = *e;
7764 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7765 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7766 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7767 // edgeF->_pos.back() = newPosF;
7768 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7771 // smooth _LayerEdge's around moved nodes
7772 //size_t nbBadBefore = badSmooEdges.size();
7773 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7775 _LayerEdge* edgeF = *e;
7776 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7777 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7778 //&& !edges.count( edgeF->_neibors[j] ))
7780 _LayerEdge* edgeFN = edgeF->_neibors[j];
7781 edgeFN->Unset( SMOOTHED );
7782 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7785 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7786 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7787 // int nbBadAfter = edgeFN->_simplices.size();
7789 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7791 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7793 // if ( nbBadAfter <= nbBad )
7795 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7796 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7797 // edgeF->_pos.back() = newPosF;
7798 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7799 // nbBad = nbBadAfter;
7803 badSmooEdges.push_back( edgeFN );
7806 // move a bit not smoothed around moved nodes
7807 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7809 // _LayerEdge* edgeF = badSmooEdges[i];
7810 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7811 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7812 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7813 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7814 // edgeF->_pos.back() = newPosF;
7815 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7819 //================================================================================
7821 * \brief Perform smooth of _LayerEdge's based on EDGE's
7822 * \retval bool - true if node has been moved
7824 //================================================================================
7826 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7827 const TopoDS_Face& F,
7828 SMESH_MesherHelper& helper)
7830 ASSERT( IsOnEdge() );
7832 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7833 SMESH_TNodeXYZ oldPos( tgtNode );
7834 double dist01, distNewOld;
7836 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7837 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7838 dist01 = p0.Distance( _2neibors->tgtNode(1) );
7840 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7841 double lenDelta = 0;
7844 //lenDelta = _curvature->lenDelta( _len );
7845 lenDelta = _curvature->lenDeltaByDist( dist01 );
7846 newPos.ChangeCoord() += _normal * lenDelta;
7849 distNewOld = newPos.Distance( oldPos );
7853 if ( _2neibors->_plnNorm )
7855 // put newPos on the plane defined by source node and _plnNorm
7856 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7857 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7858 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7860 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7861 _pos.back() = newPos.XYZ();
7865 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7866 gp_XY uv( Precision::Infinite(), 0 );
7867 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7868 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7870 newPos = surface->Value( uv );
7871 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7874 // commented for IPAL0052478
7875 // if ( _curvature && lenDelta < 0 )
7877 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7878 // _len -= prevPos.Distance( oldPos );
7879 // _len += prevPos.Distance( newPos );
7881 bool moved = distNewOld > dist01/50;
7883 dumpMove( tgtNode ); // debug
7888 //================================================================================
7890 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7892 //================================================================================
7894 void _LayerEdge::SmoothWoCheck()
7896 if ( Is( DIFFICULT ))
7899 bool moved = Is( SMOOTHED );
7900 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
7901 moved = _neibors[i]->Is( SMOOTHED );
7905 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7907 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7908 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7909 _pos.back() = newPos;
7911 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7914 //================================================================================
7916 * \brief Checks validity of _neibors on EDGEs and VERTEXes
7918 //================================================================================
7920 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7922 if ( ! Is( NEAR_BOUNDARY ))
7927 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7929 _LayerEdge* eN = _neibors[iN];
7930 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7933 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7934 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7935 eN->_pos.size() != _pos.size() );
7937 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7938 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7939 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7940 if ( eN->_nodes.size() > 1 &&
7941 eN->_simplices[i].Includes( _nodes.back() ) &&
7942 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7947 badNeibors->push_back( eN );
7948 debugMsg("Bad boundary simplex ( "
7949 << " "<< eN->_nodes[0]->GetID()
7950 << " "<< eN->_nodes.back()->GetID()
7951 << " "<< eN->_simplices[i]._nPrev->GetID()
7952 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7963 //================================================================================
7965 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7966 * \retval int - nb of bad simplices around this _LayerEdge
7968 //================================================================================
7970 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7972 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7973 return 0; // shape of simplices not changed
7974 if ( _simplices.size() < 2 )
7975 return 0; // _LayerEdge inflated along EDGE or FACE
7977 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7980 const gp_XYZ& curPos = _pos.back();
7981 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7983 // quality metrics (orientation) of tetras around _tgtNode
7985 double vol, minVolBefore = 1e100;
7986 for ( size_t i = 0; i < _simplices.size(); ++i )
7988 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7989 minVolBefore = Min( minVolBefore, vol );
7991 int nbBad = _simplices.size() - nbOkBefore;
7993 bool bndNeedSmooth = false;
7995 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7999 // evaluate min angle
8000 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8002 size_t nbGoodAngles = _simplices.size();
8004 for ( size_t i = 0; i < _simplices.size(); ++i )
8006 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8009 if ( nbGoodAngles == _simplices.size() )
8015 if ( Is( ON_CONCAVE_FACE ))
8018 if ( step % 2 == 0 )
8021 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8023 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8024 _smooFunction = _funs[ FUN_CENTROIDAL ];
8026 _smooFunction = _funs[ FUN_LAPLACIAN ];
8029 // compute new position for the last _pos using different _funs
8032 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8035 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8036 else if ( _funs[ iFun ] == _smooFunction )
8037 continue; // _smooFunction again
8038 else if ( step > 1 )
8039 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8041 break; // let "easy" functions improve elements around distorted ones
8045 double delta = _curvature->lenDelta( _len );
8047 newPos += _normal * delta;
8050 double segLen = _normal * ( newPos - prevPos );
8051 if ( segLen + delta > 0 )
8052 newPos += _normal * delta;
8054 // double segLenChange = _normal * ( curPos - newPos );
8055 // newPos += 0.5 * _normal * segLenChange;
8059 double minVolAfter = 1e100;
8060 for ( size_t i = 0; i < _simplices.size(); ++i )
8062 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8063 minVolAfter = Min( minVolAfter, vol );
8066 if ( nbOkAfter < nbOkBefore )
8070 ( nbOkAfter == nbOkBefore ) &&
8071 ( minVolAfter <= minVolBefore ))
8074 nbBad = _simplices.size() - nbOkAfter;
8075 minVolBefore = minVolAfter;
8076 nbOkBefore = nbOkAfter;
8079 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8080 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8081 _pos.back() = newPos;
8083 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8084 << (nbBad ? " --BAD" : ""));
8088 continue; // look for a better function
8094 } // loop on smoothing functions
8096 if ( moved ) // notify _neibors
8099 for ( size_t i = 0; i < _neibors.size(); ++i )
8100 if ( !_neibors[i]->Is( MOVED ))
8102 _neibors[i]->Set( MOVED );
8103 toSmooth.push_back( _neibors[i] );
8110 //================================================================================
8112 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8113 * \retval int - nb of bad simplices around this _LayerEdge
8115 //================================================================================
8117 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8119 if ( !_smooFunction )
8120 return 0; // _LayerEdge inflated along EDGE or FACE
8122 return 0; // not inflated
8124 const gp_XYZ& curPos = _pos.back();
8125 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8127 // quality metrics (orientation) of tetras around _tgtNode
8129 double vol, minVolBefore = 1e100;
8130 for ( size_t i = 0; i < _simplices.size(); ++i )
8132 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8133 minVolBefore = Min( minVolBefore, vol );
8135 int nbBad = _simplices.size() - nbOkBefore;
8137 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8139 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8140 _smooFunction = _funs[ FUN_LAPLACIAN ];
8141 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8142 _smooFunction = _funs[ FUN_CENTROIDAL ];
8145 // compute new position for the last _pos using different _funs
8147 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8150 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8151 else if ( _funs[ iFun ] == _smooFunction )
8152 continue; // _smooFunction again
8153 else if ( step > 1 )
8154 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8156 break; // let "easy" functions improve elements around distorted ones
8160 double delta = _curvature->lenDelta( _len );
8162 newPos += _normal * delta;
8165 double segLen = _normal * ( newPos - prevPos );
8166 if ( segLen + delta > 0 )
8167 newPos += _normal * delta;
8169 // double segLenChange = _normal * ( curPos - newPos );
8170 // newPos += 0.5 * _normal * segLenChange;
8174 double minVolAfter = 1e100;
8175 for ( size_t i = 0; i < _simplices.size(); ++i )
8177 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8178 minVolAfter = Min( minVolAfter, vol );
8181 if ( nbOkAfter < nbOkBefore )
8183 if (( isConcaveFace || findBest ) &&
8184 ( nbOkAfter == nbOkBefore ) &&
8185 ( minVolAfter <= minVolBefore )
8189 nbBad = _simplices.size() - nbOkAfter;
8190 minVolBefore = minVolAfter;
8191 nbOkBefore = nbOkAfter;
8193 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8194 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8195 _pos.back() = newPos;
8197 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8198 << ( nbBad ? "--BAD" : ""));
8200 // commented for IPAL0052478
8201 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8202 // _len += prevPos.Distance(newPos);
8204 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8206 //_smooFunction = _funs[ iFun ];
8207 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8208 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8209 // << " minVol: " << minVolAfter
8210 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8212 continue; // look for a better function
8218 } // loop on smoothing functions
8223 //================================================================================
8225 * \brief Chooses a smoothing technic giving a position most close to an initial one.
8226 * For a correct result, _simplices must contain nodes lying on geometry.
8228 //================================================================================
8230 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8231 const TNode2Edge& n2eMap)
8233 if ( _smooFunction ) return;
8235 // use smoothNefPolygon() near concaveVertices
8236 if ( !concaveVertices.empty() )
8238 _smooFunction = _funs[ FUN_CENTROIDAL ];
8240 Set( ON_CONCAVE_FACE );
8242 for ( size_t i = 0; i < _simplices.size(); ++i )
8244 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8246 _smooFunction = _funs[ FUN_NEFPOLY ];
8248 // set FUN_CENTROIDAL to neighbor edges
8249 for ( i = 0; i < _neibors.size(); ++i )
8251 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8253 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8260 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8261 // // where the nodes are smoothed too far along a sphere thus creating
8262 // // inverted _simplices
8263 // double dist[theNbSmooFuns];
8264 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8265 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8267 // double minDist = Precision::Infinite();
8268 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8269 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8271 // gp_Pnt newP = (this->*_funs[i])();
8272 // dist[i] = p.SquareDistance( newP );
8273 // if ( dist[i]*coef[i] < minDist )
8275 // _smooFunction = _funs[i];
8276 // minDist = dist[i]*coef[i];
8282 _smooFunction = _funs[ FUN_LAPLACIAN ];
8285 // for ( size_t i = 0; i < _simplices.size(); ++i )
8286 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8287 // if ( minDim == 0 )
8288 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8289 // else if ( minDim == 1 )
8290 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8294 // for ( int i = 0; i < FUN_NB; ++i )
8296 // //cout << dist[i] << " ";
8297 // if ( _smooFunction == _funs[i] ) {
8299 // //debugMsg( fNames[i] );
8303 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8306 //================================================================================
8308 * \brief Returns a name of _SmooFunction
8310 //================================================================================
8312 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8315 fun = _smooFunction;
8316 for ( int i = 0; i < theNbSmooFuns; ++i )
8317 if ( fun == _funs[i] )
8320 return theNbSmooFuns;
8323 //================================================================================
8325 * \brief Computes a new node position using Laplacian smoothing
8327 //================================================================================
8329 gp_XYZ _LayerEdge::smoothLaplacian()
8331 gp_XYZ newPos (0,0,0);
8332 for ( size_t i = 0; i < _simplices.size(); ++i )
8333 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8334 newPos /= _simplices.size();
8339 //================================================================================
8341 * \brief Computes a new node position using angular-based smoothing
8343 //================================================================================
8345 gp_XYZ _LayerEdge::smoothAngular()
8347 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8348 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8349 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8351 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8353 for ( size_t i = 0; i < _simplices.size(); ++i )
8355 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8356 edgeDir.push_back( p - pPrev );
8357 edgeSize.push_back( edgeDir.back().Magnitude() );
8358 if ( edgeSize.back() < numeric_limits<double>::min() )
8361 edgeSize.pop_back();
8365 edgeDir.back() /= edgeSize.back();
8366 points.push_back( p );
8371 edgeDir.push_back ( edgeDir[0] );
8372 edgeSize.push_back( edgeSize[0] );
8373 pN /= points.size();
8375 gp_XYZ newPos(0,0,0);
8377 for ( size_t i = 0; i < points.size(); ++i )
8379 gp_Vec toN = pN - points[i];
8380 double toNLen = toN.Magnitude();
8381 if ( toNLen < numeric_limits<double>::min() )
8386 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8387 double bisecLen = bisec.SquareMagnitude();
8388 if ( bisecLen < numeric_limits<double>::min() )
8390 gp_Vec norm = edgeDir[i] ^ toN;
8391 bisec = norm ^ edgeDir[i];
8392 bisecLen = bisec.SquareMagnitude();
8394 bisecLen = Sqrt( bisecLen );
8398 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8399 sumSize += bisecLen;
8401 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8402 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8408 // project newPos to an average plane
8410 gp_XYZ norm(0,0,0); // plane normal
8411 points.push_back( points[0] );
8412 for ( size_t i = 1; i < points.size(); ++i )
8414 gp_XYZ vec1 = points[ i-1 ] - pN;
8415 gp_XYZ vec2 = points[ i ] - pN;
8416 gp_XYZ cross = vec1 ^ vec2;
8419 if ( cross * norm < numeric_limits<double>::min() )
8420 norm += cross.Reversed();
8424 catch (Standard_Failure) { // if |cross| == 0.
8427 gp_XYZ vec = newPos - pN;
8428 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8429 newPos = newPos - r * norm;
8434 //================================================================================
8436 * \brief Computes a new node position using weigthed node positions
8438 //================================================================================
8440 gp_XYZ _LayerEdge::smoothLengthWeighted()
8442 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8443 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8445 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8446 for ( size_t i = 0; i < _simplices.size(); ++i )
8448 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8449 edgeSize.push_back( ( p - pPrev ).Modulus() );
8450 if ( edgeSize.back() < numeric_limits<double>::min() )
8452 edgeSize.pop_back();
8456 points.push_back( p );
8460 edgeSize.push_back( edgeSize[0] );
8462 gp_XYZ newPos(0,0,0);
8464 for ( size_t i = 0; i < points.size(); ++i )
8466 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8467 sumSize += edgeSize[i] + edgeSize[i+1];
8473 //================================================================================
8475 * \brief Computes a new node position using angular-based smoothing
8477 //================================================================================
8479 gp_XYZ _LayerEdge::smoothCentroidal()
8481 gp_XYZ newPos(0,0,0);
8482 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8484 for ( size_t i = 0; i < _simplices.size(); ++i )
8486 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8487 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8488 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8489 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8492 newPos += gc * size;
8499 //================================================================================
8501 * \brief Computes a new node position located inside a Nef polygon
8503 //================================================================================
8505 gp_XYZ _LayerEdge::smoothNefPolygon()
8506 #ifdef OLD_NEF_POLYGON
8508 gp_XYZ newPos(0,0,0);
8510 // get a plane to seach a solution on
8512 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8514 const double tol = numeric_limits<double>::min();
8515 gp_XYZ center(0,0,0);
8516 for ( i = 0; i < _simplices.size(); ++i )
8518 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8519 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8520 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8522 vecs.back() = vecs[0];
8523 center /= _simplices.size();
8525 gp_XYZ zAxis(0,0,0);
8526 for ( i = 0; i < _simplices.size(); ++i )
8527 zAxis += vecs[i] ^ vecs[i+1];
8530 for ( i = 0; i < _simplices.size(); ++i )
8533 if ( yAxis.SquareModulus() > tol )
8536 gp_XYZ xAxis = yAxis ^ zAxis;
8537 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8538 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8539 // p0.Distance( _simplices[2]._nPrev ));
8540 // gp_XYZ center = smoothLaplacian();
8541 // gp_XYZ xAxis, yAxis, zAxis;
8542 // for ( i = 0; i < _simplices.size(); ++i )
8544 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8545 // if ( xAxis.SquareModulus() > tol*tol )
8548 // for ( i = 1; i < _simplices.size(); ++i )
8550 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8551 // zAxis = xAxis ^ yAxis;
8552 // if ( zAxis.SquareModulus() > tol*tol )
8555 // if ( i == _simplices.size() ) return newPos;
8557 yAxis = zAxis ^ xAxis;
8558 xAxis /= xAxis.Modulus();
8559 yAxis /= yAxis.Modulus();
8561 // get half-planes of _simplices
8563 vector< _halfPlane > halfPlns( _simplices.size() );
8565 for ( size_t i = 0; i < _simplices.size(); ++i )
8567 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8568 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8569 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8570 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8571 gp_XY vec12 = p2 - p1;
8572 double dist12 = vec12.Modulus();
8576 halfPlns[ nbHP ]._pos = p1;
8577 halfPlns[ nbHP ]._dir = vec12;
8578 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8582 // intersect boundaries of half-planes, define state of intersection points
8583 // in relation to all half-planes and calculate internal point of a 2D polygon
8586 gp_XY newPos2D (0,0);
8588 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8589 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8590 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8592 vector< vector< TIntPntState > > allIntPnts( nbHP );
8593 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8595 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8596 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8598 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8599 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8602 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8604 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8606 if ( iHP1 == iHP2 ) continue;
8608 TIntPntState & ips1 = intPnts1[ iHP2 ];
8609 if ( ips1.second == UNDEF )
8611 // find an intersection point of boundaries of iHP1 and iHP2
8613 if ( iHP2 == iPrev ) // intersection with neighbors is known
8614 ips1.first = halfPlns[ iHP1 ]._pos;
8615 else if ( iHP2 == iNext )
8616 ips1.first = halfPlns[ iHP2 ]._pos;
8617 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8618 ips1.second = NO_INT;
8620 // classify the found intersection point
8621 if ( ips1.second != NO_INT )
8623 ips1.second = NOT_OUT;
8624 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8625 if ( i != iHP1 && i != iHP2 &&
8626 halfPlns[ i ].IsOut( ips1.first, tol ))
8627 ips1.second = IS_OUT;
8629 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8630 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8631 TIntPntState & ips2 = intPnts2[ iHP1 ];
8634 if ( ips1.second == NOT_OUT )
8637 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8641 // find a NOT_OUT segment of boundary which is located between
8642 // two NOT_OUT int points
8645 continue; // no such a segment
8649 // sort points along the boundary
8650 map< double, TIntPntState* > ipsByParam;
8651 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8653 TIntPntState & ips1 = intPnts1[ iHP2 ];
8654 if ( ips1.second != NO_INT )
8656 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8657 double param = op * halfPlns[ iHP1 ]._dir;
8658 ipsByParam.insert( make_pair( param, & ips1 ));
8661 // look for two neighboring NOT_OUT points
8663 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8664 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8666 TIntPntState & ips1 = *(u2ips->second);
8667 if ( ips1.second == NOT_OUT )
8668 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8669 else if ( nbNotOut >= 2 )
8676 if ( nbNotOut >= 2 )
8678 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8681 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8688 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8697 #else // OLD_NEF_POLYGON
8698 { ////////////////////////////////// NEW
8699 gp_XYZ newPos(0,0,0);
8701 // get a plane to seach a solution on
8704 gp_XYZ center(0,0,0);
8705 for ( i = 0; i < _simplices.size(); ++i )
8706 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8707 center /= _simplices.size();
8709 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8710 for ( i = 0; i < _simplices.size(); ++i )
8711 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8712 vecs.back() = vecs[0];
8714 const double tol = numeric_limits<double>::min();
8715 gp_XYZ zAxis(0,0,0);
8716 for ( i = 0; i < _simplices.size(); ++i )
8718 gp_XYZ cross = vecs[i] ^ vecs[i+1];
8721 if ( cross * zAxis < tol )
8722 zAxis += cross.Reversed();
8726 catch (Standard_Failure) { // if |cross| == 0.
8731 for ( i = 0; i < _simplices.size(); ++i )
8734 if ( yAxis.SquareModulus() > tol )
8737 gp_XYZ xAxis = yAxis ^ zAxis;
8738 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8739 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8740 // p0.Distance( _simplices[2]._nPrev ));
8741 // gp_XYZ center = smoothLaplacian();
8742 // gp_XYZ xAxis, yAxis, zAxis;
8743 // for ( i = 0; i < _simplices.size(); ++i )
8745 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8746 // if ( xAxis.SquareModulus() > tol*tol )
8749 // for ( i = 1; i < _simplices.size(); ++i )
8751 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8752 // zAxis = xAxis ^ yAxis;
8753 // if ( zAxis.SquareModulus() > tol*tol )
8756 // if ( i == _simplices.size() ) return newPos;
8758 yAxis = zAxis ^ xAxis;
8759 xAxis /= xAxis.Modulus();
8760 yAxis /= yAxis.Modulus();
8762 // get half-planes of _simplices
8764 vector< _halfPlane > halfPlns( _simplices.size() );
8766 for ( size_t i = 0; i < _simplices.size(); ++i )
8768 const gp_XYZ& OP1 = vecs[ i ];
8769 const gp_XYZ& OP2 = vecs[ i+1 ];
8770 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8771 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8772 gp_XY vec12 = p2 - p1;
8773 double dist12 = vec12.Modulus();
8777 halfPlns[ nbHP ]._pos = p1;
8778 halfPlns[ nbHP ]._dir = vec12;
8779 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8783 // intersect boundaries of half-planes, define state of intersection points
8784 // in relation to all half-planes and calculate internal point of a 2D polygon
8787 gp_XY newPos2D (0,0);
8789 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8790 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8791 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8793 vector< vector< TIntPntState > > allIntPnts( nbHP );
8794 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8796 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8797 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8799 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8800 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8803 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8805 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8807 if ( iHP1 == iHP2 ) continue;
8809 TIntPntState & ips1 = intPnts1[ iHP2 ];
8810 if ( ips1.second == UNDEF )
8812 // find an intersection point of boundaries of iHP1 and iHP2
8814 if ( iHP2 == iPrev ) // intersection with neighbors is known
8815 ips1.first = halfPlns[ iHP1 ]._pos;
8816 else if ( iHP2 == iNext )
8817 ips1.first = halfPlns[ iHP2 ]._pos;
8818 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8819 ips1.second = NO_INT;
8821 // classify the found intersection point
8822 if ( ips1.second != NO_INT )
8824 ips1.second = NOT_OUT;
8825 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8826 if ( i != iHP1 && i != iHP2 &&
8827 halfPlns[ i ].IsOut( ips1.first, tol ))
8828 ips1.second = IS_OUT;
8830 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8831 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8832 TIntPntState & ips2 = intPnts2[ iHP1 ];
8835 if ( ips1.second == NOT_OUT )
8838 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8842 // find a NOT_OUT segment of boundary which is located between
8843 // two NOT_OUT int points
8846 continue; // no such a segment
8850 // sort points along the boundary
8851 map< double, TIntPntState* > ipsByParam;
8852 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8854 TIntPntState & ips1 = intPnts1[ iHP2 ];
8855 if ( ips1.second != NO_INT )
8857 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8858 double param = op * halfPlns[ iHP1 ]._dir;
8859 ipsByParam.insert( make_pair( param, & ips1 ));
8862 // look for two neighboring NOT_OUT points
8864 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8865 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8867 TIntPntState & ips1 = *(u2ips->second);
8868 if ( ips1.second == NOT_OUT )
8869 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8870 else if ( nbNotOut >= 2 )
8877 if ( nbNotOut >= 2 )
8879 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8882 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8889 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8898 #endif // OLD_NEF_POLYGON
8900 //================================================================================
8902 * \brief Add a new segment to _LayerEdge during inflation
8904 //================================================================================
8906 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8911 if ( len > _maxLen )
8914 Block( eos.GetData() );
8916 const double lenDelta = len - _len;
8917 if ( lenDelta < len * 1e-3 )
8919 Block( eos.GetData() );
8923 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8924 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8926 if ( eos._hyp.IsOffsetMethod() )
8930 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8931 while ( faceIt->more() )
8933 const SMDS_MeshElement* face = faceIt->next();
8934 if ( !eos.GetNormal( face, faceNorm ))
8937 // translate plane of a face
8938 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8940 // find point of intersection of the face plane located at baryCenter
8941 // and _normal located at newXYZ
8942 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8943 double dot = ( faceNorm.XYZ() * _normal );
8944 if ( dot < std::numeric_limits<double>::min() )
8945 dot = lenDelta * 1e-3;
8946 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8947 newXYZ += step * _normal;
8949 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8953 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8956 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8957 _pos.push_back( newXYZ );
8959 if ( !eos._sWOL.IsNull() )
8963 if ( eos.SWOLType() == TopAbs_EDGE )
8965 double u = Precision::Infinite(); // to force projection w/o distance check
8966 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8967 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8968 _pos.back().SetCoord( u, 0, 0 );
8969 if ( _nodes.size() > 1 && uvOK )
8971 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8972 pos->SetUParameter( u );
8977 gp_XY uv( Precision::Infinite(), 0 );
8978 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8979 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8980 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8981 if ( _nodes.size() > 1 && uvOK )
8983 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8984 pos->SetUParameter( uv.X() );
8985 pos->SetVParameter( uv.Y() );
8990 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8994 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8996 Block( eos.GetData() );
9004 if ( eos.ShapeType() != TopAbs_FACE )
9006 for ( size_t i = 0; i < _neibors.size(); ++i )
9007 //if ( _len > _neibors[i]->GetSmooLen() )
9008 _neibors[i]->Set( MOVED );
9012 dumpMove( n ); //debug
9015 //================================================================================
9017 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9019 //================================================================================
9021 void _LayerEdge::Block( _SolidData& data )
9023 //if ( Is( BLOCKED )) return;
9027 std::queue<_LayerEdge*> queue;
9030 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9031 while ( !queue.empty() )
9033 _LayerEdge* edge = queue.front(); queue.pop();
9034 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9035 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9036 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9038 _LayerEdge* neibor = edge->_neibors[iN];
9039 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9041 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9042 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9043 double minDist = pSrc.SquareDistance( pSrcN );
9044 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9045 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9046 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9047 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9048 if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9050 newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9052 if ( neibor->_maxLen > newMaxLen )
9054 neibor->_maxLen = newMaxLen;
9055 if ( neibor->_maxLen < neibor->_len )
9057 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9058 while ( neibor->_len > neibor->_maxLen &&
9059 neibor->NbSteps() > 1 )
9060 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9061 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9062 //neibor->Block( data );
9064 queue.push( neibor );
9070 //================================================================================
9072 * \brief Remove last inflation step
9074 //================================================================================
9076 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9078 if ( _pos.size() > curStep && _nodes.size() > 1 )
9080 _pos.resize( curStep );
9082 gp_Pnt nXYZ = _pos.back();
9083 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9084 SMESH_TNodeXYZ curXYZ( n );
9085 if ( !eos._sWOL.IsNull() )
9087 TopLoc_Location loc;
9088 if ( eos.SWOLType() == TopAbs_EDGE )
9090 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9091 pos->SetUParameter( nXYZ.X() );
9093 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9094 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9098 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9099 pos->SetUParameter( nXYZ.X() );
9100 pos->SetVParameter( nXYZ.Y() );
9101 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9102 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9105 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9108 if ( restoreLength )
9110 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9115 //================================================================================
9117 * \brief Return index of a _pos distant from _normal
9119 //================================================================================
9121 int _LayerEdge::GetSmoothedPos( const double tol )
9124 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9126 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9127 if ( normDist > tol * tol )
9133 //================================================================================
9135 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9137 //================================================================================
9139 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9141 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9144 // find the 1st smoothed _pos
9145 int iSmoothed = GetSmoothedPos( tol );
9146 if ( !iSmoothed ) return;
9148 //if ( 1 || Is( DISTORTED ))
9150 gp_XYZ normal = _normal;
9151 if ( Is( NORMAL_UPDATED ))
9152 for ( size_t i = 1; i < _pos.size(); ++i )
9154 normal = _pos[i] - _pos[0];
9155 double size = normal.Modulus();
9156 if ( size > RealSmall() )
9162 const double r = 0.2;
9163 for ( int iter = 0; iter < 50; ++iter )
9166 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9168 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9169 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9171 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9172 double newLen = ( 1-r ) * midLen + r * segLen[i];
9173 const_cast< double& >( segLen[i] ) = newLen;
9174 // check angle between normal and (_pos[i+1], _pos[i] )
9175 gp_XYZ posDir = _pos[i+1] - _pos[i];
9176 double size = posDir.SquareModulus();
9177 if ( size > RealSmall() )
9178 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9180 if ( minDot > 0.5 * 0.5 )
9186 // for ( size_t i = 1; i < _pos.size()-1; ++i )
9188 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
9191 // double wgt = segLen[i] / segLen.back();
9192 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9193 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
9194 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
9195 // _pos[i] = newPos;
9200 //================================================================================
9202 * \brief Create layers of prisms
9204 //================================================================================
9206 bool _ViscousBuilder::refine(_SolidData& data)
9208 SMESH_MesherHelper& helper = data.GetHelper();
9209 helper.SetElementsOnShape(false);
9211 Handle(Geom_Curve) curve;
9212 Handle(ShapeAnalysis_Surface) surface;
9213 TopoDS_Edge geomEdge;
9214 TopoDS_Face geomFace;
9215 TopLoc_Location loc;
9218 vector< gp_XYZ > pos3D;
9220 TGeomID prevBaseId = -1;
9221 TNode2Edge* n2eMap = 0;
9222 TNode2Edge::iterator n2e;
9224 // Create intermediate nodes on each _LayerEdge
9226 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9228 _EdgesOnShape& eos = data._edgesOnShape[iS];
9229 if ( eos._edges.empty() ) continue;
9231 if ( eos._edges[0]->_nodes.size() < 2 )
9232 continue; // on _noShrinkShapes
9234 // get data of a shrink shape
9236 geomEdge.Nullify(); geomFace.Nullify();
9237 curve.Nullify(); surface.Nullify();
9238 if ( !eos._sWOL.IsNull() )
9240 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9243 geomEdge = TopoDS::Edge( eos._sWOL );
9244 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9248 geomFace = TopoDS::Face( eos._sWOL );
9249 surface = helper.GetSurface( geomFace );
9252 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9254 geomFace = TopoDS::Face( eos._shape );
9255 surface = helper.GetSurface( geomFace );
9256 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9257 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9259 eos._eosC1[ i ]->_toSmooth = true;
9260 for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9261 eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9265 vector< double > segLen;
9266 for ( size_t i = 0; i < eos._edges.size(); ++i )
9268 _LayerEdge& edge = *eos._edges[i];
9269 if ( edge._pos.size() < 2 )
9272 // get accumulated length of segments
9273 segLen.resize( edge._pos.size() );
9275 if ( eos._sWOL.IsNull() )
9277 bool useNormal = true;
9278 bool usePos = false;
9279 bool smoothed = false;
9280 double preci = 0.1 * edge._len;
9281 if ( eos._toSmooth && edge._pos.size() > 2 )
9283 smoothed = edge.GetSmoothedPos( preci );
9287 if ( !surface.IsNull() &&
9288 !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9290 useNormal = usePos = false;
9291 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9292 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9294 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9295 if ( surface->Gap() < 2. * edge._len )
9296 segLen[j] = surface->Gap();
9302 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9304 #ifndef __NODES_AT_POS
9305 useNormal = usePos = false;
9306 edge._pos[1] = edge._pos.back();
9307 edge._pos.resize( 2 );
9309 segLen[ 1 ] = edge._len;
9312 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9314 useNormal = usePos = false;
9315 _LayerEdge tmpEdge; // get original _normal
9316 tmpEdge._nodes.push_back( edge._nodes[0] );
9317 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9320 for ( size_t j = 1; j < edge._pos.size(); ++j )
9321 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9325 for ( size_t j = 1; j < edge._pos.size(); ++j )
9326 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9330 for ( size_t j = 1; j < edge._pos.size(); ++j )
9331 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9335 bool swapped = ( edge._pos.size() > 2 );
9339 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9340 if ( segLen[j] > segLen.back() )
9342 segLen.erase( segLen.begin() + j );
9343 edge._pos.erase( edge._pos.begin() + j );
9346 else if ( segLen[j] < segLen[j-1] )
9348 std::swap( segLen[j], segLen[j-1] );
9349 std::swap( edge._pos[j], edge._pos[j-1] );
9354 // smooth a path formed by edge._pos
9355 #ifndef __NODES_AT_POS
9356 if (( smoothed ) /*&&
9357 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9358 edge.SmoothPos( segLen, preci );
9361 else if ( eos._isRegularSWOL ) // usual SWOL
9363 for ( size_t j = 1; j < edge._pos.size(); ++j )
9364 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9366 else if ( !surface.IsNull() ) // SWOL surface with singularities
9368 pos3D.resize( edge._pos.size() );
9369 for ( size_t j = 0; j < edge._pos.size(); ++j )
9370 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9372 for ( size_t j = 1; j < edge._pos.size(); ++j )
9373 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9376 // allocate memory for new nodes if it is not yet refined
9377 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9378 if ( edge._nodes.size() == 2 )
9380 #ifdef __NODES_AT_POS
9381 int nbNodes = edge._pos.size();
9383 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9385 edge._nodes.resize( nbNodes, 0 );
9387 edge._nodes.back() = tgtNode;
9389 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9390 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9391 if ( baseShapeId != prevBaseId )
9393 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9394 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9395 prevBaseId = baseShapeId;
9397 _LayerEdge* edgeOnSameNode = 0;
9398 bool useExistingPos = false;
9399 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9401 edgeOnSameNode = n2e->second;
9402 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9403 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9404 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9407 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9408 epos->SetUParameter( otherTgtPos.X() );
9412 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9413 fpos->SetUParameter( otherTgtPos.X() );
9414 fpos->SetVParameter( otherTgtPos.Y() );
9417 // calculate height of the first layer
9419 const double T = segLen.back(); //data._hyp.GetTotalThickness();
9420 const double f = eos._hyp.GetStretchFactor();
9421 const int N = eos._hyp.GetNumberLayers();
9422 const double fPowN = pow( f, N );
9423 if ( fPowN - 1 <= numeric_limits<double>::min() )
9426 h0 = T * ( f - 1 )/( fPowN - 1 );
9428 const double zeroLen = std::numeric_limits<double>::min();
9430 // create intermediate nodes
9431 double hSum = 0, hi = h0/f;
9433 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9435 // compute an intermediate position
9438 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9440 int iPrevSeg = iSeg-1;
9441 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9443 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9444 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9445 #ifdef __NODES_AT_POS
9446 pos = edge._pos[ iStep ];
9448 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9449 if ( !eos._sWOL.IsNull() )
9451 // compute XYZ by parameters <pos>
9456 pos = curve->Value( u ).Transformed(loc);
9458 else if ( eos._isRegularSWOL )
9460 uv.SetCoord( pos.X(), pos.Y() );
9462 pos = surface->Value( pos.X(), pos.Y() );
9466 uv.SetCoord( pos.X(), pos.Y() );
9467 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9468 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9470 pos = surface->Value( uv );
9473 // create or update the node
9476 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9477 if ( !eos._sWOL.IsNull() )
9480 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9482 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9486 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9491 if ( !eos._sWOL.IsNull() )
9493 // make average pos from new and current parameters
9496 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9497 if ( useExistingPos )
9498 u = helper.GetNodeU( geomEdge, node );
9499 pos = curve->Value( u ).Transformed(loc);
9501 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9502 epos->SetUParameter( u );
9506 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9507 if ( useExistingPos )
9508 uv = helper.GetNodeUV( geomFace, node );
9509 pos = surface->Value( uv );
9511 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9512 fpos->SetUParameter( uv.X() );
9513 fpos->SetVParameter( uv.Y() );
9516 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9518 } // loop on edge._nodes
9520 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9523 edge._pos.back().SetCoord( u, 0,0);
9525 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9527 if ( edgeOnSameNode )
9528 edgeOnSameNode->_pos.back() = edge._pos.back();
9531 } // loop on eos._edges to create nodes
9534 if ( !getMeshDS()->IsEmbeddedMode() )
9535 // Log node movement
9536 for ( size_t i = 0; i < eos._edges.size(); ++i )
9538 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9539 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9546 helper.SetElementsOnShape(true);
9548 vector< vector<const SMDS_MeshNode*>* > nnVec;
9549 set< vector<const SMDS_MeshNode*>* > nnSet;
9550 set< int > degenEdgeInd;
9551 vector<const SMDS_MeshElement*> degenVols;
9553 TopExp_Explorer exp( data._solid, TopAbs_FACE );
9554 for ( ; exp.More(); exp.Next() )
9556 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9557 if ( data._ignoreFaceIds.count( faceID ))
9559 const bool isReversedFace = data._reversedFaceIds.count( faceID );
9560 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
9561 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
9562 while ( fIt->more() )
9564 const SMDS_MeshElement* face = fIt->next();
9565 const int nbNodes = face->NbCornerNodes();
9566 nnVec.resize( nbNodes );
9568 degenEdgeInd.clear();
9569 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9570 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9571 for ( int iN = 0; iN < nbNodes; ++iN )
9573 const SMDS_MeshNode* n = nIt->next();
9574 _LayerEdge* edge = data._n2eMap[ n ];
9575 const int i = isReversedFace ? nbNodes-1-iN : iN;
9576 nnVec[ i ] = & edge->_nodes;
9577 maxZ = std::max( maxZ, nnVec[ i ]->size() );
9578 minZ = std::min( minZ, nnVec[ i ]->size() );
9580 if ( helper.HasDegeneratedEdges() )
9581 nnSet.insert( nnVec[ i ]);
9586 if ( 0 < nnSet.size() && nnSet.size() < 3 )
9594 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9595 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9596 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
9598 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9600 for ( int iN = 0; iN < nbNodes; ++iN )
9601 if ( nnVec[ iN ]->size() < iZ+1 )
9602 degenEdgeInd.insert( iN );
9604 if ( degenEdgeInd.size() == 1 ) // PYRAM
9606 int i2 = *degenEdgeInd.begin();
9607 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9608 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9609 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9610 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
9614 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9615 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9616 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9617 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9618 (*nnVec[ i3 ])[ iZ ]);
9626 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9627 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9628 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9629 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
9630 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
9632 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9634 for ( int iN = 0; iN < nbNodes; ++iN )
9635 if ( nnVec[ iN ]->size() < iZ+1 )
9636 degenEdgeInd.insert( iN );
9638 switch ( degenEdgeInd.size() )
9642 int i2 = *degenEdgeInd.begin();
9643 int i3 = *degenEdgeInd.rbegin();
9644 bool ok = ( i3 - i2 == 1 );
9645 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9646 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9647 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9649 const SMDS_MeshElement* vol =
9650 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9651 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9653 degenVols.push_back( vol );
9657 default: // degen HEX
9659 const SMDS_MeshElement* vol =
9660 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9661 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9662 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9663 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9664 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
9665 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
9666 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
9667 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
9668 degenVols.push_back( vol );
9675 return error("Not supported type of element", data._index);
9677 } // switch ( nbNodes )
9678 } // while ( fIt->more() )
9681 if ( !degenVols.empty() )
9683 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9684 if ( !err || err->IsOK() )
9686 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9687 "Bad quality volumes created" ));
9688 err->myBadElements.insert( err->myBadElements.end(),
9689 degenVols.begin(),degenVols.end() );
9696 //================================================================================
9698 * \brief Shrink 2D mesh on faces to let space for inflated layers
9700 //================================================================================
9702 bool _ViscousBuilder::shrink(_SolidData& theData)
9704 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9705 // _LayerEdge's inflated along FACE or EDGE)
9706 map< TGeomID, list< _SolidData* > > f2sdMap;
9707 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9709 _SolidData& data = _sdVec[i];
9710 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9711 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9712 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9714 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9716 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9717 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9718 // by StdMeshers_QuadToTriaAdaptor
9719 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9721 SMESH_ProxyMesh::SubMesh* proxySub =
9722 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9723 if ( proxySub->NbElements() == 0 )
9725 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9726 while ( fIt->more() )
9728 const SMDS_MeshElement* f = fIt->next();
9729 // as a result 3D algo will use elements from proxySub and not from smDS
9730 proxySub->AddElement( f );
9731 f->setIsMarked( true );
9733 // Mark nodes on the FACE to discriminate them from nodes
9734 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
9735 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
9737 const SMDS_MeshNode* n = f->GetNode( iN );
9738 if ( n->GetPosition()->GetDim() == 2 )
9739 n->setIsMarked( true );
9747 SMESH_MesherHelper helper( *_mesh );
9748 helper.ToFixNodeParameters( true );
9751 map< TGeomID, _Shrinker1D > e2shrMap;
9752 vector< _EdgesOnShape* > subEOS;
9753 vector< _LayerEdge* > lEdges;
9755 // loop on FACEs to srink mesh on
9756 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9757 for ( ; f2sd != f2sdMap.end(); ++f2sd )
9759 list< _SolidData* > & dataList = f2sd->second;
9760 if ( dataList.front()->_n2eMap.empty() ||
9761 dataList.back() ->_n2eMap.empty() )
9762 continue; // not yet computed
9763 if ( dataList.front() != &theData &&
9764 dataList.back() != &theData )
9767 _SolidData& data = *dataList.front();
9768 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9769 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
9770 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9772 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9774 _shrinkedFaces.Add( F );
9775 helper.SetSubShape( F );
9777 // ===========================
9778 // Prepare data for shrinking
9779 // ===========================
9781 // Collect nodes to smooth, they are marked at the beginning of this method
9782 vector < const SMDS_MeshNode* > smoothNodes;
9784 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9785 while ( nIt->more() )
9787 const SMDS_MeshNode* n = nIt->next();
9788 if ( n->isMarked() )
9789 smoothNodes.push_back( n );
9792 // Find out face orientation
9794 const set<TGeomID> ignoreShapes;
9796 if ( !smoothNodes.empty() )
9798 vector<_Simplex> simplices;
9799 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9800 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9801 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9802 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9803 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9807 // Find _LayerEdge's inflated along F
9811 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9812 /*complexFirst=*/true); //!!!
9813 while ( subIt->more() )
9815 const TGeomID subID = subIt->next()->GetId();
9816 if ( data._noShrinkShapes.count( subID ))
9818 _EdgesOnShape* eos = data.GetShapeEdges( subID );
9819 if ( !eos || eos->_sWOL.IsNull() ) continue;
9821 subEOS.push_back( eos );
9823 for ( size_t i = 0; i < eos->_edges.size(); ++i )
9825 lEdges.push_back( eos->_edges[ i ] );
9826 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9831 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9832 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9833 while ( fIt->more() )
9834 if ( const SMDS_MeshElement* f = fIt->next() )
9835 dumpChangeNodes( f );
9838 // Replace source nodes by target nodes in mesh faces to shrink
9839 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9840 const SMDS_MeshNode* nodes[20];
9841 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9843 _EdgesOnShape& eos = * subEOS[ iS ];
9844 for ( size_t i = 0; i < eos._edges.size(); ++i )
9846 _LayerEdge& edge = *eos._edges[i];
9847 const SMDS_MeshNode* srcNode = edge._nodes[0];
9848 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9849 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9850 while ( fIt->more() )
9852 const SMDS_MeshElement* f = fIt->next();
9853 if ( !smDS->Contains( f ) || !f->isMarked() )
9855 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9856 for ( int iN = 0; nIt->more(); ++iN )
9858 const SMDS_MeshNode* n = nIt->next();
9859 nodes[iN] = ( n == srcNode ? tgtNode : n );
9861 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9862 dumpChangeNodes( f );
9868 // find out if a FACE is concave
9869 const bool isConcaveFace = isConcave( F, helper );
9871 // Create _SmoothNode's on face F
9872 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9874 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9875 const bool sortSimplices = isConcaveFace;
9876 for ( size_t i = 0; i < smoothNodes.size(); ++i )
9878 const SMDS_MeshNode* n = smoothNodes[i];
9879 nodesToSmooth[ i ]._node = n;
9880 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9881 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9882 // fix up incorrect uv of nodes on the FACE
9883 helper.GetNodeUV( F, n, 0, &isOkUV);
9888 //if ( nodesToSmooth.empty() ) continue;
9890 // Find EDGE's to shrink and set simpices to LayerEdge's
9891 set< _Shrinker1D* > eShri1D;
9893 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9895 _EdgesOnShape& eos = * subEOS[ iS ];
9896 if ( eos.SWOLType() == TopAbs_EDGE )
9898 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9899 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
9900 eShri1D.insert( & srinker );
9901 srinker.AddEdge( eos._edges[0], eos, helper );
9902 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9903 // restore params of nodes on EGDE if the EDGE has been already
9904 // srinked while srinking other FACE
9905 srinker.RestoreParams();
9907 for ( size_t i = 0; i < eos._edges.size(); ++i )
9909 _LayerEdge& edge = * eos._edges[i];
9910 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9912 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
9913 // not-marked nodes are those added by refine()
9914 edge._nodes.back()->setIsMarked( true );
9919 bool toFixTria = false; // to improve quality of trias by diagonal swap
9920 if ( isConcaveFace )
9922 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9923 if ( hasTria != hasQuad ) {
9924 toFixTria = hasTria;
9927 set<int> nbNodesSet;
9928 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9929 while ( fIt->more() && nbNodesSet.size() < 2 )
9930 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9931 toFixTria = ( *nbNodesSet.begin() == 3 );
9935 // ==================
9936 // Perform shrinking
9937 // ==================
9939 bool shrinked = true;
9940 int nbBad, shriStep=0, smooStep=0;
9941 _SmoothNode::SmoothType smoothType
9942 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9943 SMESH_Comment errMsg;
9947 // Move boundary nodes (actually just set new UV)
9948 // -----------------------------------------------
9949 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9951 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9953 _EdgesOnShape& eos = * subEOS[ iS ];
9954 for ( size_t i = 0; i < eos._edges.size(); ++i )
9956 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9961 // Move nodes on EDGE's
9962 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9963 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9964 for ( ; shr != eShri1D.end(); ++shr )
9965 (*shr)->Compute( /*set3D=*/false, helper );
9968 // -----------------
9969 int nbNoImpSteps = 0;
9972 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9974 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9976 int oldBadNb = nbBad;
9979 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9980 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9981 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9983 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9984 smooTy, /*set3D=*/isConcaveFace);
9986 if ( nbBad < oldBadNb )
9996 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9997 if ( shriStep > 200 )
9998 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9999 if ( !errMsg.empty() )
10002 // Fix narrow triangles by swapping diagonals
10003 // ---------------------------------------
10006 set<const SMDS_MeshNode*> usedNodes;
10007 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10009 // update working data
10010 set<const SMDS_MeshNode*>::iterator n;
10011 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10013 n = usedNodes.find( nodesToSmooth[ i ]._node );
10014 if ( n != usedNodes.end())
10016 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10017 nodesToSmooth[ i ]._simplices,
10018 ignoreShapes, NULL,
10019 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10020 usedNodes.erase( n );
10023 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10025 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10026 if ( n != usedNodes.end())
10028 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10029 lEdges[i]->_simplices,
10031 usedNodes.erase( n );
10035 // TODO: check effect of this additional smooth
10036 // additional laplacian smooth to increase allowed shrink step
10037 // for ( int st = 1; st; --st )
10039 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10040 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10042 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10043 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10047 } // while ( shrinked )
10049 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10051 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10054 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10056 vector< const SMDS_MeshElement* > facesToRm;
10059 facesToRm.reserve( psm->NbElements() );
10060 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10061 facesToRm.push_back( ite->next() );
10063 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10064 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10067 for ( size_t i = 0; i < facesToRm.size(); ++i )
10068 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10072 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10073 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10074 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10075 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10076 subEOS[iS]->_edges[i]->_nodes.end() );
10078 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10079 while ( itn->more() ) {
10080 const SMDS_MeshNode* n = itn->next();
10081 if ( !nodesToKeep.count( n ))
10082 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10085 // restore position and UV of target nodes
10087 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10088 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10090 _LayerEdge* edge = subEOS[iS]->_edges[i];
10091 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10092 if ( edge->_pos.empty() ||
10093 edge->Is( _LayerEdge::SHRUNK )) continue;
10094 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10096 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10097 pos->SetUParameter( edge->_pos[0].X() );
10098 pos->SetVParameter( edge->_pos[0].Y() );
10099 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10103 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10104 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10105 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10107 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10108 dumpMove( tgtNode );
10110 // shrink EDGE sub-meshes and set proxy sub-meshes
10111 UVPtStructVec uvPtVec;
10112 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10113 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10115 _Shrinker1D* shr = (*shrIt);
10116 shr->Compute( /*set3D=*/true, helper );
10118 // set proxy mesh of EDGEs w/o layers
10119 map< double, const SMDS_MeshNode* > nodes;
10120 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10121 // remove refinement nodes
10122 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10123 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10124 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10125 if ( u2n->second == sn0 || u2n->second == sn1 )
10127 while ( u2n->second != tn0 && u2n->second != tn1 )
10129 nodes.erase( nodes.begin(), u2n );
10131 u2n = --nodes.end();
10132 if ( u2n->second == sn0 || u2n->second == sn1 )
10134 while ( u2n->second != tn0 && u2n->second != tn1 )
10136 nodes.erase( ++u2n, nodes.end() );
10138 // set proxy sub-mesh
10139 uvPtVec.resize( nodes.size() );
10140 u2n = nodes.begin();
10141 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10142 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10144 uvPtVec[ i ].node = u2n->second;
10145 uvPtVec[ i ].param = u2n->first;
10146 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10148 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10149 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10152 // set proxy mesh of EDGEs with layers
10153 vector< _LayerEdge* > edges;
10154 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10156 _EdgesOnShape& eos = * subEOS[ iS ];
10157 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10159 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10160 data.SortOnEdge( E, eos._edges );
10163 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10164 if ( !eov->_edges.empty() )
10165 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10167 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10169 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10170 if ( !eov->_edges.empty() )
10171 edges.push_back( eov->_edges[0] ); // on last VERTEX
10173 uvPtVec.resize( edges.size() );
10174 for ( size_t i = 0; i < edges.size(); ++i )
10176 uvPtVec[ i ].node = edges[i]->_nodes.back();
10177 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10178 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10180 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10181 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10182 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10184 // temporary clear the FACE sub-mesh from faces made by refine()
10185 vector< const SMDS_MeshElement* > elems;
10186 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10187 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10188 elems.push_back( ite->next() );
10189 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10190 elems.push_back( ite->next() );
10193 // compute the mesh on the FACE
10194 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10195 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10197 // re-fill proxy sub-meshes of the FACE
10198 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10199 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10200 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10201 psm->AddElement( ite->next() );
10204 for ( size_t i = 0; i < elems.size(); ++i )
10205 smDS->AddElement( elems[i] );
10207 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10208 return error( errMsg );
10210 } // end of re-meshing in case of failed smoothing
10213 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10214 bool isStructuredFixed = false;
10215 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10216 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10217 if ( !isStructuredFixed )
10219 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10220 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10222 for ( int st = 3; st; --st )
10225 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10226 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10227 case 3: smoothType = _SmoothNode::ANGULAR; break;
10229 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10230 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10232 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10233 smoothType,/*set3D=*/st==1 );
10238 if ( !getMeshDS()->IsEmbeddedMode() )
10239 // Log node movement
10240 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10242 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10243 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10247 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10248 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10250 } // loop on FACES to srink mesh on
10253 // Replace source nodes by target nodes in shrinked mesh edges
10255 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10256 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10257 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10262 //================================================================================
10264 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10266 //================================================================================
10268 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10269 _EdgesOnShape& eos,
10270 SMESH_MesherHelper& helper,
10271 const SMESHDS_SubMesh* faceSubMesh)
10273 const SMDS_MeshNode* srcNode = edge._nodes[0];
10274 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10276 if ( eos.SWOLType() == TopAbs_FACE )
10278 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10281 edge.Set( _LayerEdge::SHRUNK );
10282 return srcNode == tgtNode;
10284 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10285 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10286 gp_Vec2d uvDir( srcUV, tgtUV );
10287 double uvLen = uvDir.Magnitude();
10289 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10292 //edge._pos.resize(1);
10293 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10295 // set UV of source node to target node
10296 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10297 pos->SetUParameter( srcUV.X() );
10298 pos->SetVParameter( srcUV.Y() );
10300 else // _sWOL is TopAbs_EDGE
10302 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10305 edge.Set( _LayerEdge::SHRUNK );
10306 return srcNode == tgtNode;
10308 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10309 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10310 if ( !edgeSM || edgeSM->NbElements() == 0 )
10311 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10313 const SMDS_MeshNode* n2 = 0;
10314 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10315 while ( eIt->more() && !n2 )
10317 const SMDS_MeshElement* e = eIt->next();
10318 if ( !edgeSM->Contains(e)) continue;
10319 n2 = e->GetNode( 0 );
10320 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10323 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10325 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10326 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10327 double u2 = helper.GetNodeU( E, n2, srcNode );
10329 //edge._pos.clear();
10331 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10333 // tgtNode is located so that it does not make faces with wrong orientation
10334 edge.Set( _LayerEdge::SHRUNK );
10337 //edge._pos.resize(1);
10338 edge._pos[0].SetCoord( U_TGT, uTgt );
10339 edge._pos[0].SetCoord( U_SRC, uSrc );
10340 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10342 edge._simplices.resize( 1 );
10343 edge._simplices[0]._nPrev = n2;
10345 // set U of source node to the target node
10346 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10347 pos->SetUParameter( uSrc );
10352 //================================================================================
10354 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10356 //================================================================================
10358 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10360 if ( edge._nodes.size() == 1 )
10365 const SMDS_MeshNode* srcNode = edge._nodes[0];
10366 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10367 if ( S.IsNull() ) return;
10371 switch ( S.ShapeType() )
10376 TopLoc_Location loc;
10377 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10378 if ( curve.IsNull() ) return;
10379 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10380 p = curve->Value( ePos->GetUParameter() );
10383 case TopAbs_VERTEX:
10385 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10390 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10391 dumpMove( srcNode );
10395 //================================================================================
10397 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10399 //================================================================================
10401 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10402 SMESH_MesherHelper& helper,
10405 set<const SMDS_MeshNode*> * involvedNodes)
10407 SMESH::Controls::AspectRatio qualifier;
10408 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10409 const double maxAspectRatio = is2D ? 4. : 2;
10410 _NodeCoordHelper xyz( F, helper, is2D );
10412 // find bad triangles
10414 vector< const SMDS_MeshElement* > badTrias;
10415 vector< double > badAspects;
10416 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
10417 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10418 while ( fIt->more() )
10420 const SMDS_MeshElement * f = fIt->next();
10421 if ( f->NbCornerNodes() != 3 ) continue;
10422 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10423 double aspect = qualifier.GetValue( points );
10424 if ( aspect > maxAspectRatio )
10426 badTrias.push_back( f );
10427 badAspects.push_back( aspect );
10432 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10433 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10434 while ( fIt->more() )
10436 const SMDS_MeshElement * f = fIt->next();
10437 if ( f->NbCornerNodes() == 3 )
10438 dumpChangeNodes( f );
10442 if ( badTrias.empty() )
10445 // find couples of faces to swap diagonal
10447 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10448 vector< T2Trias > triaCouples;
10450 TIDSortedElemSet involvedFaces, emptySet;
10451 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10454 double aspRatio [3];
10457 if ( !involvedFaces.insert( badTrias[iTia] ).second )
10459 for ( int iP = 0; iP < 3; ++iP )
10460 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10462 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10463 int bestCouple = -1;
10464 for ( int iSide = 0; iSide < 3; ++iSide )
10466 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10467 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10468 trias [iSide].first = badTrias[iTia];
10469 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10471 if (( ! trias[iSide].second ) ||
10472 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10473 ( ! sm->Contains( trias[iSide].second )))
10476 // aspect ratio of an adjacent tria
10477 for ( int iP = 0; iP < 3; ++iP )
10478 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10479 double aspectInit = qualifier.GetValue( points2 );
10481 // arrange nodes as after diag-swaping
10482 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10483 i3 = helper.WrapIndex( i1-1, 3 );
10485 i3 = helper.WrapIndex( i1+1, 3 );
10487 points1( 1+ iSide ) = points2( 1+ i3 );
10488 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
10490 // aspect ratio after diag-swaping
10491 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10492 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10495 // prevent inversion of a triangle
10496 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10497 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10498 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10501 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10502 bestCouple = iSide;
10505 if ( bestCouple >= 0 )
10507 triaCouples.push_back( trias[bestCouple] );
10508 involvedFaces.insert ( trias[bestCouple].second );
10512 involvedFaces.erase( badTrias[iTia] );
10515 if ( triaCouples.empty() )
10520 SMESH_MeshEditor editor( helper.GetMesh() );
10521 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10522 for ( size_t i = 0; i < triaCouples.size(); ++i )
10524 dumpChangeNodes( triaCouples[i].first );
10525 dumpChangeNodes( triaCouples[i].second );
10526 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10529 if ( involvedNodes )
10530 for ( size_t i = 0; i < triaCouples.size(); ++i )
10532 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10533 triaCouples[i].first->end_nodes() );
10534 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10535 triaCouples[i].second->end_nodes() );
10538 // just for debug dump resulting triangles
10539 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10540 for ( size_t i = 0; i < triaCouples.size(); ++i )
10542 dumpChangeNodes( triaCouples[i].first );
10543 dumpChangeNodes( triaCouples[i].second );
10547 //================================================================================
10549 * \brief Move target node to it's final position on the FACE during shrinking
10551 //================================================================================
10553 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10554 const TopoDS_Face& F,
10555 _EdgesOnShape& eos,
10556 SMESH_MesherHelper& helper )
10559 return false; // already at the target position
10561 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10563 if ( eos.SWOLType() == TopAbs_FACE )
10565 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
10566 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10567 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10568 const double uvLen = tgtUV.Distance( curUV );
10569 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10571 // Select shrinking step such that not to make faces with wrong orientation.
10572 double stepSize = 1e100;
10573 for ( size_t i = 0; i < _simplices.size(); ++i )
10575 if ( !_simplices[i]._nPrev->isMarked() ||
10576 !_simplices[i]._nNext->isMarked() )
10577 continue; // simplex of quadrangle created by addBoundaryElements()
10579 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10580 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10581 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10582 gp_XY dirN = uvN2 - uvN1;
10583 double det = uvDir.Crossed( dirN );
10584 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
10585 gp_XY dirN2Cur = curUV - uvN1;
10586 double step = dirN.Crossed( dirN2Cur ) / det;
10588 stepSize = Min( step, stepSize );
10591 if ( uvLen <= stepSize )
10597 else if ( stepSize > 0 )
10599 newUV = curUV + uvDir.XY() * stepSize * kSafe;
10605 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10606 pos->SetUParameter( newUV.X() );
10607 pos->SetVParameter( newUV.Y() );
10610 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10611 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10612 dumpMove( tgtNode );
10615 else // _sWOL is TopAbs_EDGE
10617 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10618 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
10619 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10621 const double u2 = helper.GetNodeU( E, n2, tgtNode );
10622 const double uSrc = _pos[0].Coord( U_SRC );
10623 const double lenTgt = _pos[0].Coord( LEN_TGT );
10625 double newU = _pos[0].Coord( U_TGT );
10626 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10628 Set( _LayerEdge::SHRUNK );
10633 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10635 tgtPos->SetUParameter( newU );
10637 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10638 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10639 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10640 dumpMove( tgtNode );
10647 //================================================================================
10649 * \brief Perform smooth on the FACE
10650 * \retval bool - true if the node has been moved
10652 //================================================================================
10654 bool _SmoothNode::Smooth(int& nbBad,
10655 Handle(Geom_Surface)& surface,
10656 SMESH_MesherHelper& helper,
10657 const double refSign,
10661 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10663 // get uv of surrounding nodes
10664 vector<gp_XY> uv( _simplices.size() );
10665 for ( size_t i = 0; i < _simplices.size(); ++i )
10666 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10668 // compute new UV for the node
10669 gp_XY newPos (0,0);
10670 if ( how == TFI && _simplices.size() == 4 )
10673 for ( size_t i = 0; i < _simplices.size(); ++i )
10674 if ( _simplices[i]._nOpp )
10675 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10677 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10679 newPos = helper.calcTFI ( 0.5, 0.5,
10680 corners[0], corners[1], corners[2], corners[3],
10681 uv[1], uv[2], uv[3], uv[0] );
10683 else if ( how == ANGULAR )
10685 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10687 else if ( how == CENTROIDAL && _simplices.size() > 3 )
10689 // average centers of diagonals wieghted with their reciprocal lengths
10690 if ( _simplices.size() == 4 )
10692 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10693 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10694 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10698 double sumWeight = 0;
10699 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10700 for ( int i = 0; i < nb; ++i )
10703 int iTo = i + _simplices.size() - 1;
10704 for ( int j = iFrom; j < iTo; ++j )
10706 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10707 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10709 newPos += w * ( uv[i]+uv[i2] );
10712 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10717 // Laplacian smooth
10718 for ( size_t i = 0; i < _simplices.size(); ++i )
10720 newPos /= _simplices.size();
10723 // count quality metrics (orientation) of triangles around the node
10724 int nbOkBefore = 0;
10725 gp_XY tgtUV = helper.GetNodeUV( face, _node );
10726 for ( size_t i = 0; i < _simplices.size(); ++i )
10727 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10730 for ( size_t i = 0; i < _simplices.size(); ++i )
10731 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10733 if ( nbOkAfter < nbOkBefore )
10735 nbBad += _simplices.size() - nbOkBefore;
10739 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10740 pos->SetUParameter( newPos.X() );
10741 pos->SetVParameter( newPos.Y() );
10748 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10749 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10753 nbBad += _simplices.size() - nbOkAfter;
10754 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10757 //================================================================================
10759 * \brief Computes new UV using angle based smoothing technic
10761 //================================================================================
10763 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10764 const gp_XY& uvToFix,
10765 const double refSign)
10767 uv.push_back( uv.front() );
10769 vector< gp_XY > edgeDir ( uv.size() );
10770 vector< double > edgeSize( uv.size() );
10771 for ( size_t i = 1; i < edgeDir.size(); ++i )
10773 edgeDir [i-1] = uv[i] - uv[i-1];
10774 edgeSize[i-1] = edgeDir[i-1].Modulus();
10775 if ( edgeSize[i-1] < numeric_limits<double>::min() )
10776 edgeDir[i-1].SetX( 100 );
10778 edgeDir[i-1] /= edgeSize[i-1] * refSign;
10780 edgeDir.back() = edgeDir.front();
10781 edgeSize.back() = edgeSize.front();
10785 double sumSize = 0;
10786 for ( size_t i = 1; i < edgeDir.size(); ++i )
10788 if ( edgeDir[i-1].X() > 1. ) continue;
10790 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10791 if ( i == edgeDir.size() ) break;
10793 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10794 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
10795 gp_XY bisec = norm1 + norm2;
10796 double bisecSize = bisec.Modulus();
10797 if ( bisecSize < numeric_limits<double>::min() )
10799 bisec = -edgeDir[i1] + edgeDir[i];
10800 bisecSize = bisec.Modulus();
10802 bisec /= bisecSize;
10804 gp_XY dirToN = uvToFix - p;
10805 double distToN = dirToN.Modulus();
10806 if ( bisec * dirToN < 0 )
10807 distToN = -distToN;
10809 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10811 sumSize += edgeSize[i1] + edgeSize[i];
10813 newPos /= /*nbEdges * */sumSize;
10817 //================================================================================
10819 * \brief Delete _SolidData
10821 //================================================================================
10823 _SolidData::~_SolidData()
10825 TNode2Edge::iterator n2e = _n2eMap.begin();
10826 for ( ; n2e != _n2eMap.end(); ++n2e )
10828 _LayerEdge* & e = n2e->second;
10831 delete e->_curvature;
10832 if ( e->_2neibors )
10833 delete e->_2neibors->_plnNorm;
10834 delete e->_2neibors;
10845 //================================================================================
10847 * \brief Keep a _LayerEdge inflated along the EDGE
10849 //================================================================================
10851 void _Shrinker1D::AddEdge( const _LayerEdge* e,
10852 _EdgesOnShape& eos,
10853 SMESH_MesherHelper& helper )
10856 if ( _nodes.empty() )
10858 _edges[0] = _edges[1] = 0;
10861 // check _LayerEdge
10862 if ( e == _edges[0] || e == _edges[1] )
10864 if ( eos.SWOLType() != TopAbs_EDGE )
10865 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10866 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10867 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10869 // store _LayerEdge
10870 _geomEdge = TopoDS::Edge( eos._sWOL );
10872 BRep_Tool::Range( _geomEdge, f,l );
10873 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10874 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10878 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10879 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10881 if ( _nodes.empty() )
10883 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10884 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10886 TopLoc_Location loc;
10887 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10888 GeomAdaptor_Curve aCurve(C, f,l);
10889 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10891 int nbExpectNodes = eSubMesh->NbNodes();
10892 _initU .reserve( nbExpectNodes );
10893 _normPar.reserve( nbExpectNodes );
10894 _nodes .reserve( nbExpectNodes );
10895 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10896 while ( nIt->more() )
10898 const SMDS_MeshNode* node = nIt->next();
10900 // skip refinement nodes
10901 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10902 node == tgtNode0 || node == tgtNode1 )
10904 bool hasMarkedFace = false;
10905 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
10906 while ( fIt->more() && !hasMarkedFace )
10907 hasMarkedFace = fIt->next()->isMarked();
10908 if ( !hasMarkedFace )
10911 _nodes.push_back( node );
10912 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10913 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10914 _normPar.push_back( len / totLen );
10919 // remove target node of the _LayerEdge from _nodes
10920 size_t nbFound = 0;
10921 for ( size_t i = 0; i < _nodes.size(); ++i )
10922 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10923 _nodes[i] = 0, nbFound++;
10924 if ( nbFound == _nodes.size() )
10929 //================================================================================
10931 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10933 //================================================================================
10935 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10937 if ( _done || _nodes.empty())
10939 const _LayerEdge* e = _edges[0];
10940 if ( !e ) e = _edges[1];
10943 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
10944 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
10947 if ( set3D || _done )
10949 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10950 GeomAdaptor_Curve aCurve(C, f,l);
10953 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10955 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10956 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10958 for ( size_t i = 0; i < _nodes.size(); ++i )
10960 if ( !_nodes[i] ) continue;
10961 double len = totLen * _normPar[i];
10962 GCPnts_AbscissaPoint discret( aCurve, len, f );
10963 if ( !discret.IsDone() )
10964 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10965 double u = discret.Parameter();
10966 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10967 pos->SetUParameter( u );
10968 gp_Pnt p = C->Value( u );
10969 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10974 BRep_Tool::Range( _geomEdge, f,l );
10976 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10978 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10980 for ( size_t i = 0; i < _nodes.size(); ++i )
10982 if ( !_nodes[i] ) continue;
10983 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10984 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10985 pos->SetUParameter( u );
10990 //================================================================================
10992 * \brief Restore initial parameters of nodes on EDGE
10994 //================================================================================
10996 void _Shrinker1D::RestoreParams()
10999 for ( size_t i = 0; i < _nodes.size(); ++i )
11001 if ( !_nodes[i] ) continue;
11002 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11003 pos->SetUParameter( _initU[i] );
11008 //================================================================================
11010 * \brief Replace source nodes by target nodes in shrinked mesh edges
11012 //================================================================================
11014 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11016 const SMDS_MeshNode* nodes[3];
11017 for ( int i = 0; i < 2; ++i )
11019 if ( !_edges[i] ) continue;
11021 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11022 if ( !eSubMesh ) return;
11023 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11024 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11025 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11026 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11027 while ( eIt->more() )
11029 const SMDS_MeshElement* e = eIt->next();
11030 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11032 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11033 for ( int iN = 0; iN < e->NbNodes(); ++iN )
11035 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11036 nodes[iN] = ( n == srcNode ? tgtNode : n );
11038 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11043 //================================================================================
11045 * \brief Creates 2D and 1D elements on boundaries of new prisms
11047 //================================================================================
11049 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11051 SMESH_MesherHelper helper( *_mesh );
11053 vector< const SMDS_MeshNode* > faceNodes;
11055 //for ( size_t i = 0; i < _sdVec.size(); ++i )
11057 //_SolidData& data = _sdVec[i];
11058 TopTools_IndexedMapOfShape geomEdges;
11059 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11060 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11062 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11063 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
11066 // Get _LayerEdge's based on E
11068 map< double, const SMDS_MeshNode* > u2nodes;
11069 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11072 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11073 TNode2Edge & n2eMap = data._n2eMap;
11074 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11076 //check if 2D elements are needed on E
11077 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11078 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11079 ledges.push_back( n2e->second );
11081 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11082 continue; // no layers on E
11083 ledges.push_back( n2eMap[ u2n->second ]);
11085 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11086 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11087 int nbSharedPyram = 0;
11088 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11089 while ( vIt->more() )
11091 const SMDS_MeshElement* v = vIt->next();
11092 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11094 if ( nbSharedPyram > 1 )
11095 continue; // not free border of the pyramid
11098 faceNodes.push_back( ledges[0]->_nodes[0] );
11099 faceNodes.push_back( ledges[1]->_nodes[0] );
11100 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11101 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11103 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11104 continue; // faces already created
11106 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11107 ledges.push_back( n2eMap[ u2n->second ]);
11109 // Find out orientation and type of face to create
11111 bool reverse = false, isOnFace;
11113 map< TGeomID, TopoDS_Shape >::iterator e2f =
11114 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
11116 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11118 F = e2f->second.Oriented( TopAbs_FORWARD );
11119 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11120 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11121 reverse = !reverse, F.Reverse();
11122 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11123 reverse = !reverse;
11125 else if ( !data._ignoreFaceIds.count( e2f->first ))
11127 // find FACE with layers sharing E
11128 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11130 F = *( fIt->next() );
11132 // Find the sub-mesh to add new faces
11133 SMESHDS_SubMesh* sm = 0;
11135 sm = getMeshDS()->MeshElements( F );
11137 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11139 return error("error in addBoundaryElements()", data._index);
11142 const int dj1 = reverse ? 0 : 1;
11143 const int dj2 = reverse ? 1 : 0;
11144 for ( size_t j = 1; j < ledges.size(); ++j )
11146 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11147 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11148 if ( nn1.size() == nn2.size() )
11151 for ( size_t z = 1; z < nn1.size(); ++z )
11152 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11154 for ( size_t z = 1; z < nn1.size(); ++z )
11155 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11157 else if ( nn1.size() == 1 )
11160 for ( size_t z = 1; z < nn2.size(); ++z )
11161 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11163 for ( size_t z = 1; z < nn2.size(); ++z )
11164 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11169 for ( size_t z = 1; z < nn1.size(); ++z )
11170 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11172 for ( size_t z = 1; z < nn1.size(); ++z )
11173 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11178 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11180 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11181 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11182 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11184 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11185 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11187 helper.SetSubShape( eos->_sWOL );
11188 helper.SetElementsOnShape( true );
11189 for ( size_t z = 1; z < nn.size(); ++z )
11190 helper.AddEdge( nn[z-1], nn[z] );
11194 } // loop on EDGE's
11195 } // loop on _SolidData's