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.6;
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 achieved 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 _LayerEdge::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 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
437 MARKED = 0x0000200, // local usage
438 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
439 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
440 SMOOTHED_C1 = 0x0001000, // is on _eosC1
441 DISTORTED = 0x0002000, // was bad before smoothing
442 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
443 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
444 UNUSED_FLAG = 0x0100000 // to add user flags after
446 bool Is ( int flag ) const { return _flags & flag; }
447 void Set ( int flag ) { _flags |= flag; }
448 void Unset( int flag ) { _flags &= ~flag; }
449 std::string DumpFlags() const; // debug
451 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
452 bool SetNewLength2d( Handle(Geom_Surface)& surface,
453 const TopoDS_Face& F,
455 SMESH_MesherHelper& helper );
456 void SetDataByNeighbors( const SMDS_MeshNode* n1,
457 const SMDS_MeshNode* n2,
458 const _EdgesOnShape& eos,
459 SMESH_MesherHelper& helper);
460 void Block( _SolidData& data );
461 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
462 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
463 const TNode2Edge& n2eMap);
464 void SmoothPos( const vector< double >& segLen, const double tol );
465 int GetSmoothedPos( const double tol );
466 int Smooth(const int step, const bool isConcaveFace, bool findBest);
467 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
468 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
469 void SmoothWoCheck();
470 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
471 const TopoDS_Face& F,
472 SMESH_MesherHelper& helper);
473 void MoveNearConcaVer( const _EdgesOnShape* eov,
474 const _EdgesOnShape* eos,
476 vector< _LayerEdge* > & badSmooEdges);
477 bool FindIntersection( SMESH_ElementSearcher& searcher,
479 const double& epsilon,
481 const SMDS_MeshElement** face = 0);
482 bool SegTriaInter( const gp_Ax1& lastSegment,
487 const double& epsilon) const;
488 bool SegTriaInter( const gp_Ax1& lastSegment,
489 const SMDS_MeshNode* n0,
490 const SMDS_MeshNode* n1,
491 const SMDS_MeshNode* n2,
493 const double& epsilon) const
494 { return SegTriaInter( lastSegment,
495 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
498 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
499 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
500 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
501 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
502 bool IsOnEdge() const { return _2neibors; }
503 bool IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
504 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
505 void SetCosin( double cosin );
506 void SetNormal( const gp_XYZ& n ) { _normal = n; }
507 void SetMaxLen( double l ) { _maxLen = l; }
508 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
509 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
510 void SetSmooLen( double len ) { // set _len at which smoothing is needed
511 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
513 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
515 gp_XYZ smoothLaplacian();
516 gp_XYZ smoothAngular();
517 gp_XYZ smoothLengthWeighted();
518 gp_XYZ smoothCentroidal();
519 gp_XYZ smoothNefPolygon();
521 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
522 static const int theNbSmooFuns = FUN_NB;
523 static PSmooFun _funs[theNbSmooFuns];
524 static const char* _funNames[theNbSmooFuns+1];
525 int smooFunID( PSmooFun fun=0) const;
527 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
528 &_LayerEdge::smoothLengthWeighted,
529 &_LayerEdge::smoothCentroidal,
530 &_LayerEdge::smoothNefPolygon,
531 &_LayerEdge::smoothAngular };
532 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
540 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
542 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
543 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
546 //--------------------------------------------------------------------------------
548 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
552 gp_XY _pos, _dir, _inNorm;
553 bool IsOut( const gp_XY p, const double tol ) const
555 return _inNorm * ( p - _pos ) < -tol;
557 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
559 //const double eps = 1e-10;
560 double D = _dir.Crossed( hp._dir );
561 if ( fabs(D) < std::numeric_limits<double>::min())
563 gp_XY vec21 = _pos - hp._pos;
564 double u = hp._dir.Crossed( vec21 ) / D;
565 intPnt = _pos + _dir * u;
569 //--------------------------------------------------------------------------------
571 * Structure used to smooth a _LayerEdge based on an EDGE.
575 double _wgt [2]; // weights of _nodes
576 _LayerEdge* _edges[2];
578 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
581 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
582 const SMDS_MeshNode* tgtNode(bool is2nd) {
583 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
585 const SMDS_MeshNode* srcNode(bool is2nd) {
586 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
589 std::swap( _wgt [0], _wgt [1] );
590 std::swap( _edges[0], _edges[1] );
592 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
593 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
595 bool include( const _LayerEdge* e ) {
596 return ( _edges[0] == e || _edges[1] == e );
601 //--------------------------------------------------------------------------------
603 * \brief Layers parameters got by averaging several hypotheses
607 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
608 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
612 void Add( const StdMeshers_ViscousLayers* hyp )
617 _nbLayers = hyp->GetNumberLayers();
618 //_thickness += hyp->GetTotalThickness();
619 _thickness = Max( _thickness, hyp->GetTotalThickness() );
620 _stretchFactor += hyp->GetStretchFactor();
621 _method = hyp->GetMethod();
624 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
625 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
626 int GetNumberLayers() const { return _nbLayers; }
627 int GetMethod() const { return _method; }
629 bool UseSurfaceNormal() const
630 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
631 bool ToSmooth() const
632 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
633 bool IsOffsetMethod() const
634 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
637 int _nbLayers, _nbHyps, _method;
638 double _thickness, _stretchFactor;
641 //--------------------------------------------------------------------------------
643 * \brief _LayerEdge's on a shape and other shape data
647 vector< _LayerEdge* > _edges;
651 SMESH_subMesh * _subMesh;
652 // face or edge w/o layer along or near which _edges are inflated
654 bool _isRegularSWOL; // w/o singularities
655 // averaged StdMeshers_ViscousLayers parameters
658 _Smoother1D* _edgeSmoother;
659 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
660 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
662 vector< gp_XYZ > _faceNormals; // if _shape is FACE
663 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
665 Handle(ShapeAnalysis_Surface) _offsetSurf;
666 _LayerEdge* _edgeForOffset;
668 _SolidData* _data; // parent SOLID
670 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
671 size_t size() const { return _edges.size(); }
672 TopAbs_ShapeEnum ShapeType() const
673 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
674 TopAbs_ShapeEnum SWOLType() const
675 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
676 bool HasC1( const _EdgesOnShape* other ) const
677 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
678 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
679 _SolidData& GetData() const { return *_data; }
681 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
684 //--------------------------------------------------------------------------------
686 * \brief Convex FACE whose radius of curvature is less than the thickness of
687 * layers. It is used to detect distortion of prisms based on a convex
688 * FACE and to update normals to enable further increasing the thickness
694 // edges whose _simplices are used to detect prism distortion
695 vector< _LayerEdge* > _simplexTestEdges;
697 // map a sub-shape to _SolidData::_edgesOnShape
698 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
702 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
704 double GetMaxCurvature( _SolidData& data,
706 BRepLProp_SLProps& surfProp,
707 SMESH_MesherHelper& helper);
709 bool GetCenterOfCurvature( _LayerEdge* ledge,
710 BRepLProp_SLProps& surfProp,
711 SMESH_MesherHelper& helper,
712 gp_Pnt & center ) const;
713 bool CheckPrisms() const;
716 //--------------------------------------------------------------------------------
718 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
719 * at inflation up to the full thickness. A detected collision
720 * is fixed in updateNormals()
722 struct _CollisionEdges
725 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
726 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
727 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
730 //--------------------------------------------------------------------------------
732 * \brief Data of a SOLID
736 typedef const StdMeshers_ViscousLayers* THyp;
738 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
739 TGeomID _index; // SOLID id
740 _MeshOfSolid* _proxyMesh;
742 list< TopoDS_Shape > _hypShapes;
743 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
744 set< TGeomID > _reversedFaceIds;
745 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
747 double _stepSize, _stepSizeCoeff, _geomSize;
748 const SMDS_MeshNode* _stepSizeNodes[2];
750 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
752 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
753 map< TGeomID, TNode2Edge* > _s2neMap;
754 // _LayerEdge's with underlying shapes
755 vector< _EdgesOnShape > _edgesOnShape;
757 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
758 // layers and a FACE w/o layers
759 // value: the shape (FACE or EDGE) to shrink mesh on.
760 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
761 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
763 // Convex FACEs whose radius of curvature is less than the thickness of layers
764 map< TGeomID, _ConvexFace > _convexFaces;
766 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
767 // the adjacent SOLID
768 set< TGeomID > _noShrinkShapes;
770 int _nbShapesToSmooth;
772 vector< _CollisionEdges > _collisionEdges;
773 set< TGeomID > _concaveFaces;
775 double _maxThickness; // of all _hyps
776 double _minThickness; // of all _hyps
778 double _epsilon; // precision for SegTriaInter()
780 SMESH_MesherHelper* _helper;
782 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
784 :_solid(s), _proxyMesh(m), _helper(0) {}
787 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
788 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
790 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
791 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
792 return id2face == _convexFaces.end() ? 0 : & id2face->second;
794 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
795 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
796 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
797 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
799 SMESH_MesherHelper& GetHelper() const { return *_helper; }
801 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
802 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
803 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
804 _edgesOnShape[i]._edges[j]->Unset( flag );
806 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
807 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
809 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
811 //--------------------------------------------------------------------------------
813 * \brief Offset plane used in getNormalByOffset()
819 int _faceIndexNext[2];
820 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
823 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
825 void ComputeIntersectionLine( _OffsetPlane& pln,
826 const TopoDS_Edge& E,
827 const TopoDS_Vertex& V );
828 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
829 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
831 //--------------------------------------------------------------------------------
833 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
835 struct _CentralCurveOnEdge
838 vector< gp_Pnt > _curvaCenters;
839 vector< _LayerEdge* > _ledges;
840 vector< gp_XYZ > _normals; // new normal for each of _ledges
841 vector< double > _segLength2;
844 TopoDS_Face _adjFace;
845 bool _adjFaceToSmooth;
847 void Append( const gp_Pnt& center, _LayerEdge* ledge )
849 if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
851 if ( _curvaCenters.size() > 0 )
852 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
853 _curvaCenters.push_back( center );
854 _ledges.push_back( ledge );
855 _normals.push_back( ledge->_normal );
857 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
858 void SetShapes( const TopoDS_Edge& edge,
859 const _ConvexFace& convFace,
861 SMESH_MesherHelper& helper);
863 //--------------------------------------------------------------------------------
865 * \brief Data of node on a shrinked FACE
869 const SMDS_MeshNode* _node;
870 vector<_Simplex> _simplices; // for quality check
872 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
874 bool Smooth(int& badNb,
875 Handle(Geom_Surface)& surface,
876 SMESH_MesherHelper& helper,
877 const double refSign,
881 gp_XY computeAngularPos(vector<gp_XY>& uv,
882 const gp_XY& uvToFix,
883 const double refSign );
886 //--------------------------------------------------------------------------------
888 * \brief Builder of viscous layers
890 class _ViscousBuilder
895 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
896 const TopoDS_Shape& shape);
897 // check validity of hypotheses
898 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
899 const TopoDS_Shape& shape );
901 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
902 void RestoreListeners();
904 // computes SMESH_ProxyMesh::SubMesh::_n2n;
905 bool MakeN2NMap( _MeshOfSolid* pm );
909 bool findSolidsWithLayers();
910 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
911 bool findFacesWithLayers(const bool onlyWith=false);
912 void getIgnoreFaces(const TopoDS_Shape& solid,
913 const StdMeshers_ViscousLayers* hyp,
914 const TopoDS_Shape& hypShape,
915 set<TGeomID>& ignoreFaces);
916 bool makeLayer(_SolidData& data);
917 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
918 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
919 SMESH_MesherHelper& helper, _SolidData& data);
920 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
921 const TopoDS_Face& face,
922 SMESH_MesherHelper& helper,
924 bool shiftInside=false);
925 bool getFaceNormalAtSingularity(const gp_XY& uv,
926 const TopoDS_Face& face,
927 SMESH_MesherHelper& helper,
929 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
930 gp_XYZ getNormalByOffset( _LayerEdge* edge,
931 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
933 bool lastNoOffset = false);
934 bool findNeiborsOnEdge(const _LayerEdge* edge,
935 const SMDS_MeshNode*& n1,
936 const SMDS_MeshNode*& n2,
939 void findSimplexTestEdges( _SolidData& data,
940 vector< vector<_LayerEdge*> >& edgesByGeom);
941 void computeGeomSize( _SolidData& data );
942 bool findShapesToSmooth( _SolidData& data);
943 void limitStepSizeByCurvature( _SolidData& data );
944 void limitStepSize( _SolidData& data,
945 const SMDS_MeshElement* face,
946 const _LayerEdge* maxCosinEdge );
947 void limitStepSize( _SolidData& data, const double minSize);
948 bool inflate(_SolidData& data);
949 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
950 int invalidateBadSmooth( _SolidData& data,
951 SMESH_MesherHelper& helper,
952 vector< _LayerEdge* >& badSmooEdges,
953 vector< _EdgesOnShape* >& eosC1,
955 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
956 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
957 vector< _EdgesOnShape* >& eosC1,
958 int smooStep=0, int moveAll=false );
959 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
960 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
962 SMESH_MesherHelper& helper );
963 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
964 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
965 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
966 const bool isSmoothable );
967 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
968 bool updateNormalsOfConvexFaces( _SolidData& data,
969 SMESH_MesherHelper& helper,
971 void updateNormalsOfC1Vertices( _SolidData& data );
972 bool updateNormalsOfSmoothed( _SolidData& data,
973 SMESH_MesherHelper& helper,
975 const double stepSize );
976 bool isNewNormalOk( _SolidData& data,
978 const gp_XYZ& newNormal);
979 bool refine(_SolidData& data);
980 bool shrink(_SolidData& data);
981 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
982 SMESH_MesherHelper& helper,
983 const SMESHDS_SubMesh* faceSubMesh );
984 void restoreNoShrink( _LayerEdge& edge ) const;
985 void fixBadFaces(const TopoDS_Face& F,
986 SMESH_MesherHelper& helper,
989 set<const SMDS_MeshNode*> * involvedNodes=NULL);
990 bool addBoundaryElements(_SolidData& data);
992 bool error( const string& text, int solidID=-1 );
993 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
996 void makeGroupOfLE();
999 SMESH_ComputeErrorPtr _error;
1001 vector< _SolidData > _sdVec;
1002 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1003 TopTools_MapOfShape _shrinkedFaces;
1008 //--------------------------------------------------------------------------------
1010 * \brief Shrinker of nodes on the EDGE
1014 TopoDS_Edge _geomEdge;
1015 vector<double> _initU;
1016 vector<double> _normPar;
1017 vector<const SMDS_MeshNode*> _nodes;
1018 const _LayerEdge* _edges[2];
1021 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1022 void Compute(bool set3D, SMESH_MesherHelper& helper);
1023 void RestoreParams();
1024 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1025 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1026 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1027 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1028 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1029 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1031 //--------------------------------------------------------------------------------
1033 * \brief Smoother of _LayerEdge's on EDGE.
1037 struct OffPnt // point of the offsetted EDGE
1039 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1040 double _len; // length reached at previous inflation step
1041 double _param; // on EDGE
1042 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1043 gp_XYZ _edgeDir;// EDGE tangent at _param
1044 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1046 vector< OffPnt > _offPoints;
1047 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1048 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1049 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1050 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1051 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1052 _EdgesOnShape& _eos;
1053 double _curveLen; // length of the EDGE
1054 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1056 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1058 SMESH_MesherHelper& helper);
1060 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1061 _EdgesOnShape& eos )
1062 : _anaCurve( curveForSmooth ), _eos( eos )
1065 bool Perform(_SolidData& data,
1066 Handle(ShapeAnalysis_Surface)& surface,
1067 const TopoDS_Face& F,
1068 SMESH_MesherHelper& helper );
1070 void prepare(_SolidData& data );
1072 void findEdgesToSmooth();
1074 bool isToSmooth( int iE );
1076 bool smoothAnalyticEdge( _SolidData& data,
1077 Handle(ShapeAnalysis_Surface)& surface,
1078 const TopoDS_Face& F,
1079 SMESH_MesherHelper& helper);
1080 bool smoothComplexEdge( _SolidData& data,
1081 Handle(ShapeAnalysis_Surface)& surface,
1082 const TopoDS_Face& F,
1083 SMESH_MesherHelper& helper);
1084 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1085 const gp_XYZ& edgeDir);
1086 _LayerEdge* getLEdgeOnV( bool is2nd )
1088 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1090 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1092 void offPointsToPython() const; // debug
1094 //--------------------------------------------------------------------------------
1096 * \brief Class of temporary mesh face.
1097 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1098 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1100 struct _TmpMeshFace : public SMDS_MeshElement
1102 vector<const SMDS_MeshNode* > _nn;
1103 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1104 int id, int faceID=-1, int idInFace=-1):
1105 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1106 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1107 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1108 virtual vtkIdType GetVtkType() const { return -1; }
1109 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1110 virtual SMDSAbs_GeometryType GetGeomType() const
1111 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1112 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1113 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1115 //--------------------------------------------------------------------------------
1117 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1119 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1121 _LayerEdge *_le1, *_le2;
1122 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1123 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1125 _nn[0]=_le1->_nodes[0];
1126 _nn[1]=_le1->_nodes.back();
1127 _nn[2]=_le2->_nodes.back();
1128 _nn[3]=_le2->_nodes[0];
1130 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1132 SMESH_TNodeXYZ p0s( _nn[0] );
1133 SMESH_TNodeXYZ p0t( _nn[1] );
1134 SMESH_TNodeXYZ p1t( _nn[2] );
1135 SMESH_TNodeXYZ p1s( _nn[3] );
1136 gp_XYZ v0 = p0t - p0s;
1137 gp_XYZ v1 = p1t - p1s;
1138 gp_XYZ v01 = p1s - p0s;
1139 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1144 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1146 _nn[0]=le1->_nodes[0];
1147 _nn[1]=le1->_nodes.back();
1148 _nn[2]=le2->_nodes.back();
1149 _nn[3]=le2->_nodes[0];
1153 //--------------------------------------------------------------------------------
1155 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1156 * \warning Location of a surface is ignored
1158 struct _NodeCoordHelper
1160 SMESH_MesherHelper& _helper;
1161 const TopoDS_Face& _face;
1162 Handle(Geom_Surface) _surface;
1163 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1165 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1166 : _helper( helper ), _face( F )
1170 TopLoc_Location loc;
1171 _surface = BRep_Tool::Surface( _face, loc );
1173 if ( _surface.IsNull() )
1174 _fun = & _NodeCoordHelper::direct;
1176 _fun = & _NodeCoordHelper::byUV;
1178 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1181 gp_XYZ direct(const SMDS_MeshNode* n) const
1183 return SMESH_TNodeXYZ( n );
1185 gp_XYZ byUV (const SMDS_MeshNode* n) const
1187 gp_XY uv = _helper.GetNodeUV( _face, n );
1188 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1192 //================================================================================
1194 * \brief Check angle between vectors
1196 //================================================================================
1198 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1200 double dot = v1 * v2; // cos * |v1| * |v2|
1201 double l1 = v1.SquareMagnitude();
1202 double l2 = v2.SquareMagnitude();
1203 return (( dot * cos >= 0 ) &&
1204 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1207 } // namespace VISCOUS_3D
1211 //================================================================================
1212 // StdMeshers_ViscousLayers hypothesis
1214 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1215 :SMESH_Hypothesis(hypId, studyId, gen),
1216 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1217 _method( SURF_OFFSET_SMOOTH )
1219 _name = StdMeshers_ViscousLayers::GetHypType();
1220 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1221 } // --------------------------------------------------------------------------------
1222 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1224 if ( faceIds != _shapeIds )
1225 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1226 if ( _isToIgnoreShapes != toIgnore )
1227 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1231 if ( thickness != _thickness )
1232 _thickness = thickness, NotifySubMeshesHypothesisModification();
1233 } // --------------------------------------------------------------------------------
1234 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1236 if ( _nbLayers != nb )
1237 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1238 } // --------------------------------------------------------------------------------
1239 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1241 if ( _stretchFactor != factor )
1242 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1243 } // --------------------------------------------------------------------------------
1244 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1246 if ( _method != method )
1247 _method = method, NotifySubMeshesHypothesisModification();
1248 } // --------------------------------------------------------------------------------
1249 SMESH_ProxyMesh::Ptr
1250 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1251 const TopoDS_Shape& theShape,
1252 const bool toMakeN2NMap) const
1254 using namespace VISCOUS_3D;
1255 _ViscousBuilder builder;
1256 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1257 if ( err && !err->IsOK() )
1258 return SMESH_ProxyMesh::Ptr();
1260 vector<SMESH_ProxyMesh::Ptr> components;
1261 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1262 for ( ; exp.More(); exp.Next() )
1264 if ( _MeshOfSolid* pm =
1265 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1267 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1268 if ( !builder.MakeN2NMap( pm ))
1269 return SMESH_ProxyMesh::Ptr();
1270 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1271 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1273 if ( pm->_warning && !pm->_warning->IsOK() )
1275 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1276 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1277 if ( !smError || smError->IsOK() )
1278 smError = pm->_warning;
1281 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1283 switch ( components.size() )
1287 case 1: return components[0];
1289 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1291 return SMESH_ProxyMesh::Ptr();
1292 } // --------------------------------------------------------------------------------
1293 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1295 save << " " << _nbLayers
1296 << " " << _thickness
1297 << " " << _stretchFactor
1298 << " " << _shapeIds.size();
1299 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1300 save << " " << _shapeIds[i];
1301 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1302 save << " " << _method;
1304 } // --------------------------------------------------------------------------------
1305 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1307 int nbFaces, faceID, shapeToTreat, method;
1308 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1309 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1310 _shapeIds.push_back( faceID );
1311 if ( load >> shapeToTreat ) {
1312 _isToIgnoreShapes = !shapeToTreat;
1313 if ( load >> method )
1314 _method = (ExtrusionMethod) method;
1317 _isToIgnoreShapes = true; // old behavior
1320 } // --------------------------------------------------------------------------------
1321 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1322 const TopoDS_Shape& theShape)
1326 } // --------------------------------------------------------------------------------
1327 SMESH_ComputeErrorPtr
1328 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1329 const TopoDS_Shape& theShape,
1330 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1332 VISCOUS_3D::_ViscousBuilder builder;
1333 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1334 if ( err && !err->IsOK() )
1335 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1337 theStatus = SMESH_Hypothesis::HYP_OK;
1341 // --------------------------------------------------------------------------------
1342 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1345 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1346 return IsToIgnoreShapes() ? !isIn : isIn;
1348 // END StdMeshers_ViscousLayers hypothesis
1349 //================================================================================
1351 namespace VISCOUS_3D
1353 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1357 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1358 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1359 gp_Pnt p = BRep_Tool::Pnt( fromV );
1360 double distF = p.SquareDistance( c->Value( f ));
1361 double distL = p.SquareDistance( c->Value( l ));
1362 c->D1(( distF < distL ? f : l), p, dir );
1363 if ( distL < distF ) dir.Reverse();
1366 //--------------------------------------------------------------------------------
1367 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1368 SMESH_MesherHelper& helper)
1371 double f,l; gp_Pnt p;
1372 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1373 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1374 double u = helper.GetNodeU( E, atNode );
1378 //--------------------------------------------------------------------------------
1379 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1380 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1382 //--------------------------------------------------------------------------------
1383 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1384 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1387 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1390 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1391 return getFaceDir( F, v, node, helper, ok );
1393 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1394 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1395 gp_Pnt p; gp_Vec du, dv, norm;
1396 surface->D1( uv.X(),uv.Y(), p, du,dv );
1399 double u = helper.GetNodeU( fromE, node, 0, &ok );
1401 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1402 if ( o == TopAbs_REVERSED )
1405 gp_Vec dir = norm ^ du;
1407 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1408 helper.IsClosedEdge( fromE ))
1410 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1411 else c->D1( f, p, dv );
1412 if ( o == TopAbs_REVERSED )
1414 gp_Vec dir2 = norm ^ dv;
1415 dir = dir.Normalized() + dir2.Normalized();
1419 //--------------------------------------------------------------------------------
1420 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1421 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1422 bool& ok, double* cosin)
1424 TopoDS_Face faceFrw = F;
1425 faceFrw.Orientation( TopAbs_FORWARD );
1426 //double f,l; TopLoc_Location loc;
1427 TopoDS_Edge edges[2]; // sharing a vertex
1430 TopoDS_Vertex VV[2];
1431 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1432 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1434 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1435 if ( SMESH_Algo::isDegenerated( e )) continue;
1436 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1437 if ( VV[1].IsSame( fromV )) {
1438 nbEdges += edges[ 0 ].IsNull();
1441 else if ( VV[0].IsSame( fromV )) {
1442 nbEdges += edges[ 1 ].IsNull();
1447 gp_XYZ dir(0,0,0), edgeDir[2];
1450 // get dirs of edges going fromV
1452 for ( size_t i = 0; i < nbEdges && ok; ++i )
1454 edgeDir[i] = getEdgeDir( edges[i], fromV );
1455 double size2 = edgeDir[i].SquareModulus();
1456 if (( ok = size2 > numeric_limits<double>::min() ))
1457 edgeDir[i] /= sqrt( size2 );
1459 if ( !ok ) return dir;
1461 // get angle between the 2 edges
1463 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1464 if ( Abs( angle ) < 5 * M_PI/180 )
1466 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1470 dir = edgeDir[0] + edgeDir[1];
1475 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1476 *cosin = Cos( angle );
1479 else if ( nbEdges == 1 )
1481 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1482 if ( cosin ) *cosin = 1.;
1492 //================================================================================
1494 * \brief Finds concave VERTEXes of a FACE
1496 //================================================================================
1498 bool getConcaveVertices( const TopoDS_Face& F,
1499 SMESH_MesherHelper& helper,
1500 set< TGeomID >* vertices = 0)
1502 // check angles at VERTEXes
1504 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1505 for ( size_t iW = 0; iW < wires.size(); ++iW )
1507 const int nbEdges = wires[iW]->NbEdges();
1508 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1510 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1512 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1513 int iE2 = ( iE1 + 1 ) % nbEdges;
1514 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1515 iE2 = ( iE2 + 1 ) % nbEdges;
1516 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1517 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1518 wires[iW]->Edge( iE2 ), F, V );
1519 if ( angle < -5. * M_PI / 180. )
1523 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1527 return vertices ? !vertices->empty() : false;
1530 //================================================================================
1532 * \brief Returns true if a FACE is bound by a concave EDGE
1534 //================================================================================
1536 bool isConcave( const TopoDS_Face& F,
1537 SMESH_MesherHelper& helper,
1538 set< TGeomID >* vertices = 0 )
1540 bool isConcv = false;
1541 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1543 gp_Vec2d drv1, drv2;
1545 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1546 for ( ; eExp.More(); eExp.Next() )
1548 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1549 if ( SMESH_Algo::isDegenerated( E )) continue;
1550 // check if 2D curve is concave
1551 BRepAdaptor_Curve2d curve( E, F );
1552 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1553 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1554 curve.Intervals( intervals, GeomAbs_C2 );
1555 bool isConvex = true;
1556 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1558 double u1 = intervals( i );
1559 double u2 = intervals( i+1 );
1560 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1561 double cross = drv1 ^ drv2;
1562 if ( E.Orientation() == TopAbs_REVERSED )
1564 isConvex = ( cross > -1e-9 ); // 0.1 );
1568 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1577 // check angles at VERTEXes
1578 if ( getConcaveVertices( F, helper, vertices ))
1584 //================================================================================
1586 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1587 * \param [in] face - the mesh face to treat
1588 * \param [in] nodeOnEdge - a node on the EDGE
1589 * \param [out] faceSize - the computed distance
1590 * \return bool - true if faceSize computed
1592 //================================================================================
1594 bool getDistFromEdge( const SMDS_MeshElement* face,
1595 const SMDS_MeshNode* nodeOnEdge,
1598 faceSize = Precision::Infinite();
1601 int nbN = face->NbCornerNodes();
1602 int iOnE = face->GetNodeIndex( nodeOnEdge );
1603 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1604 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1605 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1606 face->GetNode( iNext[1] ) };
1607 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1608 double segLen = -1.;
1609 // look for two neighbor not in-FACE nodes of face
1610 for ( int i = 0; i < 2; ++i )
1612 if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1613 ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1615 // look for an in-FACE node
1616 for ( int iN = 0; iN < nbN; ++iN )
1618 if ( iN == iOnE || iN == iNext[i] )
1620 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1621 gp_XYZ v = pInFace - segEnd;
1624 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1625 segLen = segVec.Modulus();
1627 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1628 faceSize = Min( faceSize, distToSeg );
1636 //================================================================================
1638 * \brief Return direction of axis or revolution of a surface
1640 //================================================================================
1642 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1645 switch ( surface.GetType() ) {
1648 gp_Cone cone = surface.Cone();
1649 axis = cone.Axis().Direction();
1652 case GeomAbs_Sphere:
1654 gp_Sphere sphere = surface.Sphere();
1655 axis = sphere.Position().Direction();
1658 case GeomAbs_SurfaceOfRevolution:
1660 axis = surface.AxeOfRevolution().Direction();
1663 //case GeomAbs_SurfaceOfExtrusion:
1664 case GeomAbs_OffsetSurface:
1666 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1667 return getRovolutionAxis( base->Surface(), axis );
1669 default: return false;
1674 //--------------------------------------------------------------------------------
1675 // DEBUG. Dump intermediate node positions into a python script
1676 // HOWTO use: run python commands written in a console to see
1677 // construction steps of viscous layers
1683 PyDump(SMESH_Mesh& m) {
1684 int tag = 3 + m.GetId();
1685 const char* fname = "/tmp/viscous.py";
1686 cout << "execfile('"<<fname<<"')"<<endl;
1687 py = _pyStream = new ofstream(fname);
1688 *py << "import SMESH" << endl
1689 << "from salome.smesh import smeshBuilder" << endl
1690 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1691 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1692 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1697 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1698 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1699 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1700 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1704 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1705 struct MyStream : public ostream
1707 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1709 void Pause() { py = &_mystream; }
1710 void Resume() { py = _pyStream; }
1714 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1715 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1716 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1717 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1718 void _dumpFunction(const string& fun, int ln)
1719 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1720 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1721 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1722 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1723 void _dumpCmd(const string& txt, int ln)
1724 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1725 void dumpFunctionEnd()
1726 { if (py) *py<< " return"<< endl; }
1727 void dumpChangeNodes( const SMDS_MeshElement* f )
1728 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1729 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1730 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1731 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1735 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1736 #define dumpFunction(f) f
1738 #define dumpMoveComm(n,txt)
1739 #define dumpCmd(txt)
1740 #define dumpFunctionEnd()
1741 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1742 #define debugMsg( txt ) {}
1747 using namespace VISCOUS_3D;
1749 //================================================================================
1751 * \brief Constructor of _ViscousBuilder
1753 //================================================================================
1755 _ViscousBuilder::_ViscousBuilder()
1757 _error = SMESH_ComputeError::New(COMPERR_OK);
1761 //================================================================================
1763 * \brief Stores error description and returns false
1765 //================================================================================
1767 bool _ViscousBuilder::error(const string& text, int solidId )
1769 const string prefix = string("Viscous layers builder: ");
1770 _error->myName = COMPERR_ALGO_FAILED;
1771 _error->myComment = prefix + text;
1774 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1775 if ( !sm && !_sdVec.empty() )
1776 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1777 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1779 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1780 if ( smError && smError->myAlgo )
1781 _error->myAlgo = smError->myAlgo;
1783 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1785 // set KO to all solids
1786 for ( size_t i = 0; i < _sdVec.size(); ++i )
1788 if ( _sdVec[i]._index == solidId )
1790 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1791 if ( !sm->IsEmpty() )
1793 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1794 if ( !smError || smError->IsOK() )
1796 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1797 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1801 makeGroupOfLE(); // debug
1806 //================================================================================
1808 * \brief At study restoration, restore event listeners used to clear an inferior
1809 * dim sub-mesh modified by viscous layers
1811 //================================================================================
1813 void _ViscousBuilder::RestoreListeners()
1818 //================================================================================
1820 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1822 //================================================================================
1824 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1826 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1827 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1828 for ( ; fExp.More(); fExp.Next() )
1830 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1831 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1833 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1835 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1838 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1839 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1841 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1842 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1843 while( prxIt->more() )
1845 const SMDS_MeshElement* fSrc = srcIt->next();
1846 const SMDS_MeshElement* fPrx = prxIt->next();
1847 if ( fSrc->NbNodes() != fPrx->NbNodes())
1848 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1849 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1850 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1853 pm->_n2nMapComputed = true;
1857 //================================================================================
1859 * \brief Does its job
1861 //================================================================================
1863 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1864 const TopoDS_Shape& theShape)
1868 // check if proxy mesh already computed
1869 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1871 return error("No SOLID's in theShape"), _error;
1873 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1874 return SMESH_ComputeErrorPtr(); // everything already computed
1876 PyDump debugDump( theMesh );
1877 _pyDump = &debugDump;
1879 // TODO: ignore already computed SOLIDs
1880 if ( !findSolidsWithLayers())
1883 if ( !findFacesWithLayers() )
1886 for ( size_t i = 0; i < _sdVec.size(); ++i )
1889 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1890 if ( _sdVec[iSD]._before.IsEmpty() &&
1891 !_sdVec[iSD]._solid.IsNull() &&
1892 _sdVec[iSD]._n2eMap.empty() )
1895 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1898 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1900 _sdVec[iSD]._solid.Nullify();
1904 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
1907 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
1910 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
1913 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1915 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1916 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1917 _sdVec[iSD]._before.Remove( solid );
1920 makeGroupOfLE(); // debug
1926 //================================================================================
1928 * \brief Check validity of hypotheses
1930 //================================================================================
1932 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1933 const TopoDS_Shape& shape )
1937 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1938 return SMESH_ComputeErrorPtr(); // everything already computed
1941 findSolidsWithLayers();
1942 bool ok = findFacesWithLayers( true );
1944 // remove _MeshOfSolid's of _SolidData's
1945 for ( size_t i = 0; i < _sdVec.size(); ++i )
1946 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1951 return SMESH_ComputeErrorPtr();
1954 //================================================================================
1956 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1958 //================================================================================
1960 bool _ViscousBuilder::findSolidsWithLayers()
1963 TopTools_IndexedMapOfShape allSolids;
1964 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1965 _sdVec.reserve( allSolids.Extent());
1967 SMESH_HypoFilter filter;
1968 for ( int i = 1; i <= allSolids.Extent(); ++i )
1970 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1971 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1972 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1973 continue; // solid is already meshed
1974 SMESH_Algo* algo = sm->GetAlgo();
1975 if ( !algo ) continue;
1976 // TODO: check if algo is hidden
1977 const list <const SMESHDS_Hypothesis *> & allHyps =
1978 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1979 _SolidData* soData = 0;
1980 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1981 const StdMeshers_ViscousLayers* viscHyp = 0;
1982 for ( ; hyp != allHyps.end(); ++hyp )
1983 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1985 TopoDS_Shape hypShape;
1986 filter.Init( filter.Is( viscHyp ));
1987 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1991 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1994 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1995 soData = & _sdVec.back();
1996 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1997 soData->_helper = new SMESH_MesherHelper( *_mesh );
1998 soData->_helper->SetSubShape( allSolids(i) );
1999 _solids.Add( allSolids(i) );
2001 soData->_hyps.push_back( viscHyp );
2002 soData->_hypShapes.push_back( hypShape );
2005 if ( _sdVec.empty() )
2007 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2012 //================================================================================
2014 * \brief Set a _SolidData to be computed before another
2016 //================================================================================
2018 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2020 // check possibility to set this order; get all solids before solidBefore
2021 TopTools_IndexedMapOfShape allSolidsBefore;
2022 allSolidsBefore.Add( solidBefore._solid );
2023 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2025 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2028 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2029 for ( ; soIt.More(); soIt.Next() )
2030 allSolidsBefore.Add( soIt.Value() );
2033 if ( allSolidsBefore.Contains( solidAfter._solid ))
2036 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2037 solidAfter._before.Add( allSolidsBefore(i) );
2042 //================================================================================
2046 //================================================================================
2048 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2050 SMESH_MesherHelper helper( *_mesh );
2051 TopExp_Explorer exp;
2053 // collect all faces-to-ignore defined by hyp
2054 for ( size_t i = 0; i < _sdVec.size(); ++i )
2056 // get faces-to-ignore defined by each hyp
2057 typedef const StdMeshers_ViscousLayers* THyp;
2058 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2059 list< TFacesOfHyp > ignoreFacesOfHyps;
2060 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2061 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2062 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2064 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2065 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2068 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2069 const int nbHyps = _sdVec[i]._hyps.size();
2072 // check if two hypotheses define different parameters for the same FACE
2073 list< TFacesOfHyp >::iterator igFacesOfHyp;
2074 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2076 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2078 igFacesOfHyp = ignoreFacesOfHyps.begin();
2079 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2080 if ( ! igFacesOfHyp->first.count( faceID ))
2083 return error(SMESH_Comment("Several hypotheses define "
2084 "Viscous Layers on the face #") << faceID );
2085 hyp = igFacesOfHyp->second;
2088 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2090 _sdVec[i]._ignoreFaceIds.insert( faceID );
2093 // check if two hypotheses define different number of viscous layers for
2094 // adjacent faces of a solid
2095 set< int > nbLayersSet;
2096 igFacesOfHyp = ignoreFacesOfHyps.begin();
2097 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2099 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2101 if ( nbLayersSet.size() > 1 )
2103 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2105 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2106 THyp hyp1 = 0, hyp2 = 0;
2107 while( const TopoDS_Shape* face = fIt->next() )
2109 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2110 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2111 if ( f2h != _sdVec[i]._face2hyp.end() )
2113 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2116 if ( hyp1 && hyp2 &&
2117 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2119 return error("Two hypotheses define different number of "
2120 "viscous layers on adjacent faces");
2124 } // if ( nbHyps > 1 )
2127 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2131 if ( onlyWith ) // is called to check hypotheses compatibility only
2134 // fill _SolidData::_reversedFaceIds
2135 for ( size_t i = 0; i < _sdVec.size(); ++i )
2137 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2138 for ( ; exp.More(); exp.Next() )
2140 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2141 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2142 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2143 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2144 helper.IsReversedSubMesh( face ))
2146 _sdVec[i]._reversedFaceIds.insert( faceID );
2151 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2152 TopTools_IndexedMapOfShape shapes;
2153 std::string structAlgoName = "Hexa_3D";
2154 for ( size_t i = 0; i < _sdVec.size(); ++i )
2157 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2158 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2160 const TopoDS_Shape& edge = shapes(iE);
2161 // find 2 FACEs sharing an EDGE
2163 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2164 while ( fIt->more())
2166 const TopoDS_Shape* f = fIt->next();
2167 FF[ int( !FF[0].IsNull()) ] = *f;
2169 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2171 // check presence of layers on them
2173 for ( int j = 0; j < 2; ++j )
2174 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2175 if ( ignore[0] == ignore[1] )
2176 continue; // nothing interesting
2177 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2180 if ( !fWOL.IsNull())
2182 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2183 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2188 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2190 for ( size_t i = 0; i < _sdVec.size(); ++i )
2193 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2194 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2196 const TopoDS_Shape& vertex = shapes(iV);
2197 // find faces WOL sharing the vertex
2198 vector< TopoDS_Shape > facesWOL;
2199 size_t totalNbFaces = 0;
2200 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2201 while ( fIt->more())
2203 const TopoDS_Shape* f = fIt->next();
2205 const int fID = getMeshDS()->ShapeToIndex( *f );
2206 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2207 facesWOL.push_back( *f );
2209 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2210 continue; // no layers at this vertex or no WOL
2211 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2212 switch ( facesWOL.size() )
2216 helper.SetSubShape( facesWOL[0] );
2217 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2219 TopoDS_Shape seamEdge;
2220 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2221 while ( eIt->more() && seamEdge.IsNull() )
2223 const TopoDS_Shape* e = eIt->next();
2224 if ( helper.IsRealSeam( *e ) )
2227 if ( !seamEdge.IsNull() )
2229 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2233 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2238 // find an edge shared by 2 faces
2239 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2240 while ( eIt->more())
2242 const TopoDS_Shape* e = eIt->next();
2243 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2244 helper.IsSubShape( *e, facesWOL[1]))
2246 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2252 return error("Not yet supported case", _sdVec[i]._index);
2257 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2258 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2259 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2260 for ( size_t i = 0; i < _sdVec.size(); ++i )
2262 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2263 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2265 const TopoDS_Shape& fWOL = e2f->second;
2266 const TGeomID edgeID = e2f->first;
2267 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2268 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2269 if ( edge.ShapeType() != TopAbs_EDGE )
2270 continue; // shrink shape is VERTEX
2273 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2274 while ( soIt->more() && solid.IsNull() )
2276 const TopoDS_Shape* so = soIt->next();
2277 if ( !so->IsSame( _sdVec[i]._solid ))
2280 if ( solid.IsNull() )
2283 bool noShrinkE = false;
2284 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2285 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2286 size_t iSolid = _solids.FindIndex( solid ) - 1;
2287 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2289 // the adjacent SOLID has NO layers on fWOL;
2290 // shrink allowed if
2291 // - there are layers on the EDGE in the adjacent SOLID
2292 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2293 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2294 bool shrinkAllowed = (( hasWLAdj ) ||
2295 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2296 noShrinkE = !shrinkAllowed;
2298 else if ( iSolid < _sdVec.size() )
2300 // the adjacent SOLID has layers on fWOL;
2301 // check if SOLID's mesh is unstructured and then try to set it
2302 // to be computed after the i-th solid
2303 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2304 noShrinkE = true; // don't shrink fWOL
2308 // the adjacent SOLID has NO layers at all
2309 noShrinkE = isStructured;
2314 _sdVec[i]._noShrinkShapes.insert( edgeID );
2316 // check if there is a collision with to-shrink-from EDGEs in iSolid
2317 // if ( iSolid < _sdVec.size() )
2320 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2321 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2323 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2324 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2325 // if ( eID == edgeID ||
2326 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2327 // _sdVec[i]._noShrinkShapes.count( eID ))
2329 // for ( int is1st = 0; is1st < 2; ++is1st )
2331 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2332 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2334 // return error("No way to make a conformal mesh with "
2335 // "the given set of faces with layers", _sdVec[i]._index);
2342 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2343 // _shrinkShape2Shape is different in the adjacent SOLID
2344 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2346 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2347 bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2349 if ( iSolid < _sdVec.size() )
2351 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2353 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2354 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2355 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2356 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2357 noShrinkV = (( isStructured ) ||
2358 ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2360 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2364 noShrinkV = noShrinkE;
2369 // the adjacent SOLID has NO layers at all
2376 noShrinkV = noShrinkIfAdjMeshed =
2377 ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2381 if ( noShrinkV && noShrinkIfAdjMeshed )
2383 // noShrinkV if FACEs in the adjacent SOLID are meshed
2384 PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2385 *_mesh, TopAbs_FACE, &solid );
2386 while ( fIt->more() )
2388 const TopoDS_Shape* f = fIt->next();
2389 if ( !f->IsSame( fWOL ))
2391 noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2397 _sdVec[i]._noShrinkShapes.insert( vID );
2400 } // loop on _sdVec[i]._shrinkShape2Shape
2401 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2404 // add FACEs of other SOLIDs to _ignoreFaceIds
2405 for ( size_t i = 0; i < _sdVec.size(); ++i )
2408 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2410 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2412 if ( !shapes.Contains( exp.Current() ))
2413 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2420 //================================================================================
2422 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2424 //================================================================================
2426 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2427 const StdMeshers_ViscousLayers* hyp,
2428 const TopoDS_Shape& hypShape,
2429 set<TGeomID>& ignoreFaceIds)
2431 TopExp_Explorer exp;
2433 vector<TGeomID> ids = hyp->GetBndShapes();
2434 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2436 for ( size_t ii = 0; ii < ids.size(); ++ii )
2438 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2439 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2440 ignoreFaceIds.insert( ids[ii] );
2443 else // FACEs with layers are given
2445 exp.Init( solid, TopAbs_FACE );
2446 for ( ; exp.More(); exp.Next() )
2448 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2449 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2450 ignoreFaceIds.insert( faceInd );
2454 // ignore internal FACEs if inlets and outlets are specified
2455 if ( hyp->IsToIgnoreShapes() )
2457 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2458 TopExp::MapShapesAndAncestors( hypShape,
2459 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2461 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2463 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2464 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2467 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2469 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2474 //================================================================================
2476 * \brief Create the inner surface of the viscous layer and prepare data for infation
2478 //================================================================================
2480 bool _ViscousBuilder::makeLayer(_SolidData& data)
2482 // get all sub-shapes to make layers on
2483 set<TGeomID> subIds, faceIds;
2484 subIds = data._noShrinkShapes;
2485 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2486 for ( ; exp.More(); exp.Next() )
2488 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2489 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2490 faceIds.insert( fSubM->GetId() );
2493 // make a map to find new nodes on sub-shapes shared with other SOLID
2494 map< TGeomID, TNode2Edge* >::iterator s2ne;
2495 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2496 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2498 TGeomID shapeInd = s2s->first;
2499 for ( size_t i = 0; i < _sdVec.size(); ++i )
2501 if ( _sdVec[i]._index == data._index ) continue;
2502 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2503 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2504 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2506 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2512 // Create temporary faces and _LayerEdge's
2514 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2516 data._stepSize = Precision::Infinite();
2517 data._stepSizeNodes[0] = 0;
2519 SMESH_MesherHelper helper( *_mesh );
2520 helper.SetSubShape( data._solid );
2521 helper.SetElementsOnShape( true );
2523 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2524 TNode2Edge::iterator n2e2;
2526 // collect _LayerEdge's of shapes they are based on
2527 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2528 const int nbShapes = getMeshDS()->MaxShapeIndex();
2529 edgesByGeom.resize( nbShapes+1 );
2531 // set data of _EdgesOnShape's
2532 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2534 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2535 while ( smIt->more() )
2538 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2539 !faceIds.count( sm->GetId() ))
2541 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2544 // make _LayerEdge's
2545 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2547 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2548 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2549 SMESH_ProxyMesh::SubMesh* proxySub =
2550 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2552 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2553 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2555 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2556 while ( eIt->more() )
2558 const SMDS_MeshElement* face = eIt->next();
2559 double faceMaxCosin = -1;
2560 _LayerEdge* maxCosinEdge = 0;
2561 int nbDegenNodes = 0;
2563 newNodes.resize( face->NbCornerNodes() );
2564 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2566 const SMDS_MeshNode* n = face->GetNode( i );
2567 const int shapeID = n->getshapeId();
2568 const bool onDegenShap = helper.IsDegenShape( shapeID );
2569 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2574 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2575 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2576 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2577 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2587 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2588 if ( !(*n2e).second )
2591 _LayerEdge* edge = new _LayerEdge();
2592 edge->_nodes.push_back( n );
2594 edgesByGeom[ shapeID ]._edges.push_back( edge );
2595 const bool noShrink = data._noShrinkShapes.count( shapeID );
2597 SMESH_TNodeXYZ xyz( n );
2599 // set edge data or find already refined _LayerEdge and get data from it
2600 if (( !noShrink ) &&
2601 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2602 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2603 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2605 _LayerEdge* foundEdge = (*n2e2).second;
2606 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2607 foundEdge->_pos.push_back( lastPos );
2608 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2609 const_cast< SMDS_MeshNode* >
2610 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2616 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2618 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2621 if ( edge->_nodes.size() < 2 )
2622 edge->Block( data );
2623 //data._noShrinkShapes.insert( shapeID );
2625 dumpMove(edge->_nodes.back());
2627 if ( edge->_cosin > faceMaxCosin )
2629 faceMaxCosin = edge->_cosin;
2630 maxCosinEdge = edge;
2633 newNodes[ i ] = n2e->second->_nodes.back();
2636 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2638 if ( newNodes.size() - nbDegenNodes < 2 )
2641 // create a temporary face
2642 const SMDS_MeshElement* newFace =
2643 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2644 proxySub->AddElement( newFace );
2646 // compute inflation step size by min size of element on a convex surface
2647 if ( faceMaxCosin > theMinSmoothCosin )
2648 limitStepSize( data, face, maxCosinEdge );
2650 } // loop on 2D elements on a FACE
2651 } // loop on FACEs of a SOLID to create _LayerEdge's
2654 // Set _LayerEdge::_neibors
2655 TNode2Edge::iterator n2e;
2656 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2658 _EdgesOnShape& eos = data._edgesOnShape[iS];
2659 for ( size_t i = 0; i < eos._edges.size(); ++i )
2661 _LayerEdge* edge = eos._edges[i];
2662 TIDSortedNodeSet nearNodes;
2663 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2664 while ( fIt->more() )
2666 const SMDS_MeshElement* f = fIt->next();
2667 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2668 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2670 nearNodes.erase( edge->_nodes[0] );
2671 edge->_neibors.reserve( nearNodes.size() );
2672 TIDSortedNodeSet::iterator node = nearNodes.begin();
2673 for ( ; node != nearNodes.end(); ++node )
2674 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2675 edge->_neibors.push_back( n2e->second );
2679 data._epsilon = 1e-7;
2680 if ( data._stepSize < 1. )
2681 data._epsilon *= data._stepSize;
2683 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2686 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2687 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2689 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2690 const SMDS_MeshNode* nn[2];
2691 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2693 _EdgesOnShape& eos = data._edgesOnShape[iS];
2694 for ( size_t i = 0; i < eos._edges.size(); ++i )
2696 _LayerEdge* edge = eos._edges[i];
2697 if ( edge->IsOnEdge() )
2699 // get neighbor nodes
2700 bool hasData = ( edge->_2neibors->_edges[0] );
2701 if ( hasData ) // _LayerEdge is a copy of another one
2703 nn[0] = edge->_2neibors->srcNode(0);
2704 nn[1] = edge->_2neibors->srcNode(1);
2706 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2710 // set neighbor _LayerEdge's
2711 for ( int j = 0; j < 2; ++j )
2713 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2714 return error("_LayerEdge not found by src node", data._index);
2715 edge->_2neibors->_edges[j] = n2e->second;
2718 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2721 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2723 _Simplex& s = edge->_simplices[j];
2724 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2725 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2728 // For an _LayerEdge on a degenerated EDGE, copy some data from
2729 // a corresponding _LayerEdge on a VERTEX
2730 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2731 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2733 // Generally we should not get here
2734 if ( eos.ShapeType() != TopAbs_EDGE )
2736 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2737 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2738 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2740 const _LayerEdge* vEdge = n2e->second;
2741 edge->_normal = vEdge->_normal;
2742 edge->_lenFactor = vEdge->_lenFactor;
2743 edge->_cosin = vEdge->_cosin;
2746 } // loop on data._edgesOnShape._edges
2747 } // loop on data._edgesOnShape
2749 // fix _LayerEdge::_2neibors on EDGEs to smooth
2750 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2751 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2752 // if ( !e2c->second.IsNull() )
2754 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2755 // data.Sort2NeiborsOnEdge( eos->_edges );
2762 //================================================================================
2764 * \brief Compute inflation step size by min size of element on a convex surface
2766 //================================================================================
2768 void _ViscousBuilder::limitStepSize( _SolidData& data,
2769 const SMDS_MeshElement* face,
2770 const _LayerEdge* maxCosinEdge )
2773 double minSize = 10 * data._stepSize;
2774 const int nbNodes = face->NbCornerNodes();
2775 for ( int i = 0; i < nbNodes; ++i )
2777 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2778 const SMDS_MeshNode* curN = face->GetNode( i );
2779 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2780 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2782 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2783 if ( dist < minSize )
2784 minSize = dist, iN = i;
2787 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2788 if ( newStep < data._stepSize )
2790 data._stepSize = newStep;
2791 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2792 data._stepSizeNodes[0] = face->GetNode( iN );
2793 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2797 //================================================================================
2799 * \brief Compute inflation step size by min size of element on a convex surface
2801 //================================================================================
2803 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2805 if ( minSize < data._stepSize )
2807 data._stepSize = minSize;
2808 if ( data._stepSizeNodes[0] )
2811 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2812 data._stepSizeCoeff = data._stepSize / dist;
2817 //================================================================================
2819 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2821 //================================================================================
2823 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2825 SMESH_MesherHelper helper( *_mesh );
2827 BRepLProp_SLProps surfProp( 2, 1e-6 );
2828 data._convexFaces.clear();
2830 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2832 _EdgesOnShape& eof = data._edgesOnShape[iS];
2833 if ( eof.ShapeType() != TopAbs_FACE ||
2834 data._ignoreFaceIds.count( eof._shapeID ))
2837 TopoDS_Face F = TopoDS::Face( eof._shape );
2838 const TGeomID faceID = eof._shapeID;
2840 BRepAdaptor_Surface surface( F, false );
2841 surfProp.SetSurface( surface );
2843 _ConvexFace cnvFace;
2845 cnvFace._normalsFixed = false;
2846 cnvFace._isTooCurved = false;
2848 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2849 if ( maxCurvature > 0 )
2851 limitStepSize( data, 0.9 / maxCurvature );
2852 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2854 if ( !cnvFace._isTooCurved ) continue;
2856 _ConvexFace & convFace =
2857 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2859 // skip a closed surface (data._convexFaces is useful anyway)
2860 bool isClosedF = false;
2861 helper.SetSubShape( F );
2862 if ( helper.HasRealSeam() )
2864 // in the closed surface there must be a closed EDGE
2865 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2866 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2870 // limit _LayerEdge::_maxLen on the FACE
2871 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2872 const double minCurvature =
2873 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2874 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2875 if ( id2eos != cnvFace._subIdToEOS.end() )
2877 _EdgesOnShape& eos = * id2eos->second;
2878 for ( size_t i = 0; i < eos._edges.size(); ++i )
2880 _LayerEdge* ledge = eos._edges[ i ];
2881 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2882 surfProp.SetParameters( uv.X(), uv.Y() );
2883 if ( surfProp.IsCurvatureDefined() )
2885 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2886 surfProp.MinCurvature() * oriFactor );
2887 if ( curvature > minCurvature )
2888 ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2895 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2896 // prism distortion.
2897 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2898 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2900 // there are _LayerEdge's on the FACE it-self;
2901 // select _LayerEdge's near EDGEs
2902 _EdgesOnShape& eos = * id2eos->second;
2903 for ( size_t i = 0; i < eos._edges.size(); ++i )
2905 _LayerEdge* ledge = eos._edges[ i ];
2906 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2907 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2909 // do not select _LayerEdge's neighboring sharp EDGEs
2910 bool sharpNbr = false;
2911 for ( size_t iN = 0; iN < ledge->_neibors.size() && !sharpNbr; ++iN )
2912 sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2914 convFace._simplexTestEdges.push_back( ledge );
2921 // where there are no _LayerEdge's on a _ConvexFace,
2922 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2923 // so that collision of viscous internal faces is not detected by check of
2924 // intersection of _LayerEdge's with the viscous internal faces.
2926 set< const SMDS_MeshNode* > usedNodes;
2928 // look for _LayerEdge's with null _sWOL
2929 id2eos = convFace._subIdToEOS.begin();
2930 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2932 _EdgesOnShape& eos = * id2eos->second;
2933 if ( !eos._sWOL.IsNull() )
2935 for ( size_t i = 0; i < eos._edges.size(); ++i )
2937 _LayerEdge* ledge = eos._edges[ i ];
2938 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2939 if ( !usedNodes.insert( srcNode ).second ) continue;
2941 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2943 usedNodes.insert( ledge->_simplices[i]._nPrev );
2944 usedNodes.insert( ledge->_simplices[i]._nNext );
2946 convFace._simplexTestEdges.push_back( ledge );
2950 } // loop on FACEs of data._solid
2953 //================================================================================
2955 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2957 //================================================================================
2959 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2961 // define allowed thickness
2962 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2965 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2966 // boundary inclined to the shape at a sharp angle
2968 TopTools_MapOfShape edgesOfSmooFaces;
2969 SMESH_MesherHelper helper( *_mesh );
2972 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2973 data._nbShapesToSmooth = 0;
2975 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2977 _EdgesOnShape& eos = edgesByGeom[iS];
2978 eos._toSmooth = false;
2979 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2982 double tgtThick = eos._hyp.GetTotalThickness();
2983 SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
2984 while ( subIt->more() && !eos._toSmooth )
2986 TGeomID iSub = subIt->next()->GetId();
2987 const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
2988 if ( eSub.empty() ) continue;
2991 for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
2992 if ( eSub[i]->_cosin > theMinSmoothCosin )
2994 SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2995 while ( fIt->more() && !eos._toSmooth )
2997 const SMDS_MeshElement* face = fIt->next();
2998 if ( face->getshapeId() == eos._shapeID &&
2999 getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3001 eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3002 tgtThick * eSub[i]->_lenFactor,
3008 if ( eos._toSmooth )
3010 for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3011 edgesOfSmooFaces.Add( eExp.Current() );
3013 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3015 data._nbShapesToSmooth += eos._toSmooth;
3019 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3021 _EdgesOnShape& eos = edgesByGeom[iS];
3022 eos._edgeSmoother = NULL;
3023 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3024 if ( !eos._hyp.ToSmooth() ) continue;
3026 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3027 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3030 double tgtThick = eos._hyp.GetTotalThickness();
3031 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3033 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3034 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3035 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3036 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3037 double angle = eDir.Angle( eV[0]->_normal );
3038 double cosin = Cos( angle );
3039 double cosinAbs = Abs( cosin );
3040 if ( cosinAbs > theMinSmoothCosin )
3042 // always smooth analytic EDGEs
3043 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3044 eos._toSmooth = ! curve.IsNull();
3046 // compare tgtThick with the length of an end segment
3047 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3048 while ( eIt->more() && !eos._toSmooth )
3050 const SMDS_MeshElement* endSeg = eIt->next();
3051 if ( endSeg->getshapeId() == (int) iS )
3054 SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3055 eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3058 if ( eos._toSmooth )
3060 eos._edgeSmoother = new _Smoother1D( curve, eos );
3062 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3063 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3067 data._nbShapesToSmooth += eos._toSmooth;
3071 // Reset _cosin if no smooth is allowed by the user
3072 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3074 _EdgesOnShape& eos = edgesByGeom[iS];
3075 if ( eos._edges.empty() ) continue;
3077 if ( !eos._hyp.ToSmooth() )
3078 for ( size_t i = 0; i < eos._edges.size(); ++i )
3079 //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3080 eos._edges[i]->_lenFactor = 1;
3084 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3086 TopTools_MapOfShape c1VV;
3088 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3090 _EdgesOnShape& eos = edgesByGeom[iS];
3091 if ( eos._edges.empty() ||
3092 eos.ShapeType() != TopAbs_FACE ||
3096 // check EDGEs of a FACE
3097 TopTools_MapOfShape checkedEE, allVV;
3098 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3099 while ( !smQueue.empty() )
3101 SMESH_subMesh* sm = smQueue.front();
3102 smQueue.pop_front();
3103 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3104 while ( smIt->more() )
3107 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3108 allVV.Add( sm->GetSubShape() );
3109 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3110 !checkedEE.Add( sm->GetSubShape() ))
3113 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3114 vector<_LayerEdge*>& eE = eoe->_edges;
3115 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3118 bool isC1 = true; // check continuity along an EDGE
3119 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3120 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3124 // check that mesh faces are C1 as well
3126 gp_XYZ norm1, norm2;
3127 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3128 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3129 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3131 while ( fIt->more() && isC1 )
3132 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3133 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3138 // add the EDGE and an adjacent FACE to _eosC1
3139 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3140 while ( const TopoDS_Shape* face = fIt->next() )
3142 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3143 if ( !eof ) continue; // other solid
3144 if ( eos._shapeID == eof->_shapeID ) continue;
3145 if ( !eos.HasC1( eof ))
3148 eos._eosC1.push_back( eof );
3149 eof->_toSmooth = false;
3150 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3151 smQueue.push_back( eof->_subMesh );
3153 if ( !eos.HasC1( eoe ))
3155 eos._eosC1.push_back( eoe );
3156 eoe->_toSmooth = false;
3157 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3162 if ( eos._eosC1.empty() )
3165 // check VERTEXes of C1 FACEs
3166 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3167 for ( ; vIt.More(); vIt.Next() )
3169 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3170 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3173 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3174 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3175 while ( const TopoDS_Shape* face = fIt->next() )
3177 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3178 if ( !eof ) continue; // other solid
3179 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3185 eos._eosC1.push_back( eov );
3186 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3187 c1VV.Add( eov->_shape );
3191 } // fill _eosC1 of FACEs
3196 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3198 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3200 _EdgesOnShape& eov = edgesByGeom[iS];
3201 if ( eov._edges.empty() ||
3202 eov.ShapeType() != TopAbs_VERTEX ||
3203 c1VV.Contains( eov._shape ))
3205 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3207 // get directions of surrounding EDGEs
3209 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3210 while ( const TopoDS_Shape* e = fIt->next() )
3212 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3213 if ( !eoe ) continue; // other solid
3214 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3215 if ( !Precision::IsInfinite( eDir.X() ))
3216 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3219 // find EDGEs with C1 directions
3220 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3221 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3222 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3224 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3225 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3228 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3229 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3230 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3231 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3232 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3233 dirOfEdges[i].first = 0;
3234 dirOfEdges[j].first = 0;
3237 } // fill _eosC1 of VERTEXes
3244 //================================================================================
3246 * \brief initialize data of _EdgesOnShape
3248 //================================================================================
3250 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3254 if ( !eos._shape.IsNull() ||
3255 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3258 SMESH_MesherHelper helper( *_mesh );
3261 eos._shapeID = sm->GetId();
3262 eos._shape = sm->GetSubShape();
3263 if ( eos.ShapeType() == TopAbs_FACE )
3264 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3265 eos._toSmooth = false;
3269 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3270 data._shrinkShape2Shape.find( eos._shapeID );
3271 if ( s2s != data._shrinkShape2Shape.end() )
3272 eos._sWOL = s2s->second;
3274 eos._isRegularSWOL = true;
3275 if ( eos.SWOLType() == TopAbs_FACE )
3277 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3278 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3279 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3283 if ( data._hyps.size() == 1 )
3285 eos._hyp = data._hyps.back();
3289 // compute average StdMeshers_ViscousLayers parameters
3290 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3291 if ( eos.ShapeType() == TopAbs_FACE )
3293 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3294 eos._hyp = f2hyp->second;
3298 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3299 while ( const TopoDS_Shape* face = fIt->next() )
3301 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3302 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3303 eos._hyp.Add( f2hyp->second );
3309 if ( ! eos._hyp.UseSurfaceNormal() )
3311 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3313 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3314 if ( !smDS ) return;
3315 eos._faceNormals.resize( smDS->NbElements() );
3317 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3318 for ( int iF = 0; eIt->more(); ++iF )
3320 const SMDS_MeshElement* face = eIt->next();
3321 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3322 eos._faceNormals[iF].SetCoord( 0,0,0 );
3325 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3326 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3327 eos._faceNormals[iF].Reverse();
3329 else // find EOS of adjacent FACEs
3331 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3332 while ( const TopoDS_Shape* face = fIt->next() )
3334 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3335 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3336 if ( eos._faceEOS.back()->_shape.IsNull() )
3337 // avoid using uninitialised _shapeID in GetNormal()
3338 eos._faceEOS.back()->_shapeID = faceID;
3344 //================================================================================
3346 * \brief Returns normal of a face
3348 //================================================================================
3350 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3353 const _EdgesOnShape* eos = 0;
3355 if ( face->getshapeId() == _shapeID )
3361 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3362 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3363 eos = _faceEOS[ iF ];
3367 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3369 norm = eos->_faceNormals[ face->getIdInShape() ];
3373 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3374 << " on _shape #" << _shapeID );
3380 //================================================================================
3382 * \brief Set data of _LayerEdge needed for smoothing
3384 //================================================================================
3386 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3388 SMESH_MesherHelper& helper,
3391 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3394 edge._maxLen = Precision::Infinite();
3397 edge._curvature = 0;
3400 // --------------------------
3401 // Compute _normal and _cosin
3402 // --------------------------
3405 edge._lenFactor = 1.;
3406 edge._normal.SetCoord(0,0,0);
3407 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3409 int totalNbFaces = 0;
3411 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3415 const bool onShrinkShape = !eos._sWOL.IsNull();
3416 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3417 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3419 // get geom FACEs the node lies on
3420 //if ( useGeometry )
3422 set<TGeomID> faceIds;
3423 if ( eos.ShapeType() == TopAbs_FACE )
3425 faceIds.insert( eos._shapeID );
3429 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3430 while ( fIt->more() )
3431 faceIds.insert( fIt->next()->getshapeId() );
3433 set<TGeomID>::iterator id = faceIds.begin();
3434 for ( ; id != faceIds.end(); ++id )
3436 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3437 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3439 F = TopoDS::Face( s );
3440 face2Norm[ totalNbFaces ].first = F;
3446 bool fromVonF = false;
3449 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3450 eos.SWOLType() == TopAbs_FACE &&
3453 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3455 if ( eos.SWOLType() == TopAbs_EDGE )
3457 // inflate from VERTEX along EDGE
3458 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3460 else if ( eos.ShapeType() == TopAbs_VERTEX )
3462 // inflate from VERTEX along FACE
3463 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3464 node, helper, normOK, &edge._cosin);
3468 // inflate from EDGE along FACE
3469 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3470 node, helper, normOK);
3473 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3476 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3479 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3481 F = face2Norm[ iF ].first;
3482 geomNorm = getFaceNormal( node, F, helper, normOK );
3483 if ( !normOK ) continue;
3486 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3488 face2Norm[ iF ].second = geomNorm.XYZ();
3489 edge._normal += geomNorm.XYZ();
3491 if ( nbOkNorms == 0 )
3492 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3494 if ( totalNbFaces >= 3 )
3496 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3499 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3501 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3502 edge._normal.SetCoord( 0,0,0 );
3503 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3505 const TopoDS_Face& F = face2Norm[iF].first;
3506 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3507 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3510 face2Norm[ iF ].second = geomNorm.XYZ();
3511 edge._normal += face2Norm[ iF ].second;
3516 else // !useGeometry - get _normal using surrounding mesh faces
3518 edge._normal = getWeigthedNormal( &edge );
3520 // set<TGeomID> faceIds;
3522 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3523 // while ( fIt->more() )
3525 // const SMDS_MeshElement* face = fIt->next();
3526 // if ( eos.GetNormal( face, geomNorm ))
3528 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3529 // continue; // use only one mesh face on FACE
3530 // edge._normal += geomNorm.XYZ();
3537 //if ( eos._hyp.UseSurfaceNormal() )
3539 switch ( eos.ShapeType() )
3546 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3547 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3548 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3549 edge._cosin = Cos( angle );
3552 case TopAbs_VERTEX: {
3555 getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3556 node, helper, normOK, &edge._cosin );
3558 else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3560 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3561 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3562 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3563 edge._cosin = Cos( angle );
3564 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3565 for ( int iF = 1; iF < totalNbFaces; ++iF )
3567 F = face2Norm[ iF ].first;
3568 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3570 double angle = inFaceDir.Angle( edge._normal );
3571 double cosin = Cos( angle );
3572 if ( Abs( cosin ) > Abs( edge._cosin ))
3573 edge._cosin = cosin;
3580 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3584 double normSize = edge._normal.SquareModulus();
3585 if ( normSize < numeric_limits<double>::min() )
3586 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3588 edge._normal /= sqrt( normSize );
3590 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3592 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3593 edge._nodes.resize( 1 );
3594 edge._normal.SetCoord( 0,0,0 );
3595 edge.SetMaxLen( 0 );
3598 // Set the rest data
3599 // --------------------
3601 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3603 if ( onShrinkShape )
3605 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3606 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3607 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3609 // set initial position which is parameters on _sWOL in this case
3610 if ( eos.SWOLType() == TopAbs_EDGE )
3612 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3613 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3614 if ( edge._nodes.size() > 1 )
3615 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3617 else // eos.SWOLType() == TopAbs_FACE
3619 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3620 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3621 if ( edge._nodes.size() > 1 )
3622 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3625 if ( edge._nodes.size() > 1 )
3627 // check if an angle between a FACE with layers and SWOL is sharp,
3628 // else the edge should not inflate
3630 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3631 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3632 F = face2Norm[iF].first;
3635 geomNorm = getFaceNormal( node, F, helper, normOK );
3636 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3637 geomNorm.Reverse(); // inside the SOLID
3638 if ( geomNorm * edge._normal < -0.001 )
3640 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3641 edge._nodes.resize( 1 );
3643 else if ( edge._lenFactor > 3 )
3645 edge._lenFactor = 2;
3646 edge.Set( _LayerEdge::RISKY_SWOL );
3653 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3655 if ( eos.ShapeType() == TopAbs_FACE )
3658 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3660 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3661 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3666 // Set neighbor nodes for a _LayerEdge based on EDGE
3668 if ( eos.ShapeType() == TopAbs_EDGE /*||
3669 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3671 edge._2neibors = new _2NearEdges;
3672 // target nodes instead of source ones will be set later
3678 //================================================================================
3680 * \brief Return normal to a FACE at a node
3681 * \param [in] n - node
3682 * \param [in] face - FACE
3683 * \param [in] helper - helper
3684 * \param [out] isOK - true or false
3685 * \param [in] shiftInside - to find normal at a position shifted inside the face
3686 * \return gp_XYZ - normal
3688 //================================================================================
3690 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3691 const TopoDS_Face& face,
3692 SMESH_MesherHelper& helper,
3699 // get a shifted position
3700 gp_Pnt p = SMESH_TNodeXYZ( node );
3701 gp_XYZ shift( 0,0,0 );
3702 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3703 switch ( S.ShapeType() ) {
3706 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3711 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3719 p.Translate( shift * 1e-5 );
3721 TopLoc_Location loc;
3722 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3724 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3726 projector.Perform( p );
3727 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3733 projector.LowerDistanceParameters(U,V);
3738 uv = helper.GetNodeUV( face, node, 0, &isOK );
3744 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3746 if ( !shiftInside &&
3747 helper.IsDegenShape( node->getshapeId() ) &&
3748 getFaceNormalAtSingularity( uv, face, helper, normal ))
3751 return normal.XYZ();
3754 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3755 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3757 if ( pointKind == IMPOSSIBLE &&
3758 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3760 // probably NormEstim() failed due to a too high tolerance
3761 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3762 isOK = ( pointKind < IMPOSSIBLE );
3764 if ( pointKind < IMPOSSIBLE )
3766 if ( pointKind != REGULAR &&
3768 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3770 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3771 if ( normShift * normal.XYZ() < 0. )
3777 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3779 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3781 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3782 while ( fIt->more() )
3784 const SMDS_MeshElement* f = fIt->next();
3785 if ( f->getshapeId() == faceID )
3787 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3790 TopoDS_Face ff = face;
3791 ff.Orientation( TopAbs_FORWARD );
3792 if ( helper.IsReversedSubMesh( ff ))
3799 return normal.XYZ();
3802 //================================================================================
3804 * \brief Try to get normal at a singularity of a surface basing on it's nature
3806 //================================================================================
3808 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3809 const TopoDS_Face& face,
3810 SMESH_MesherHelper& helper,
3813 BRepAdaptor_Surface surface( face );
3815 if ( !getRovolutionAxis( surface, axis ))
3818 double f,l, d, du, dv;
3819 f = surface.FirstUParameter();
3820 l = surface.LastUParameter();
3821 d = ( uv.X() - f ) / ( l - f );
3822 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3823 f = surface.FirstVParameter();
3824 l = surface.LastVParameter();
3825 d = ( uv.Y() - f ) / ( l - f );
3826 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3829 gp_Pnt2d testUV = uv;
3830 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3832 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3833 for ( int iLoop = 0; true ; ++iLoop )
3835 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3836 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3843 if ( axis * refDir < 0. )
3851 //================================================================================
3853 * \brief Return a normal at a node weighted with angles taken by faces
3855 //================================================================================
3857 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3859 const SMDS_MeshNode* n = edge->_nodes[0];
3861 gp_XYZ resNorm(0,0,0);
3862 SMESH_TNodeXYZ p0( n ), pP, pN;
3863 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3865 pP.Set( edge->_simplices[i]._nPrev );
3866 pN.Set( edge->_simplices[i]._nNext );
3867 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3868 double l0P = v0P.SquareMagnitude();
3869 double l0N = v0N.SquareMagnitude();
3870 double lPN = vPN.SquareMagnitude();
3871 if ( l0P < std::numeric_limits<double>::min() ||
3872 l0N < std::numeric_limits<double>::min() ||
3873 lPN < std::numeric_limits<double>::min() )
3875 double lNorm = norm.SquareMagnitude();
3876 double sin2 = lNorm / l0P / l0N;
3877 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3879 double weight = sin2 * angle / lPN;
3880 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3886 //================================================================================
3888 * \brief Return a normal at a node by getting a common point of offset planes
3889 * defined by the FACE normals
3891 //================================================================================
3893 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3894 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3898 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3900 gp_XYZ resNorm(0,0,0);
3901 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3902 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3904 for ( int i = 0; i < nbFaces; ++i )
3905 resNorm += f2Normal[i].second;
3909 // prepare _OffsetPlane's
3910 vector< _OffsetPlane > pln( nbFaces );
3911 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3913 pln[i]._faceIndex = i;
3914 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3918 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3919 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3922 // intersect neighboring OffsetPlane's
3923 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3924 while ( const TopoDS_Shape* edge = edgeIt->next() )
3926 int f1 = -1, f2 = -1;
3927 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3928 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3929 (( f1 < 0 ) ? f1 : f2 ) = i;
3932 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3935 // get a common point
3936 gp_XYZ commonPnt( 0, 0, 0 );
3939 for ( int i = 0; i < nbFaces; ++i )
3941 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3942 nbPoints += isPointFound;
3944 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3945 if ( nbPoints == 0 )
3948 commonPnt /= nbPoints;
3949 resNorm = commonPnt - p0;
3953 // choose the best among resNorm and wgtNorm
3954 resNorm.Normalize();
3955 wgtNorm.Normalize();
3956 double resMinDot = std::numeric_limits<double>::max();
3957 double wgtMinDot = std::numeric_limits<double>::max();
3958 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3960 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3961 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3964 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3966 edge->Set( _LayerEdge::MULTI_NORMAL );
3969 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3972 //================================================================================
3974 * \brief Compute line of intersection of 2 planes
3976 //================================================================================
3978 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3979 const TopoDS_Edge& E,
3980 const TopoDS_Vertex& V )
3982 int iNext = bool( _faceIndexNext[0] >= 0 );
3983 _faceIndexNext[ iNext ] = pln._faceIndex;
3985 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3986 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3988 gp_XYZ lineDir = n1 ^ n2;
3990 double x = Abs( lineDir.X() );
3991 double y = Abs( lineDir.Y() );
3992 double z = Abs( lineDir.Z() );
3994 int cooMax; // max coordinate
3996 if (x > z) cooMax = 1;
4000 if (y > z) cooMax = 2;
4005 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4007 // parallel planes - intersection is an offset of the common EDGE
4008 gp_Pnt p = BRep_Tool::Pnt( V );
4009 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4010 lineDir = getEdgeDir( E, V );
4014 // the constants in the 2 plane equations
4015 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
4016 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4021 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4022 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4025 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4027 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4030 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4031 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4035 gp_Lin& line = _lines[ iNext ];
4036 line.SetDirection( lineDir );
4037 line.SetLocation ( linePos );
4039 _isLineOK[ iNext ] = true;
4042 iNext = bool( pln._faceIndexNext[0] >= 0 );
4043 pln._lines [ iNext ] = line;
4044 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4045 pln._isLineOK [ iNext ] = true;
4048 //================================================================================
4050 * \brief Computes intersection point of two _lines
4052 //================================================================================
4054 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4055 const TopoDS_Vertex & V) const
4060 if ( NbLines() == 2 )
4062 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4063 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4064 if ( Abs( dot01 ) > 0.05 )
4066 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4067 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4068 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4073 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4074 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4075 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4076 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4077 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4085 //================================================================================
4087 * \brief Find 2 neigbor nodes of a node on EDGE
4089 //================================================================================
4091 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4092 const SMDS_MeshNode*& n1,
4093 const SMDS_MeshNode*& n2,
4097 const SMDS_MeshNode* node = edge->_nodes[0];
4098 const int shapeInd = eos._shapeID;
4099 SMESHDS_SubMesh* edgeSM = 0;
4100 if ( eos.ShapeType() == TopAbs_EDGE )
4102 edgeSM = eos._subMesh->GetSubMeshDS();
4103 if ( !edgeSM || edgeSM->NbElements() == 0 )
4104 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4108 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4109 while ( eIt->more() && !n2 )
4111 const SMDS_MeshElement* e = eIt->next();
4112 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4113 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4116 if (!edgeSM->Contains(e)) continue;
4120 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4121 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4123 ( iN++ ? n2 : n1 ) = nNeibor;
4126 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4130 //================================================================================
4132 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4134 //================================================================================
4136 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4137 const SMDS_MeshNode* n2,
4138 const _EdgesOnShape& eos,
4139 SMESH_MesherHelper& helper)
4141 if ( eos.ShapeType() != TopAbs_EDGE )
4143 if ( _curvature && Is( SMOOTHED_C1 ))
4146 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4147 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4148 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4152 double sumLen = vec1.Modulus() + vec2.Modulus();
4153 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4154 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4155 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4156 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4157 if ( _curvature ) delete _curvature;
4158 _curvature = _Curvature::New( avgNormProj, avgLen );
4159 // if ( _curvature )
4160 // debugMsg( _nodes[0]->GetID()
4161 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4162 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4163 // << _curvature->lenDelta(0) );
4167 if ( eos._sWOL.IsNull() )
4169 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4170 // if ( SMESH_Algo::isDegenerated( E ))
4172 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4173 gp_XYZ plnNorm = dirE ^ _normal;
4174 double proj0 = plnNorm * vec1;
4175 double proj1 = plnNorm * vec2;
4176 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4178 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4179 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4184 //================================================================================
4186 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4187 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4189 //================================================================================
4191 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4193 SMESH_MesherHelper& helper )
4195 _nodes = other._nodes;
4196 _normal = other._normal;
4198 _lenFactor = other._lenFactor;
4199 _cosin = other._cosin;
4200 _2neibors = other._2neibors;
4201 _curvature = 0; std::swap( _curvature, other._curvature );
4202 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4204 gp_XYZ lastPos( 0,0,0 );
4205 if ( eos.SWOLType() == TopAbs_EDGE )
4207 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4208 _pos.push_back( gp_XYZ( u, 0, 0));
4210 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4215 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4216 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4218 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4219 lastPos.SetX( uv.X() );
4220 lastPos.SetY( uv.Y() );
4225 //================================================================================
4227 * \brief Set _cosin and _lenFactor
4229 //================================================================================
4231 void _LayerEdge::SetCosin( double cosin )
4234 cosin = Abs( _cosin );
4235 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4236 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4239 //================================================================================
4241 * \brief Check if another _LayerEdge is a neighbor on EDGE
4243 //================================================================================
4245 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4247 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4248 ( edge->_2neibors && edge->_2neibors->include( this )));
4251 //================================================================================
4253 * \brief Fills a vector<_Simplex >
4255 //================================================================================
4257 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4258 vector<_Simplex>& simplices,
4259 const set<TGeomID>& ingnoreShapes,
4260 const _SolidData* dataToCheckOri,
4264 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4265 while ( fIt->more() )
4267 const SMDS_MeshElement* f = fIt->next();
4268 const TGeomID shapeInd = f->getshapeId();
4269 if ( ingnoreShapes.count( shapeInd )) continue;
4270 const int nbNodes = f->NbCornerNodes();
4271 const int srcInd = f->GetNodeIndex( node );
4272 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4273 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4274 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4275 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4276 std::swap( nPrev, nNext );
4277 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4281 SortSimplices( simplices );
4284 //================================================================================
4286 * \brief Set neighbor simplices side by side
4288 //================================================================================
4290 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4292 vector<_Simplex> sortedSimplices( simplices.size() );
4293 sortedSimplices[0] = simplices[0];
4295 for ( size_t i = 1; i < simplices.size(); ++i )
4297 for ( size_t j = 1; j < simplices.size(); ++j )
4298 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4300 sortedSimplices[i] = simplices[j];
4305 if ( nbFound == simplices.size() - 1 )
4306 simplices.swap( sortedSimplices );
4309 //================================================================================
4311 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4313 //================================================================================
4315 void _ViscousBuilder::makeGroupOfLE()
4318 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4320 if ( _sdVec[i]._n2eMap.empty() ) continue;
4322 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4323 TNode2Edge::iterator n2e;
4324 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4326 _LayerEdge* le = n2e->second;
4327 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4328 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4329 // << ", " << le->_nodes[iN]->GetID() <<"])");
4331 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4332 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4337 dumpFunction( SMESH_Comment("makeNormals") << i );
4338 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4340 _LayerEdge* edge = n2e->second;
4341 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4342 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4343 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4344 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4348 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4349 dumpCmd( "faceId1 = mesh.NbElements()" );
4350 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4351 for ( ; fExp.More(); fExp.Next() )
4353 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4355 if ( sm->NbElements() == 0 ) continue;
4356 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4357 while ( fIt->more())
4359 const SMDS_MeshElement* e = fIt->next();
4360 SMESH_Comment cmd("mesh.AddFace([");
4361 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4362 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4367 dumpCmd( "faceId2 = mesh.NbElements()" );
4368 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4369 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4370 << "'%s-%s' % (faceId1+1, faceId2))");
4376 //================================================================================
4378 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4380 //================================================================================
4382 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4384 data._geomSize = Precision::Infinite();
4385 double intersecDist;
4386 const SMDS_MeshElement* face;
4387 SMESH_MesherHelper helper( *_mesh );
4389 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4390 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4391 data._proxyMesh->GetFaces( data._solid )));
4393 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4395 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4396 if ( eos._edges.empty() )
4398 // get neighbor faces, intersection with which should not be considered since
4399 // collisions are avoided by means of smoothing
4400 set< TGeomID > neighborFaces;
4401 if ( eos._hyp.ToSmooth() )
4403 SMESH_subMeshIteratorPtr subIt =
4404 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4405 while ( subIt->more() )
4407 SMESH_subMesh* sm = subIt->next();
4408 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4409 while ( const TopoDS_Shape* face = fIt->next() )
4410 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4413 // find intersections
4414 double thinkness = eos._hyp.GetTotalThickness();
4415 for ( size_t i = 0; i < eos._edges.size(); ++i )
4417 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4418 eos._edges[i]->SetMaxLen( thinkness );
4419 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4420 if ( intersecDist > 0 && face )
4422 data._geomSize = Min( data._geomSize, intersecDist );
4423 if ( !neighborFaces.count( face->getshapeId() ))
4424 eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4429 data._maxThickness = 0;
4430 data._minThickness = 1e100;
4431 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4432 for ( ; hyp != data._hyps.end(); ++hyp )
4434 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4435 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4438 // Limit inflation step size by geometry size found by intersecting
4439 // normals of _LayerEdge's with mesh faces
4440 if ( data._stepSize > 0.3 * data._geomSize )
4441 limitStepSize( data, 0.3 * data._geomSize );
4443 if ( data._stepSize > data._minThickness )
4444 limitStepSize( data, data._minThickness );
4447 // -------------------------------------------------------------------------
4448 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4449 // so no need in detecting intersection at each inflation step
4450 // -------------------------------------------------------------------------
4452 int nbSteps = data._maxThickness / data._stepSize;
4453 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4456 vector< const SMDS_MeshElement* > closeFaces;
4459 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4461 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4462 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4465 for ( size_t i = 0; i < eos.size(); ++i )
4467 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4468 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4470 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4472 bool toIgnore = true;
4473 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4474 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4475 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4477 // check if a _LayerEdge will inflate in a direction opposite to a direction
4478 // toward a close face
4479 bool allBehind = true;
4480 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4482 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4483 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4485 toIgnore = allBehind;
4489 if ( toIgnore ) // no need to detect intersection
4491 eos[i]->Set( _LayerEdge::INTERSECTED );
4497 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4502 //================================================================================
4504 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4506 //================================================================================
4508 bool _ViscousBuilder::inflate(_SolidData& data)
4510 SMESH_MesherHelper helper( *_mesh );
4512 const double tgtThick = data._maxThickness;
4514 if ( data._stepSize < 1. )
4515 data._epsilon = data._stepSize * 1e-7;
4517 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4520 findCollisionEdges( data, helper );
4522 limitMaxLenByCurvature( data, helper );
4526 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4527 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4528 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4529 data._edgesOnShape[i]._edges.size() > 0 &&
4530 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4532 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4533 data._edgesOnShape[i]._edges[0]->Block( data );
4536 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4538 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4539 int nbSteps = 0, nbRepeats = 0;
4540 while ( avgThick < 0.99 )
4542 // new target length
4543 double prevThick = curThick;
4544 curThick += data._stepSize;
4545 if ( curThick > tgtThick )
4547 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4551 double stepSize = curThick - prevThick;
4552 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4554 // Elongate _LayerEdge's
4555 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4556 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4558 _EdgesOnShape& eos = data._edgesOnShape[iS];
4559 if ( eos._edges.empty() ) continue;
4561 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4562 for ( size_t i = 0; i < eos._edges.size(); ++i )
4564 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4569 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4572 // Improve and check quality
4573 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4577 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4578 debugMsg("NOT INVALIDATED STEP!");
4579 return error("Smoothing failed", data._index);
4581 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4582 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4584 _EdgesOnShape& eos = data._edgesOnShape[iS];
4585 for ( size_t i = 0; i < eos._edges.size(); ++i )
4586 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4590 break; // no more inflating possible
4594 // Evaluate achieved thickness
4596 int nbActiveEdges = 0;
4597 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4599 _EdgesOnShape& eos = data._edgesOnShape[iS];
4600 if ( eos._edges.empty() ) continue;
4602 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4603 for ( size_t i = 0; i < eos._edges.size(); ++i )
4605 if ( eos._edges[i]->_nodes.size() > 1 )
4606 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4608 avgThick += shapeTgtThick;
4609 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4612 avgThick /= data._n2eMap.size();
4613 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4615 #ifdef BLOCK_INFLATION
4616 if ( nbActiveEdges == 0 )
4618 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4622 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4624 debugMsg( "-- Stop inflation since "
4625 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4626 << tgtThick * avgThick << " ) * " << safeFactor );
4632 limitStepSize( data, 0.25 * distToIntersection );
4633 if ( data._stepSizeNodes[0] )
4634 data._stepSize = data._stepSizeCoeff *
4635 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4637 } // while ( avgThick < 0.99 )
4640 return error("failed at the very first inflation step", data._index);
4642 if ( avgThick < 0.99 )
4644 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4646 data._proxyMesh->_warning.reset
4647 ( new SMESH_ComputeError (COMPERR_WARNING,
4648 SMESH_Comment("Thickness ") << tgtThick <<
4649 " of viscous layers not reached,"
4650 " average reached thickness is " << avgThick*tgtThick));
4654 // Restore position of src nodes moved by inflation on _noShrinkShapes
4655 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4656 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4658 _EdgesOnShape& eos = data._edgesOnShape[iS];
4659 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4660 for ( size_t i = 0; i < eos._edges.size(); ++i )
4662 restoreNoShrink( *eos._edges[ i ] );
4667 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4670 //================================================================================
4672 * \brief Improve quality of layer inner surface and check intersection
4674 //================================================================================
4676 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4678 double & distToIntersection)
4680 if ( data._nbShapesToSmooth == 0 )
4681 return true; // no shapes needing smoothing
4683 bool moved, improved;
4685 vector< _LayerEdge* > movedEdges, badEdges;
4686 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4687 vector< bool > isConcaveFace;
4689 SMESH_MesherHelper helper(*_mesh);
4690 Handle(ShapeAnalysis_Surface) surface;
4693 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4695 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4697 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4699 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4700 if ( !eos._toSmooth ||
4701 eos.ShapeType() != shapeType ||
4702 eos._edges.empty() )
4705 // already smoothed?
4706 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4707 // if ( !toSmooth ) continue;
4709 if ( !eos._hyp.ToSmooth() )
4711 // smooth disabled by the user; check validy only
4712 if ( !isFace ) continue;
4714 for ( size_t i = 0; i < eos._edges.size(); ++i )
4716 _LayerEdge* edge = eos._edges[i];
4717 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4718 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4720 // debugMsg( "-- Stop inflation. Bad simplex ("
4721 // << " "<< edge->_nodes[0]->GetID()
4722 // << " "<< edge->_nodes.back()->GetID()
4723 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4724 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4726 badEdges.push_back( edge );
4729 if ( !badEdges.empty() )
4733 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4737 continue; // goto the next EDGE or FACE
4741 if ( eos.SWOLType() == TopAbs_FACE )
4743 if ( !F.IsSame( eos._sWOL )) {
4744 F = TopoDS::Face( eos._sWOL );
4745 helper.SetSubShape( F );
4746 surface = helper.GetSurface( F );
4751 F.Nullify(); surface.Nullify();
4753 const TGeomID sInd = eos._shapeID;
4755 // perform smoothing
4757 if ( eos.ShapeType() == TopAbs_EDGE )
4759 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4761 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4763 // smooth on EDGE's (normally we should not get here)
4767 for ( size_t i = 0; i < eos._edges.size(); ++i )
4769 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4771 dumpCmd( SMESH_Comment("# end step ")<<step);
4773 while ( moved && step++ < 5 );
4778 else // smooth on FACE
4781 eosC1.push_back( & eos );
4782 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4785 isConcaveFace.resize( eosC1.size() );
4786 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4788 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4789 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4790 for ( size_t i = 0; i < edges.size(); ++i )
4791 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4792 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4793 movedEdges.push_back( edges[i] );
4795 makeOffsetSurface( *eosC1[ iEOS ], helper );
4798 int step = 0, stepLimit = 5, nbBad = 0;
4799 while (( ++step <= stepLimit ) || improved )
4801 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4802 <<"_InfStep"<<infStep<<"_"<<step); // debug
4803 int oldBadNb = nbBad;
4806 #ifdef INCREMENTAL_SMOOTH
4807 bool findBest = false; // ( step == stepLimit );
4808 for ( size_t i = 0; i < movedEdges.size(); ++i )
4810 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4811 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4812 badEdges.push_back( movedEdges[i] );
4815 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4816 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4818 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4819 for ( size_t i = 0; i < edges.size(); ++i )
4821 edges[i]->Unset( _LayerEdge::SMOOTHED );
4822 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4823 badEdges.push_back( eos._edges[i] );
4827 nbBad = badEdges.size();
4830 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4832 if ( !badEdges.empty() && step >= stepLimit / 2 )
4834 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4837 // resolve hard smoothing situation around concave VERTEXes
4838 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4840 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4841 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4842 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4845 // look for the best smooth of _LayerEdge's neighboring badEdges
4847 for ( size_t i = 0; i < badEdges.size(); ++i )
4849 _LayerEdge* ledge = badEdges[i];
4850 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4852 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4853 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4855 ledge->Unset( _LayerEdge::SMOOTHED );
4856 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4858 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4861 if ( nbBad == oldBadNb &&
4863 step < stepLimit ) // smooth w/o chech of validity
4866 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4867 <<"_InfStep"<<infStep<<"_"<<step); // debug
4868 for ( size_t i = 0; i < movedEdges.size(); ++i )
4870 movedEdges[i]->SmoothWoCheck();
4872 if ( stepLimit < 9 )
4876 improved = ( nbBad < oldBadNb );
4880 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4881 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4883 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4886 } // smoothing steps
4888 // project -- to prevent intersections or fix bad simplices
4889 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4891 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4892 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4895 //if ( !badEdges.empty() )
4898 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4900 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4902 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4904 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4905 edge->CheckNeiborsOnBoundary( & badEdges );
4906 if (( nbBad > 0 ) ||
4907 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4909 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4910 gp_XYZ prevXYZ = edge->PrevCheckPos();
4911 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4912 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4914 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4915 << " "<< tgtXYZ._node->GetID()
4916 << " "<< edge->_simplices[j]._nPrev->GetID()
4917 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4918 badEdges.push_back( edge );
4925 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4926 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4932 } // // smooth on FACE's
4934 } // smooth on [ EDGEs, FACEs ]
4936 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4938 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4940 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4941 if ( eos.ShapeType() == TopAbs_FACE ||
4942 eos._edges.empty() ||
4943 !eos._sWOL.IsNull() )
4947 for ( size_t i = 0; i < eos._edges.size(); ++i )
4949 _LayerEdge* edge = eos._edges[i];
4950 if ( edge->_nodes.size() < 2 ) continue;
4951 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4952 //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
4953 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4954 //const gp_XYZ& prevXYZ = edge->PrevPos();
4955 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4956 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4958 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4959 << " "<< tgtXYZ._node->GetID()
4960 << " "<< edge->_simplices[j]._nPrev->GetID()
4961 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4962 badEdges.push_back( edge );
4967 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4969 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4975 // Check if the last segments of _LayerEdge intersects 2D elements;
4976 // checked elements are either temporary faces or faces on surfaces w/o the layers
4978 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4979 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4980 data._proxyMesh->GetFaces( data._solid )) );
4982 #ifdef BLOCK_INFLATION
4983 const bool toBlockInfaltion = true;
4985 const bool toBlockInfaltion = false;
4987 distToIntersection = Precision::Infinite();
4989 const SMDS_MeshElement* intFace = 0;
4990 const SMDS_MeshElement* closestFace = 0;
4992 bool is1stBlocked = true; // dbg
4993 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4995 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4996 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4998 for ( size_t i = 0; i < eos._edges.size(); ++i )
5000 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5001 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5003 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5006 // commented due to "Illegal hash-positionPosition" error in NETGEN
5007 // on Debian60 on viscous_layers_01/B2 case
5008 // Collision; try to deflate _LayerEdge's causing it
5009 // badEdges.clear();
5010 // badEdges.push_back( eos._edges[i] );
5011 // eosC1[0] = & eos;
5012 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5016 // badEdges.clear();
5017 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5019 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5021 // const SMDS_MeshElement* srcFace =
5022 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5023 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5024 // while ( nIt->more() )
5026 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5027 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5028 // if ( n2e != data._n2eMap.end() )
5029 // badEdges.push_back( n2e->second );
5032 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5037 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5044 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5049 const bool isShorterDist = ( distToIntersection > dist );
5050 if ( toBlockInfaltion || isShorterDist )
5052 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5053 // lying on this _ConvexFace
5054 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5055 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5058 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5059 // ( avoid limiting the thickness on the case of issue 22576)
5060 if ( intFace->getshapeId() == eos._shapeID )
5063 // ignore intersection with intFace of an adjacent FACE
5064 if ( dist > 0.1 * eos._edges[i]->_len )
5066 bool toIgnore = false;
5067 if ( eos._toSmooth )
5069 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5070 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5072 TopExp_Explorer sub( eos._shape,
5073 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5074 for ( ; !toIgnore && sub.More(); sub.Next() )
5075 // is adjacent - has a common EDGE or VERTEX
5076 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5078 if ( toIgnore ) // check angle between normals
5081 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5082 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5086 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5088 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5090 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5091 toIgnore = ( nInd >= 0 );
5098 // intersection not ignored
5100 if ( toBlockInfaltion &&
5101 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5103 if ( is1stBlocked ) { is1stBlocked = false; // debug
5104 dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5106 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5107 eos._edges[i]->Block( data ); // not to inflate
5109 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5111 // block _LayerEdge's, on top of which intFace is
5112 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5114 const SMDS_MeshElement* srcFace =
5115 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5116 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5117 while ( nIt->more() )
5119 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5120 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5121 if ( n2e != data._n2eMap.end() )
5122 n2e->second->Block( data );
5128 if ( isShorterDist )
5130 distToIntersection = dist;
5132 closestFace = intFace;
5135 } // if ( toBlockInfaltion || isShorterDist )
5136 } // loop on eos._edges
5137 } // loop on data._edgesOnShape
5139 if ( !is1stBlocked )
5142 if ( closestFace && le )
5145 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5146 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5147 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5148 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5149 << ") distance = " << distToIntersection<< endl;
5156 //================================================================================
5158 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5159 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5160 * \return int - resulting nb of bad _LayerEdge's
5162 //================================================================================
5164 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5165 SMESH_MesherHelper& helper,
5166 vector< _LayerEdge* >& badSmooEdges,
5167 vector< _EdgesOnShape* >& eosC1,
5170 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5172 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5175 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5176 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5177 ADDED = _LayerEdge::UNUSED_FLAG * 4
5179 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5182 bool haveInvalidated = true;
5183 while ( haveInvalidated )
5185 haveInvalidated = false;
5186 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5188 _LayerEdge* edge = badSmooEdges[i];
5189 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5191 bool invalidated = false;
5192 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5194 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5195 edge->Block( data );
5196 edge->Set( INVALIDATED );
5197 edge->Unset( TO_INVALIDATE );
5199 haveInvalidated = true;
5202 // look for _LayerEdge's of bad _simplices
5204 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5205 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5206 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5207 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5209 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5210 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5214 _LayerEdge* ee[2] = { 0,0 };
5215 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5216 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5217 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5219 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5220 while ( maxNbSteps > edge->NbSteps() && isBad )
5223 for ( int iE = 0; iE < 2; ++iE )
5225 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5226 ee[ iE ]->NbSteps() > 1 )
5228 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5229 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5230 ee[ iE ]->Block( data );
5231 ee[ iE ]->Set( INVALIDATED );
5232 haveInvalidated = true;
5235 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5236 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5240 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5241 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5242 ee[0]->Set( ADDED );
5243 ee[1]->Set( ADDED );
5246 ee[0]->Set( TO_INVALIDATE );
5247 ee[1]->Set( TO_INVALIDATE );
5251 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5253 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5254 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5255 edge->Block( data );
5256 edge->Set( INVALIDATED );
5257 edge->Unset( TO_INVALIDATE );
5258 haveInvalidated = true;
5260 } // loop on badSmooEdges
5261 } // while ( haveInvalidated )
5263 // re-smooth on analytical EDGEs
5264 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5266 _LayerEdge* edge = badSmooEdges[i];
5267 if ( !edge->Is( INVALIDATED )) continue;
5269 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5270 if ( eos->ShapeType() == TopAbs_VERTEX )
5272 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5273 while ( const TopoDS_Shape* e = eIt->next() )
5274 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5275 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5277 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5278 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5279 // F = TopoDS::Face( eoe->_sWOL );
5280 // surface = helper.GetSurface( F );
5282 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5283 eoe->_edgeSmoother->_anaCurve.Nullify();
5289 // check result of invalidation
5292 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5294 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5296 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5297 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5298 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5299 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5300 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5301 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5304 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5305 << " "<< tgtXYZ._node->GetID()
5306 << " "<< edge->_simplices[j]._nPrev->GetID()
5307 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5316 //================================================================================
5318 * \brief Create an offset surface
5320 //================================================================================
5322 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5324 if ( eos._offsetSurf.IsNull() ||
5325 eos._edgeForOffset == 0 ||
5326 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5329 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5332 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5333 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5334 double offset = baseSurface->Gap();
5336 eos._offsetSurf.Nullify();
5340 BRepOffsetAPI_MakeOffsetShape offsetMaker;
5341 offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5342 if ( !offsetMaker.IsDone() ) return;
5344 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5345 if ( !fExp.More() ) return;
5347 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5348 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5349 if ( surf.IsNull() ) return;
5351 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5353 catch ( Standard_Failure )
5358 //================================================================================
5360 * \brief Put nodes of a curved FACE to its offset surface
5362 //================================================================================
5364 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5366 vector< _EdgesOnShape* >& eosC1,
5370 _EdgesOnShape * eof = & eos;
5371 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5374 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5376 if ( eosC1[i]->_offsetSurf.IsNull() ||
5377 eosC1[i]->ShapeType() != TopAbs_FACE ||
5378 eosC1[i]->_edgeForOffset == 0 ||
5379 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5381 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5386 eof->_offsetSurf.IsNull() ||
5387 eof->ShapeType() != TopAbs_FACE ||
5388 eof->_edgeForOffset == 0 ||
5389 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5392 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5393 for ( size_t i = 0; i < eos._edges.size(); ++i )
5395 _LayerEdge* edge = eos._edges[i];
5396 edge->Unset( _LayerEdge::MARKED );
5397 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5399 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5401 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5404 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5407 int nbBlockedAround = 0;
5408 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5409 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5410 if ( nbBlockedAround > 1 )
5413 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5414 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5415 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5416 edge->_curvature->_uv = uv;
5417 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5419 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5420 gp_XYZ prevP = edge->PrevCheckPos();
5423 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5425 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5429 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5430 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5431 edge->_pos.back() = newP;
5433 edge->Set( _LayerEdge::MARKED );
5434 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5436 edge->_normal = ( newP - prevP ).Normalized();
5444 // dumpMove() for debug
5446 for ( ; i < eos._edges.size(); ++i )
5447 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5449 if ( i < eos._edges.size() )
5451 dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5452 << "_InfStep" << infStep << "_" << smooStep );
5453 for ( ; i < eos._edges.size(); ++i )
5455 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5456 dumpMove( eos._edges[i]->_nodes.back() );
5462 _ConvexFace* cnvFace;
5463 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5464 eos.ShapeType() == TopAbs_FACE &&
5465 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5466 !cnvFace->_normalsFixedOnBorders )
5468 // put on the surface nodes built on FACE boundaries
5469 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5470 while ( smIt->more() )
5472 SMESH_subMesh* sm = smIt->next();
5473 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5474 if ( !subEOS->_sWOL.IsNull() ) continue;
5475 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5477 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5479 cnvFace->_normalsFixedOnBorders = true;
5483 //================================================================================
5485 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5486 * _LayerEdge's to be in a consequent order
5488 //================================================================================
5490 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5492 SMESH_MesherHelper& helper)
5494 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5496 TopLoc_Location loc; double f,l;
5498 Handle(Geom_Line) line;
5499 Handle(Geom_Circle) circle;
5500 bool isLine, isCirc;
5501 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5503 // check if the EDGE is a line
5504 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5505 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5506 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5508 line = Handle(Geom_Line)::DownCast( curve );
5509 circle = Handle(Geom_Circle)::DownCast( curve );
5510 isLine = (!line.IsNull());
5511 isCirc = (!circle.IsNull());
5513 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5515 isLine = SMESH_Algo::IsStraight( E );
5518 line = new Geom_Line( gp::OX() ); // only type does matter
5520 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5525 else //////////////////////////////////////////////////////////////////////// 2D case
5527 if ( !eos._isRegularSWOL ) // 23190
5530 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5532 // check if the EDGE is a line
5533 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5534 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5535 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5537 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5538 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5539 isLine = (!line2d.IsNull());
5540 isCirc = (!circle2d.IsNull());
5542 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5545 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5546 while ( nIt->more() )
5547 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5548 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5550 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5551 for ( int i = 0; i < 2 && !isLine; ++i )
5552 isLine = ( size.Coord( i+1 ) <= lineTol );
5554 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5560 line = new Geom_Line( gp::OX() ); // only type does matter
5564 gp_Pnt2d p = circle2d->Location();
5565 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5566 circle = new Geom_Circle( ax, 1.); // only center position does matter
5575 return Handle(Geom_Curve)();
5578 //================================================================================
5580 * \brief Smooth edges on EDGE
5582 //================================================================================
5584 bool _Smoother1D::Perform(_SolidData& data,
5585 Handle(ShapeAnalysis_Surface)& surface,
5586 const TopoDS_Face& F,
5587 SMESH_MesherHelper& helper )
5589 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5592 findEdgesToSmooth();
5594 return smoothAnalyticEdge( data, surface, F, helper );
5596 return smoothComplexEdge ( data, surface, F, helper );
5599 //================================================================================
5601 * \brief Find edges to smooth
5603 //================================================================================
5605 void _Smoother1D::findEdgesToSmooth()
5607 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5608 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5609 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5610 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5612 _eToSmooth[0].first = _eToSmooth[0].second = 0;
5614 for ( size_t i = 0; i < _eos.size(); ++i )
5616 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5618 if ( needSmoothing( _leOnV[0]._cosin,
5619 _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5622 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5626 _eToSmooth[0].second = i+1;
5629 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5631 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5633 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5635 if ( needSmoothing( _leOnV[1]._cosin,
5636 _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5638 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5642 _eToSmooth[1].first = i;
5646 //================================================================================
5648 * \brief Check if iE-th _LayerEdge needs smoothing
5650 //================================================================================
5652 bool _Smoother1D::isToSmooth( int iE )
5654 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5655 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5656 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5657 gp_XYZ seg0 = pi - p0;
5658 gp_XYZ seg1 = p1 - pi;
5659 gp_XYZ tangent = seg0 + seg1;
5660 double tangentLen = tangent.Modulus();
5661 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5662 if ( tangentLen < std::numeric_limits<double>::min() )
5664 tangent /= tangentLen;
5666 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5668 _LayerEdge* ne = _eos[iE]->_neibors[i];
5669 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5670 ne->_nodes.size() < 2 ||
5671 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5673 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5674 double proj = edgeVec * tangent;
5675 if ( needSmoothing( 1., proj, segMinLen ))
5681 //================================================================================
5683 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5685 //================================================================================
5687 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5688 Handle(ShapeAnalysis_Surface)& surface,
5689 const TopoDS_Face& F,
5690 SMESH_MesherHelper& helper)
5692 if ( !isAnalytic() ) return false;
5694 size_t iFrom = 0, iTo = _eos._edges.size();
5696 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5698 if ( F.IsNull() ) // 3D
5700 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5701 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5702 //const gp_XYZ lineDir = pSrc1 - pSrc0;
5703 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5704 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5705 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5706 // vLE0->Is( _LayerEdge::BLOCKED ) ||
5707 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5708 // vLE1->Is( _LayerEdge::BLOCKED ));
5709 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5711 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5712 if ( iFrom >= iTo ) continue;
5713 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5714 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5715 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5716 double param1 = _leParams[ iTo ];
5717 for ( size_t i = iFrom; i < iTo; ++i )
5719 _LayerEdge* edge = _eos[i];
5720 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5721 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5722 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
5724 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5726 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5727 // double shift = ( lineDir * ( newPos - pSrc0 ) -
5728 // lineDir * ( curPos - pSrc0 ));
5729 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5731 if ( edge->Is( _LayerEdge::BLOCKED ))
5733 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5734 double curThick = pSrc.SquareDistance( tgtNode );
5735 double newThink = ( pSrc - newPos ).SquareModulus();
5736 if ( newThink > curThick )
5739 edge->_pos.back() = newPos;
5740 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5741 dumpMove( tgtNode );
5747 _LayerEdge* eV0 = getLEdgeOnV( 0 );
5748 _LayerEdge* eV1 = getLEdgeOnV( 1 );
5749 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5750 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5751 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5753 int iPeriodic = helper.GetPeriodicIndex();
5754 if ( iPeriodic == 1 || iPeriodic == 2 )
5756 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5757 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5758 std::swap( uvV0, uvV1 );
5761 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5763 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5764 if ( iFrom >= iTo ) continue;
5765 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5766 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5767 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5768 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5769 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5770 double param1 = _leParams[ iTo ];
5771 gp_XY rangeUV = uv1 - uv0;
5772 for ( size_t i = iFrom; i < iTo; ++i )
5774 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5775 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5776 gp_XY newUV = uv0 + param * rangeUV;
5778 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5779 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5780 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5781 dumpMove( tgtNode );
5783 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5784 pos->SetUParameter( newUV.X() );
5785 pos->SetVParameter( newUV.Y() );
5787 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5789 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5791 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5792 if ( _eos[i]->_pos.size() > 2 )
5794 // modify previous positions to make _LayerEdge less sharply bent
5795 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5796 const gp_XYZ uvShift = newUV0 - uvVec.back();
5797 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5798 int iPrev = uvVec.size() - 2;
5801 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5802 uvVec[ iPrev ] += uvShift * r;
5807 _eos[i]->_pos.back() = newUV0;
5814 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5816 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5817 gp_Pnt center3D = circle->Location();
5819 if ( F.IsNull() ) // 3D
5821 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5822 return true; // closed EDGE - nothing to do
5824 // circle is a real curve of EDGE
5825 gp_Circ circ = circle->Circ();
5827 // new center is shifted along its axis
5828 const gp_Dir& axis = circ.Axis().Direction();
5829 _LayerEdge* e0 = getLEdgeOnV(0);
5830 _LayerEdge* e1 = getLEdgeOnV(1);
5831 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5832 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5833 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5834 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5835 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5837 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5839 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5840 gp_Circ newCirc( newAxis, newRadius );
5841 gp_Vec vecC1 ( newCenter, p1 );
5843 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5847 for ( size_t i = 0; i < _eos.size(); ++i )
5849 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5850 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5851 double u = uLast * _leParams[i];
5852 gp_Pnt p = ElCLib::Value( u, newCirc );
5853 _eos._edges[i]->_pos.back() = p.XYZ();
5855 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5856 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5857 dumpMove( tgtNode );
5863 const gp_XY center( center3D.X(), center3D.Y() );
5865 _LayerEdge* e0 = getLEdgeOnV(0);
5866 _LayerEdge* eM = _eos._edges[ 0 ];
5867 _LayerEdge* e1 = getLEdgeOnV(1);
5868 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5869 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5870 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5871 gp_Vec2d vec0( center, uv0 );
5872 gp_Vec2d vecM( center, uvM );
5873 gp_Vec2d vec1( center, uv1 );
5874 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5875 double uMidl = vec0.Angle( vecM );
5876 if ( uLast * uMidl <= 0. )
5877 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5878 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5880 gp_Ax2d axis( center, vec0 );
5881 gp_Circ2d circ( axis, radius );
5882 for ( size_t i = 0; i < _eos.size(); ++i )
5884 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5885 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5886 double newU = uLast * _leParams[i];
5887 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5888 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5890 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5891 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5892 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5893 dumpMove( tgtNode );
5895 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5896 pos->SetUParameter( newUV.X() );
5897 pos->SetVParameter( newUV.Y() );
5899 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5908 //================================================================================
5910 * \brief smooth _LayerEdge's on a an EDGE
5912 //================================================================================
5914 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5915 Handle(ShapeAnalysis_Surface)& surface,
5916 const TopoDS_Face& F,
5917 SMESH_MesherHelper& helper)
5919 if ( _offPoints.empty() )
5922 // ----------------------------------------------
5923 // move _offPoints along normals of _LayerEdge's
5924 // ----------------------------------------------
5926 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5927 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5928 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5929 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5930 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5931 _leOnV[0]._len = e[0]->_len;
5932 _leOnV[1]._len = e[1]->_len;
5933 for ( size_t i = 0; i < _offPoints.size(); i++ )
5935 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5936 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5937 const double w0 = _offPoints[i]._2edges._wgt[0];
5938 const double w1 = _offPoints[i]._2edges._wgt[1];
5939 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5940 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5941 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5942 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5943 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5944 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5946 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5947 _offPoints[i]._len = avgLen;
5951 if ( !surface.IsNull() ) // project _offPoints to the FACE
5953 fTol = 100 * BRep_Tool::Tolerance( F );
5954 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5956 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5957 //if ( surface->Gap() < 0.5 * segLen )
5958 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5960 for ( size_t i = 1; i < _offPoints.size(); ++i )
5962 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5963 //if ( surface->Gap() < 0.5 * segLen )
5964 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5968 // -----------------------------------------------------------------
5969 // project tgt nodes of extreme _LayerEdge's to the offset segments
5970 // -----------------------------------------------------------------
5972 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
5973 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
5974 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
5976 gp_Pnt pExtreme[2], pProj[2];
5977 bool isProjected[2];
5978 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5980 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5981 int i = _iSeg[ is2nd ];
5982 int di = is2nd ? -1 : +1;
5983 bool & projected = isProjected[ is2nd ];
5985 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5988 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5989 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5990 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5991 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5992 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5993 if ( dist < distMin || projected )
5996 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5999 else if ( dist > distPrev )
6001 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6007 while ( !projected &&
6008 i >= 0 && i+1 < (int)_offPoints.size() );
6012 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6015 _iSeg[1] = _offPoints.size()-2;
6016 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6021 if ( _iSeg[0] > _iSeg[1] )
6023 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6027 // adjust length of extreme LE (test viscous_layers_01/B7)
6028 gp_Vec vDiv0( pExtreme[0], pProj[0] );
6029 gp_Vec vDiv1( pExtreme[1], pProj[1] );
6030 double d0 = vDiv0.Magnitude();
6031 double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6032 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6033 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6034 else e[0]->_len -= d0;
6036 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6037 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6038 else e[1]->_len -= d1;
6041 // ---------------------------------------------------------------------------------
6042 // compute normalized length of the offset segments located between the projections
6043 // ---------------------------------------------------------------------------------
6045 // temporary replace extreme _offPoints by pExtreme
6046 gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0] ]._xyz,
6047 _offPoints[ _iSeg[1]+1 ]._xyz };
6048 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6049 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6051 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6052 vector< double > len( nbSeg + 1 );
6054 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6055 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6057 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6059 // if ( isProjected[ 1 ])
6060 // len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6062 // len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6064 double fullLen = len.back() - d0 - d1;
6065 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6066 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6068 // -------------------------------------------------------------
6069 // distribute tgt nodes of _LayerEdge's between the projections
6070 // -------------------------------------------------------------
6073 for ( size_t i = 0; i < _eos.size(); ++i )
6075 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6076 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6077 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6079 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6080 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6081 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6083 if ( surface.IsNull() )
6085 _eos[i]->_pos.back() = p;
6087 else // project a new node position to a FACE
6089 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6090 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6092 p = surface->Value( uv2 ).XYZ();
6093 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6095 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6096 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6097 dumpMove( tgtNode );
6100 _offPoints[ _iSeg[0] ]._xyz = opXYZ[0];
6101 _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6106 //================================================================================
6108 * \brief Prepare for smoothing
6110 //================================================================================
6112 void _Smoother1D::prepare(_SolidData& data)
6114 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6115 _curveLen = SMESH_Algo::EdgeLength( E );
6117 // sort _LayerEdge's by position on the EDGE
6118 data.SortOnEdge( E, _eos._edges );
6120 // compute normalized param of _eos._edges on EDGE
6121 _leParams.resize( _eos._edges.size() + 1 );
6124 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6126 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6128 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6129 curLen = p.Distance( pPrev );
6130 _leParams[i+1] = _leParams[i] + curLen;
6133 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6134 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6135 _leParams[i] = _leParams[i+1] / fullLen;
6136 _leParams.back() = 1.;
6139 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6141 // get cosin to use in findEdgesToSmooth()
6142 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6143 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6144 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6145 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6146 if ( _eos._sWOL.IsNull() ) // 3D
6147 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6148 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6153 // divide E to have offset segments with low deflection
6154 BRepAdaptor_Curve c3dAdaptor( E );
6155 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6156 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6157 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6158 if ( discret.NbPoints() <= 2 )
6160 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6164 const double u0 = c3dAdaptor.FirstParameter();
6165 gp_Pnt p; gp_Vec tangent;
6166 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6168 _offPoints.resize( discret.NbPoints() );
6169 for ( size_t i = 0; i < _offPoints.size(); i++ )
6171 double u = discret.Parameter( i+1 );
6172 c3dAdaptor.D1( u, p, tangent );
6173 _offPoints[i]._xyz = p.XYZ();
6174 _offPoints[i]._edgeDir = tangent.XYZ();
6175 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6180 std::vector< double > params( _eos.size() + 2 );
6182 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6183 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6184 for ( size_t i = 0; i < _eos.size(); i++ )
6185 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6187 if ( params[1] > params[ _eos.size() ] )
6188 std::reverse( params.begin() + 1, params.end() - 1 );
6190 _offPoints.resize( _eos.size() + 2 );
6191 for ( size_t i = 0; i < _offPoints.size(); i++ )
6193 const double u = params[i];
6194 c3dAdaptor.D1( u, p, tangent );
6195 _offPoints[i]._xyz = p.XYZ();
6196 _offPoints[i]._edgeDir = tangent.XYZ();
6197 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6202 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6203 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6204 _2NearEdges tmp2edges;
6205 tmp2edges._edges[1] = _eos._edges[0];
6206 _leOnV[0]._2neibors = & tmp2edges;
6207 _leOnV[0]._nodes = leOnV[0]->_nodes;
6208 _leOnV[1]._nodes = leOnV[1]->_nodes;
6209 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6210 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6212 // find _LayerEdge's located before and after an offset point
6213 // (_eos._edges[ iLE ] is next after ePrev)
6214 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6215 ePrev = _eos._edges[ iLE++ ];
6216 eNext = ePrev->_2neibors->_edges[1];
6218 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6219 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6220 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6221 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6224 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6225 for ( size_t i = 0; i < _offPoints.size(); i++ )
6226 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6227 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6229 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6230 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6231 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6234 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6236 int iLBO = _offPoints.size() - 2; // last but one
6238 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6239 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6241 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6242 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6243 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6245 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6246 _leOnV[ 0 ]._len = 0;
6247 _leOnV[ 1 ]._len = 0;
6248 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6249 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6252 _iSeg[1] = _offPoints.size()-2;
6254 // initialize OffPnt::_len
6255 for ( size_t i = 0; i < _offPoints.size(); ++i )
6256 _offPoints[i]._len = 0;
6258 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6260 _leOnV[0]._len = leOnV[0]->_len;
6261 _leOnV[1]._len = leOnV[1]->_len;
6262 for ( size_t i = 0; i < _offPoints.size(); i++ )
6264 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6265 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6266 const double w0 = _offPoints[i]._2edges._wgt[0];
6267 const double w1 = _offPoints[i]._2edges._wgt[1];
6268 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6269 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6270 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6271 _offPoints[i]._xyz = avgXYZ;
6272 _offPoints[i]._len = avgLen;
6277 //================================================================================
6279 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6281 //================================================================================
6283 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6284 const gp_XYZ& edgeDir)
6286 gp_XYZ cross = normal ^ edgeDir;
6287 gp_XYZ norm = edgeDir ^ cross;
6288 double size = norm.Modulus();
6290 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6291 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6296 //================================================================================
6298 * \brief Writes a script creating a mesh composed of _offPoints
6300 //================================================================================
6302 void _Smoother1D::offPointsToPython() const
6304 const char* fname = "/tmp/offPoints.py";
6305 cout << "execfile('"<<fname<<"')"<<endl;
6307 py << "import SMESH" << endl
6308 << "from salome.smesh import smeshBuilder" << endl
6309 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
6310 << "mesh = smesh.Mesh( 'offPoints' )"<<endl;
6311 for ( size_t i = 0; i < _offPoints.size(); i++ )
6313 py << "mesh.AddNode( "
6314 << _offPoints[i]._xyz.X() << ", "
6315 << _offPoints[i]._xyz.Y() << ", "
6316 << _offPoints[i]._xyz.Z() << " )" << endl;
6320 //================================================================================
6322 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6324 //================================================================================
6326 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6327 vector< _LayerEdge* >& edges)
6329 map< double, _LayerEdge* > u2edge;
6330 for ( size_t i = 0; i < edges.size(); ++i )
6331 u2edge.insert( u2edge.end(),
6332 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6334 ASSERT( u2edge.size() == edges.size() );
6335 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6336 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6337 edges[i] = u2e->second;
6339 Sort2NeiborsOnEdge( edges );
6342 //================================================================================
6344 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6346 //================================================================================
6348 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6350 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6352 for ( size_t i = 0; i < edges.size()-1; ++i )
6353 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6354 edges[i]->_2neibors->reverse();
6356 const size_t iLast = edges.size() - 1;
6357 if ( edges.size() > 1 &&
6358 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6359 edges[iLast]->_2neibors->reverse();
6362 //================================================================================
6364 * \brief Return _EdgesOnShape* corresponding to the shape
6366 //================================================================================
6368 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6370 if ( shapeID < (int)_edgesOnShape.size() &&
6371 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6372 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6374 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6375 if ( _edgesOnShape[i]._shapeID == shapeID )
6376 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6381 //================================================================================
6383 * \brief Return _EdgesOnShape* corresponding to the shape
6385 //================================================================================
6387 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6389 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6390 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6393 //================================================================================
6395 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6397 //================================================================================
6399 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6401 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6403 set< TGeomID > vertices;
6405 if ( eos->ShapeType() == TopAbs_FACE )
6407 // check FACE concavity and get concave VERTEXes
6408 F = TopoDS::Face( eos->_shape );
6409 if ( isConcave( F, helper, &vertices ))
6410 _concaveFaces.insert( eos->_shapeID );
6412 // set eos._eosConcaVer
6413 eos->_eosConcaVer.clear();
6414 eos->_eosConcaVer.reserve( vertices.size() );
6415 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6417 _EdgesOnShape* eov = GetShapeEdges( *v );
6418 if ( eov && eov->_edges.size() == 1 )
6420 eos->_eosConcaVer.push_back( eov );
6421 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6422 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6426 // SetSmooLen() to _LayerEdge's on FACE
6427 // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6429 // eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6431 // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6432 // while ( smIt->more() ) // loop on sub-shapes of the FACE
6434 // _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6435 // if ( !eoe ) continue;
6437 // vector<_LayerEdge*>& eE = eoe->_edges;
6438 // for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6440 // if ( eE[iE]->_cosin <= theMinSmoothCosin )
6443 // SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6444 // while ( segIt->more() )
6446 // const SMDS_MeshElement* seg = segIt->next();
6447 // if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6449 // if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6450 // continue; // not to check a seg twice
6451 // for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6453 // _LayerEdge* eN = eE[iE]->_neibors[iN];
6454 // if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6456 // double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6457 // double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6458 // eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6459 // eN->Set( _LayerEdge::NEAR_BOUNDARY );
6464 } // if ( eos->ShapeType() == TopAbs_FACE )
6466 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6468 eos->_edges[i]->_smooFunction = 0;
6469 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6471 bool isCurved = false;
6472 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6474 _LayerEdge* edge = eos->_edges[i];
6476 // get simplices sorted
6477 _Simplex::SortSimplices( edge->_simplices );
6479 // smoothing function
6480 edge->ChooseSmooFunction( vertices, _n2eMap );
6483 double avgNormProj = 0, avgLen = 0;
6484 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6486 _Simplex& s = edge->_simplices[iS];
6488 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6489 avgNormProj += edge->_normal * vec;
6490 avgLen += vec.Modulus();
6491 if ( substituteSrcNodes )
6493 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6494 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6497 avgNormProj /= edge->_simplices.size();
6498 avgLen /= edge->_simplices.size();
6499 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6501 edge->Set( _LayerEdge::SMOOTHED_C1 );
6503 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6505 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6506 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6508 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6512 // prepare for putOnOffsetSurface()
6513 if (( eos->ShapeType() == TopAbs_FACE ) &&
6514 ( isCurved || !eos->_eosConcaVer.empty() ))
6516 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6517 eos->_edgeForOffset = 0;
6519 double maxCosin = -1;
6520 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6522 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6523 if ( !eoe || eoe->_edges.empty() ) continue;
6525 vector<_LayerEdge*>& eE = eoe->_edges;
6526 _LayerEdge* e = eE[ eE.size() / 2 ];
6527 if ( e->_cosin > maxCosin )
6529 eos->_edgeForOffset = e;
6530 maxCosin = e->_cosin;
6536 //================================================================================
6538 * \brief Add faces for smoothing
6540 //================================================================================
6542 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6543 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6545 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6546 for ( ; eos != eosToSmooth.end(); ++eos )
6548 if ( !*eos || (*eos)->_toSmooth ) continue;
6550 (*eos)->_toSmooth = true;
6552 if ( (*eos)->ShapeType() == TopAbs_FACE )
6554 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6555 (*eos)->_toSmooth = true;
6559 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6560 if ( edgesNoAnaSmooth )
6561 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6563 if ( (*eos)->_edgeSmoother )
6564 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6568 //================================================================================
6570 * \brief Limit _LayerEdge::_maxLen according to local curvature
6572 //================================================================================
6574 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6576 // find intersection of neighbor _LayerEdge's to limit _maxLen
6577 // according to local curvature (IPAL52648)
6579 // This method must be called after findCollisionEdges() where _LayerEdge's
6580 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6582 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6584 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6585 if ( eosI._edges.empty() ) continue;
6586 if ( !eosI._hyp.ToSmooth() )
6588 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6590 _LayerEdge* eI = eosI._edges[i];
6591 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6593 _LayerEdge* eN = eI->_neibors[iN];
6594 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6596 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6597 limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6602 else if ( eosI.ShapeType() == TopAbs_EDGE )
6604 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6605 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6607 _LayerEdge* e0 = eosI._edges[0];
6608 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6610 _LayerEdge* eI = eosI._edges[i];
6611 limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6618 //================================================================================
6620 * \brief Limit _LayerEdge::_maxLen according to local curvature
6622 //================================================================================
6624 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6626 _EdgesOnShape& eos1,
6627 _EdgesOnShape& eos2,
6628 const bool isSmoothable )
6630 if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6631 e2->_nodes[0]->GetPosition()->GetDim() ) &&
6632 ( e1->_cosin < 0.75 ))
6633 return; // angle > 90 deg at e1
6635 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6636 double norSize = plnNorm.SquareModulus();
6637 if ( norSize < std::numeric_limits<double>::min() )
6638 return; // parallel normals
6640 // find closest points of skew _LayerEdge's
6641 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6642 gp_XYZ dir12 = src2 - src1;
6643 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6644 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6645 double dot1 = perp2 * e1->_normal;
6646 double dot2 = perp1 * e2->_normal;
6647 double u1 = ( perp2 * dir12 ) / dot1;
6648 double u2 = - ( perp1 * dir12 ) / dot2;
6649 if ( u1 > 0 && u2 > 0 )
6651 double ovl = ( u1 * e1->_normal * dir12 -
6652 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6653 if ( ovl > theSmoothThickToElemSizeRatio )
6655 const double coef = 0.75;
6656 e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6657 e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6662 //================================================================================
6664 * \brief Fill data._collisionEdges
6666 //================================================================================
6668 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6670 data._collisionEdges.clear();
6672 // set the full thickness of the layers to LEs
6673 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6675 _EdgesOnShape& eos = data._edgesOnShape[iS];
6676 if ( eos._edges.empty() ) continue;
6677 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6679 for ( size_t i = 0; i < eos._edges.size(); ++i )
6681 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6682 double maxLen = eos._edges[i]->_maxLen;
6683 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6684 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6685 eos._edges[i]->_maxLen = maxLen;
6689 // make temporary quadrangles got by extrusion of
6690 // mesh edges along _LayerEdge._normal's
6692 vector< const SMDS_MeshElement* > tmpFaces;
6694 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6696 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6697 if ( eos.ShapeType() != TopAbs_EDGE )
6699 if ( eos._edges.empty() )
6701 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6702 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6703 while ( smIt->more() )
6704 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6705 if ( eov->_edges.size() == 1 )
6706 edge[ bool( edge[0]) ] = eov->_edges[0];
6710 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6711 tmpFaces.push_back( f );
6714 for ( size_t i = 0; i < eos._edges.size(); ++i )
6716 _LayerEdge* edge = eos._edges[i];
6717 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6719 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6720 if ( src2->GetPosition()->GetDim() > 0 &&
6721 src2->GetID() < edge->_nodes[0]->GetID() )
6722 continue; // avoid using same segment twice
6724 // a _LayerEdge containg tgt2
6725 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6727 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6728 tmpFaces.push_back( f );
6733 // Find _LayerEdge's intersecting tmpFaces.
6735 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6737 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6738 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6740 double dist1, dist2, segLen, eps = 0.5;
6741 _CollisionEdges collEdges;
6742 vector< const SMDS_MeshElement* > suspectFaces;
6743 const double angle45 = Cos( 45. * M_PI / 180. );
6745 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6747 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6748 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6750 // find sub-shapes whose VL can influence VL on eos
6751 set< TGeomID > neighborShapes;
6752 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6753 while ( const TopoDS_Shape* face = fIt->next() )
6755 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6756 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6758 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6759 while ( subIt->more() )
6760 neighborShapes.insert( subIt->next()->GetId() );
6763 if ( eos.ShapeType() == TopAbs_VERTEX )
6765 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6766 while ( const TopoDS_Shape* edge = eIt->next() )
6767 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6769 // find intersecting _LayerEdge's
6770 for ( size_t i = 0; i < eos._edges.size(); ++i )
6772 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6773 _LayerEdge* edge = eos._edges[i];
6774 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6777 gp_Vec eSegDir0, eSegDir1;
6778 if ( edge->IsOnEdge() )
6780 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6781 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6782 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6784 suspectFaces.clear();
6785 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6786 SMDSAbs_Face, suspectFaces );
6787 collEdges._intEdges.clear();
6788 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6790 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6791 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6792 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6793 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6794 if ( edge->IsOnEdge() ) {
6795 if ( edge->_2neibors->include( f->_le1 ) ||
6796 edge->_2neibors->include( f->_le2 )) continue;
6799 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6800 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6802 dist1 = dist2 = Precision::Infinite();
6803 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6804 dist1 = Precision::Infinite();
6805 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6806 dist2 = Precision::Infinite();
6807 if (( dist1 > segLen ) && ( dist2 > segLen ))
6810 if ( edge->IsOnEdge() )
6812 // skip perpendicular EDGEs
6813 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6814 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6815 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6816 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6817 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6822 // either limit inflation of edges or remember them for updating _normal
6823 // double dot = edge->_normal * f->GetDir();
6826 collEdges._intEdges.push_back( f->_le1 );
6827 collEdges._intEdges.push_back( f->_le2 );
6831 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6832 // edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6836 if ( !collEdges._intEdges.empty() )
6838 collEdges._edge = edge;
6839 data._collisionEdges.push_back( collEdges );
6844 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6847 // restore the zero thickness
6848 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6850 _EdgesOnShape& eos = data._edgesOnShape[iS];
6851 if ( eos._edges.empty() ) continue;
6852 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6854 for ( size_t i = 0; i < eos._edges.size(); ++i )
6856 eos._edges[i]->InvalidateStep( 1, eos );
6857 eos._edges[i]->_len = 0;
6862 //================================================================================
6864 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6865 * will be updated at each inflation step
6867 //================================================================================
6869 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
6871 SMESH_MesherHelper& helper )
6873 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6874 const double preci = BRep_Tool::Tolerance( convFace._face );
6875 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6877 bool edgesToUpdateFound = false;
6879 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6880 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6882 _EdgesOnShape& eos = * id2eos->second;
6883 if ( !eos._sWOL.IsNull() ) continue;
6884 if ( !eos._hyp.ToSmooth() ) continue;
6885 for ( size_t i = 0; i < eos._edges.size(); ++i )
6887 _LayerEdge* ledge = eos._edges[ i ];
6888 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6889 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6891 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6892 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6894 // the normal must be updated if distance from tgtPos to surface is less than
6897 // find an initial UV for search of a projection of tgtPos to surface
6898 const SMDS_MeshNode* nodeInFace = 0;
6899 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6900 while ( fIt->more() && !nodeInFace )
6902 const SMDS_MeshElement* f = fIt->next();
6903 if ( convFaceID != f->getshapeId() ) continue;
6905 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6906 while ( nIt->more() && !nodeInFace )
6908 const SMDS_MeshElement* n = nIt->next();
6909 if ( n->getshapeId() == convFaceID )
6910 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6915 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6918 surface->NextValueOfUV( uv, tgtPos, preci );
6919 double dist = surface->Gap();
6920 if ( dist < 0.95 * ledge->_maxLen )
6922 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6923 if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6924 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6925 edgesToUpdateFound = true;
6930 if ( !convFace._isTooCurved && edgesToUpdateFound )
6932 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6936 //================================================================================
6938 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6939 * _LayerEdge's on neighbor EDGE's
6941 //================================================================================
6943 bool _ViscousBuilder::updateNormals( _SolidData& data,
6944 SMESH_MesherHelper& helper,
6948 updateNormalsOfC1Vertices( data );
6950 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6953 // map to store new _normal and _cosin for each intersected edge
6954 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6955 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6956 _LayerEdge zeroEdge;
6957 zeroEdge._normal.SetCoord( 0,0,0 );
6958 zeroEdge._maxLen = Precision::Infinite();
6959 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6961 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6963 double segLen, dist1, dist2, dist;
6964 vector< pair< _LayerEdge*, double > > intEdgesDist;
6965 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6967 for ( int iter = 0; iter < 5; ++iter )
6969 edge2newEdge.clear();
6971 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6973 _CollisionEdges& ce = data._collisionEdges[iE];
6974 _LayerEdge* edge1 = ce._edge;
6975 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6976 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6977 if ( !eos1 ) continue;
6979 // detect intersections
6980 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6981 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6983 intEdgesDist.clear();
6984 double minIntDist = Precision::Infinite();
6985 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6987 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6988 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6989 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6991 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6992 double fact = ( 1.1 + dot * dot );
6993 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6994 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6995 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6996 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6997 dist1 = dist2 = Precision::Infinite();
6998 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
6999 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7002 if ( dist > testLen || dist <= 0 )
7005 if ( dist > testLen || dist <= 0 )
7008 // choose a closest edge
7009 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7010 double d1 = intP.SquareDistance( pSrc0 );
7011 double d2 = intP.SquareDistance( pSrc1 );
7012 int iClose = i + ( d2 < d1 );
7013 _LayerEdge* edge2 = ce._intEdges[iClose];
7014 edge2->Unset( _LayerEdge::MARKED );
7016 // choose a closest edge among neighbors
7017 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7018 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7019 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7021 _LayerEdge * edgeJ = intEdgesDist[j].first;
7022 if ( edge2->IsNeiborOnEdge( edgeJ ))
7024 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7025 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7028 intEdgesDist.push_back( make_pair( edge2, dist ));
7029 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7031 // iClose = i + !( d2 < d1 );
7032 // intEdges.push_back( ce._intEdges[iClose] );
7033 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7035 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7040 // compute new _normals
7041 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7043 _LayerEdge* edge2 = intEdgesDist[i].first;
7044 double distWgt = edge1->_len / intEdgesDist[i].second;
7045 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7046 // edge2->Is( _LayerEdge::BLOCKED )) continue;
7047 if ( edge2->Is( _LayerEdge::MARKED )) continue;
7048 edge2->Set( _LayerEdge::MARKED );
7051 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7053 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7054 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7055 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7056 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7057 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7058 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7059 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7060 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7061 newNormal.Normalize();
7065 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7066 if ( cos1 < theMinSmoothCosin )
7068 newCos = cos2 * sgn1;
7070 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7072 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7076 newCos = edge1->_cosin;
7079 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7080 e2neIt->second._normal += distWgt * newNormal;
7081 e2neIt->second._cosin = newCos;
7082 e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7083 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7084 e2neIt->second._normal += dir2;
7086 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7087 e2neIt->second._normal += distWgt * newNormal;
7088 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7090 e2neIt->second._cosin = edge2->_cosin;
7091 e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7093 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7094 e2neIt->second._normal += dir1;
7098 if ( edge2newEdge.empty() )
7099 break; //return true;
7101 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7103 // Update data of edges depending on a new _normal
7106 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7108 _LayerEdge* edge = e2neIt->first;
7109 _LayerEdge& newEdge = e2neIt->second;
7110 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7111 if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7114 // Check if a new _normal is OK:
7115 newEdge._normal.Normalize();
7116 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7118 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7120 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7121 edge->SetMaxLen( newEdge._maxLen );
7122 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7124 continue; // the new _normal is bad
7126 // the new _normal is OK
7128 // find shapes that need smoothing due to change of _normal
7129 if ( edge->_cosin < theMinSmoothCosin &&
7130 newEdge._cosin > theMinSmoothCosin )
7132 if ( eos->_sWOL.IsNull() )
7134 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7135 while ( fIt->more() )
7136 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7138 else // edge inflates along a FACE
7140 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7141 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7142 while ( const TopoDS_Shape* E = eIt->next() )
7144 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7145 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7146 if ( angle < M_PI / 2 )
7147 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7152 double len = edge->_len;
7153 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7154 edge->SetNormal( newEdge._normal );
7155 edge->SetCosin( newEdge._cosin );
7156 edge->SetNewLength( len, *eos, helper );
7157 edge->Set( _LayerEdge::MARKED );
7158 edge->Set( _LayerEdge::NORMAL_UPDATED );
7159 edgesNoAnaSmooth.insert( eos );
7162 // Update normals and other dependent data of not intersecting _LayerEdge's
7163 // neighboring the intersecting ones
7165 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7167 _LayerEdge* edge1 = e2neIt->first;
7168 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7169 if ( !edge1->Is( _LayerEdge::MARKED ))
7172 if ( edge1->IsOnEdge() )
7174 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7175 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7176 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7179 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7181 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7183 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7184 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7185 continue; // j-th neighbor is also intersected
7186 _LayerEdge* prevEdge = edge1;
7187 const int nbSteps = 10;
7188 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7190 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7191 neighbor->Is( _LayerEdge::MARKED ))
7193 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7194 if ( !eos ) continue;
7195 _LayerEdge* nextEdge = neighbor;
7196 if ( neighbor->_2neibors )
7199 nextEdge = neighbor->_2neibors->_edges[iNext];
7200 if ( nextEdge == prevEdge )
7201 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7203 double r = double(step-1)/nbSteps/(iter+1);
7204 if ( !nextEdge->_2neibors )
7207 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7208 newNorm.Normalize();
7209 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7212 double len = neighbor->_len;
7213 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7214 neighbor->SetNormal( newNorm );
7215 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7216 if ( neighbor->_2neibors )
7217 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7218 neighbor->SetNewLength( len, *eos, helper );
7219 neighbor->Set( _LayerEdge::MARKED );
7220 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7221 edgesNoAnaSmooth.insert( eos );
7223 if ( !neighbor->_2neibors )
7224 break; // neighbor is on VERTEX
7226 // goto the next neighbor
7227 prevEdge = neighbor;
7228 neighbor = nextEdge;
7235 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7240 //================================================================================
7242 * \brief Check if a new normal is OK
7244 //================================================================================
7246 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7248 const gp_XYZ& newNormal)
7250 // check a min angle between the newNormal and surrounding faces
7251 vector<_Simplex> simplices;
7252 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7253 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7254 double newMinDot = 1, curMinDot = 1;
7255 for ( size_t i = 0; i < simplices.size(); ++i )
7257 n1.Set( simplices[i]._nPrev );
7258 n2.Set( simplices[i]._nNext );
7259 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7260 double normLen2 = normFace.SquareModulus();
7261 if ( normLen2 < std::numeric_limits<double>::min() )
7263 normFace /= Sqrt( normLen2 );
7264 newMinDot = Min( newNormal * normFace, newMinDot );
7265 curMinDot = Min( edge._normal * normFace, curMinDot );
7268 if ( newMinDot < 0.5 )
7270 ok = ( newMinDot >= curMinDot * 0.9 );
7271 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7272 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7273 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7279 //================================================================================
7281 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7283 //================================================================================
7285 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7286 SMESH_MesherHelper& helper,
7288 const double stepSize )
7290 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7291 return true; // no shapes needing smoothing
7293 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7295 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7296 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7297 !eos._hyp.ToSmooth() ||
7298 eos.ShapeType() != TopAbs_FACE ||
7299 eos._edges.empty() )
7302 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7303 if ( !toSmooth ) continue;
7305 for ( size_t i = 0; i < eos._edges.size(); ++i )
7307 _LayerEdge* edge = eos._edges[i];
7308 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7310 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7313 const gp_XYZ& pPrev = edge->PrevPos();
7314 const gp_XYZ& pLast = edge->_pos.back();
7315 gp_XYZ stepVec = pLast - pPrev;
7316 double realStepSize = stepVec.Modulus();
7317 if ( realStepSize < numeric_limits<double>::min() )
7320 edge->_lenFactor = realStepSize / stepSize;
7321 edge->_normal = stepVec / realStepSize;
7322 edge->Set( _LayerEdge::NORMAL_UPDATED );
7329 //================================================================================
7331 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7333 //================================================================================
7335 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7337 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7339 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7340 if ( eov._eosC1.empty() ||
7341 eov.ShapeType() != TopAbs_VERTEX ||
7342 eov._edges.empty() )
7345 gp_XYZ newNorm = eov._edges[0]->_normal;
7346 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7347 bool normChanged = false;
7349 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7351 _EdgesOnShape* eoe = eov._eosC1[i];
7352 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7353 const double eLen = SMESH_Algo::EdgeLength( e );
7354 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7355 if ( oppV.IsSame( eov._shape ))
7356 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7357 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7358 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7359 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7361 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7362 if ( curThickOpp + curThick < eLen )
7365 double wgt = 2. * curThick / eLen;
7366 newNorm += wgt * eovOpp->_edges[0]->_normal;
7371 eov._edges[0]->SetNormal( newNorm.Normalized() );
7372 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7377 //================================================================================
7379 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7381 //================================================================================
7383 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7384 SMESH_MesherHelper& helper,
7387 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7390 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7391 for ( ; id2face != data._convexFaces.end(); ++id2face )
7393 _ConvexFace & convFace = (*id2face).second;
7394 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7396 if ( convFace._normalsFixed )
7397 continue; // already fixed
7398 if ( convFace.CheckPrisms() )
7399 continue; // nothing to fix
7401 convFace._normalsFixed = true;
7403 BRepAdaptor_Surface surface ( convFace._face, false );
7404 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7406 // check if the convex FACE is of spherical shape
7408 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7412 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7413 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7415 _EdgesOnShape& eos = *(id2eos->second);
7416 if ( eos.ShapeType() == TopAbs_VERTEX )
7418 _LayerEdge* ledge = eos._edges[ 0 ];
7419 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7420 centersBox.Add( center );
7422 for ( size_t i = 0; i < eos._edges.size(); ++i )
7423 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7425 if ( centersBox.IsVoid() )
7427 debugMsg( "Error: centersBox.IsVoid()" );
7430 const bool isSpherical =
7431 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7433 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7434 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7438 // set _LayerEdge::_normal as average of all normals
7440 // WARNING: different density of nodes on EDGEs is not taken into account that
7441 // can lead to an improper new normal
7443 gp_XYZ avgNormal( 0,0,0 );
7445 id2eos = convFace._subIdToEOS.begin();
7446 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7448 _EdgesOnShape& eos = *(id2eos->second);
7449 // set data of _CentralCurveOnEdge
7450 if ( eos.ShapeType() == TopAbs_EDGE )
7452 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7453 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7454 if ( !eos._sWOL.IsNull() )
7455 ceCurve._adjFace.Nullify();
7457 ceCurve._ledges.insert( ceCurve._ledges.end(),
7458 eos._edges.begin(), eos._edges.end());
7460 // summarize normals
7461 for ( size_t i = 0; i < eos._edges.size(); ++i )
7462 avgNormal += eos._edges[ i ]->_normal;
7464 double normSize = avgNormal.SquareModulus();
7465 if ( normSize < 1e-200 )
7467 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7470 avgNormal /= Sqrt( normSize );
7472 // compute new _LayerEdge::_cosin on EDGEs
7473 double avgCosin = 0;
7476 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7478 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7479 if ( ceCurve._adjFace.IsNull() )
7481 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7483 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7484 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7487 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7488 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7489 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7495 avgCosin /= nbCosin;
7497 // set _LayerEdge::_normal = avgNormal
7498 id2eos = convFace._subIdToEOS.begin();
7499 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7501 _EdgesOnShape& eos = *(id2eos->second);
7502 if ( eos.ShapeType() != TopAbs_EDGE )
7503 for ( size_t i = 0; i < eos._edges.size(); ++i )
7504 eos._edges[ i ]->_cosin = avgCosin;
7506 for ( size_t i = 0; i < eos._edges.size(); ++i )
7508 eos._edges[ i ]->SetNormal( avgNormal );
7509 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7513 else // if ( isSpherical )
7515 // We suppose that centers of curvature at all points of the FACE
7516 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7517 // having a common center of curvature we define the same new normal
7518 // as a sum of normals of _LayerEdge's on EDGEs among them.
7520 // get all centers of curvature for each EDGE
7522 helper.SetSubShape( convFace._face );
7523 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7525 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7526 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7528 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7530 // set adjacent FACE
7531 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7533 // get _LayerEdge's of the EDGE
7534 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7535 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7536 if ( !eos || eos->_edges.empty() )
7538 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7539 for ( int iV = 0; iV < 2; ++iV )
7541 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7542 TGeomID vID = meshDS->ShapeToIndex( v );
7543 eos = data.GetShapeEdges( vID );
7544 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7546 edgeLEdge = &vertexLEdges[0];
7547 edgeLEdgeEnd = edgeLEdge + 2;
7549 centerCurves[ iE ]._adjFace.Nullify();
7553 if ( ! eos->_toSmooth )
7554 data.SortOnEdge( edge, eos->_edges );
7555 edgeLEdge = &eos->_edges[ 0 ];
7556 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7557 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7558 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7560 if ( ! eos->_sWOL.IsNull() )
7561 centerCurves[ iE ]._adjFace.Nullify();
7564 // Get curvature centers
7568 if ( edgeLEdge[0]->IsOnEdge() &&
7569 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7571 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7572 centersBox.Add( center );
7574 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7575 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7576 { // EDGE or VERTEXes
7577 centerCurves[ iE ].Append( center, *edgeLEdge );
7578 centersBox.Add( center );
7580 if ( edgeLEdge[-1]->IsOnEdge() &&
7581 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7583 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7584 centersBox.Add( center );
7586 centerCurves[ iE ]._isDegenerated =
7587 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7589 } // loop on EDGES of convFace._face to set up data of centerCurves
7591 // Compute new normals for _LayerEdge's on EDGEs
7593 double avgCosin = 0;
7596 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7598 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7599 if ( ceCurve._isDegenerated )
7601 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7602 vector< gp_XYZ > & newNormals = ceCurve._normals;
7603 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7606 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7609 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7611 if ( isOK && !ceCurve._adjFace.IsNull() )
7613 // compute new _LayerEdge::_cosin
7614 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7615 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7618 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7619 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7620 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7626 // set new normals to _LayerEdge's of NOT degenerated central curves
7627 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7629 if ( centerCurves[ iE ]._isDegenerated )
7631 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7633 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7634 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7637 // set new normals to _LayerEdge's of degenerated central curves
7638 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7640 if ( !centerCurves[ iE ]._isDegenerated ||
7641 centerCurves[ iE ]._ledges.size() < 3 )
7643 // new normal is an average of new normals at VERTEXes that
7644 // was computed on non-degenerated _CentralCurveOnEdge's
7645 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7646 centerCurves[ iE ]._ledges.back ()->_normal );
7647 double sz = newNorm.Modulus();
7651 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7652 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7653 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7655 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7656 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7657 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7661 // Find new normals for _LayerEdge's based on FACE
7664 avgCosin /= nbCosin;
7665 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7666 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7667 if ( id2eos != convFace._subIdToEOS.end() )
7671 _EdgesOnShape& eos = * ( id2eos->second );
7672 for ( size_t i = 0; i < eos._edges.size(); ++i )
7674 _LayerEdge* ledge = eos._edges[ i ];
7675 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7677 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7679 iE = iE % centerCurves.size();
7680 if ( centerCurves[ iE ]._isDegenerated )
7682 newNorm.SetCoord( 0,0,0 );
7683 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7685 ledge->SetNormal( newNorm );
7686 ledge->_cosin = avgCosin;
7687 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7694 } // not a quasi-spherical FACE
7696 // Update _LayerEdge's data according to a new normal
7698 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7699 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7701 id2eos = convFace._subIdToEOS.begin();
7702 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7704 _EdgesOnShape& eos = * ( id2eos->second );
7705 for ( size_t i = 0; i < eos._edges.size(); ++i )
7707 _LayerEdge* & ledge = eos._edges[ i ];
7708 double len = ledge->_len;
7709 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7710 ledge->SetCosin( ledge->_cosin );
7711 ledge->SetNewLength( len, eos, helper );
7713 if ( eos.ShapeType() != TopAbs_FACE )
7714 for ( size_t i = 0; i < eos._edges.size(); ++i )
7716 _LayerEdge* ledge = eos._edges[ i ];
7717 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7719 _LayerEdge* neibor = ledge->_neibors[iN];
7720 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7722 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7723 neibor->Set( _LayerEdge::MOVED );
7724 neibor->SetSmooLen( neibor->_len );
7728 } // loop on sub-shapes of convFace._face
7730 // Find FACEs adjacent to convFace._face that got necessity to smooth
7731 // as a result of normals modification
7733 set< _EdgesOnShape* > adjFacesToSmooth;
7734 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7736 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7737 centerCurves[ iE ]._adjFaceToSmooth )
7739 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7741 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7743 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7748 data.AddShapesToSmooth( adjFacesToSmooth );
7753 } // loop on data._convexFaces
7758 //================================================================================
7760 * \brief Return max curvature of a FACE
7762 //================================================================================
7764 double _ConvexFace::GetMaxCurvature( _SolidData& data,
7766 BRepLProp_SLProps& surfProp,
7767 SMESH_MesherHelper& helper)
7769 double maxCurvature = 0;
7771 TopoDS_Face F = TopoDS::Face( eof._shape );
7773 const int nbTestPnt = 5;
7774 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7775 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7776 while ( smIt->more() )
7778 SMESH_subMesh* sm = smIt->next();
7779 const TGeomID subID = sm->GetId();
7781 // find _LayerEdge's of a sub-shape
7783 if (( eos = data.GetShapeEdges( subID )))
7784 this->_subIdToEOS.insert( make_pair( subID, eos ));
7788 // check concavity and curvature and limit data._stepSize
7789 const double minCurvature =
7790 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7791 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7792 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7794 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7795 surfProp.SetParameters( uv.X(), uv.Y() );
7796 if ( surfProp.IsCurvatureDefined() )
7798 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7799 surfProp.MinCurvature() * oriFactor );
7800 maxCurvature = Max( maxCurvature, curvature );
7802 if ( curvature > minCurvature )
7803 this->_isTooCurved = true;
7806 } // loop on sub-shapes of the FACE
7808 return maxCurvature;
7811 //================================================================================
7813 * \brief Finds a center of curvature of a surface at a _LayerEdge
7815 //================================================================================
7817 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7818 BRepLProp_SLProps& surfProp,
7819 SMESH_MesherHelper& helper,
7820 gp_Pnt & center ) const
7822 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7823 surfProp.SetParameters( uv.X(), uv.Y() );
7824 if ( !surfProp.IsCurvatureDefined() )
7827 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7828 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7829 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7830 if ( surfCurvatureMin > surfCurvatureMax )
7831 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7833 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7838 //================================================================================
7840 * \brief Check that prisms are not distorted
7842 //================================================================================
7844 bool _ConvexFace::CheckPrisms() const
7847 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7849 const _LayerEdge* edge = _simplexTestEdges[i];
7850 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7851 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7852 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7854 debugMsg( "Bad simplex of _simplexTestEdges ("
7855 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7856 << " "<< edge->_simplices[j]._nPrev->GetID()
7857 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7864 //================================================================================
7866 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7867 * stored in this _CentralCurveOnEdge.
7868 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7869 * \param [in,out] newNormal - current normal at this point, to be redefined
7870 * \return bool - true if succeeded.
7872 //================================================================================
7874 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7876 if ( this->_isDegenerated )
7879 // find two centers the given one lies between
7881 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7883 double sl2 = 1.001 * _segLength2[ i ];
7885 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7889 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7890 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7895 double r = d1 / ( d1 + d2 );
7896 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7897 ( r ) * _ledges[ i+1 ]->_normal );
7901 double sz = newNormal.Modulus();
7910 //================================================================================
7912 * \brief Set shape members
7914 //================================================================================
7916 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7917 const _ConvexFace& convFace,
7919 SMESH_MesherHelper& helper)
7923 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7924 while ( const TopoDS_Shape* F = fIt->next())
7925 if ( !convFace._face.IsSame( *F ))
7927 _adjFace = TopoDS::Face( *F );
7928 _adjFaceToSmooth = false;
7929 // _adjFace already in a smoothing queue ?
7930 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7931 _adjFaceToSmooth = eos->_toSmooth;
7936 //================================================================================
7938 * \brief Looks for intersection of it's last segment with faces
7939 * \param distance - returns shortest distance from the last node to intersection
7941 //================================================================================
7943 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7945 const double& epsilon,
7947 const SMDS_MeshElement** intFace)
7949 vector< const SMDS_MeshElement* > suspectFaces;
7951 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7952 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7954 bool segmentIntersected = false;
7955 distance = Precision::Infinite();
7956 int iFace = -1; // intersected face
7957 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7959 const SMDS_MeshElement* face = suspectFaces[j];
7960 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7961 face->GetNodeIndex( _nodes[0] ) >= 0 )
7962 continue; // face sharing _LayerEdge node
7963 const int nbNodes = face->NbCornerNodes();
7964 bool intFound = false;
7966 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7969 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7973 const SMDS_MeshNode* tria[3];
7976 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7979 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7985 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7986 segmentIntersected = true;
7987 if ( distance > dist )
7988 distance = dist, iFace = j;
7991 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7995 if ( segmentIntersected )
7998 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7999 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8000 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8001 << ", intersection with face ("
8002 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8003 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8004 << ") distance = " << distance << endl;
8008 return segmentIntersected;
8011 //================================================================================
8013 * \brief Returns a point used to check orientation of _simplices
8015 //================================================================================
8017 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8019 size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8021 if ( !eos || eos->_sWOL.IsNull() )
8024 if ( eos->SWOLType() == TopAbs_EDGE )
8026 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8028 //else // TopAbs_FACE
8030 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8033 //================================================================================
8035 * \brief Returns size and direction of the last segment
8037 //================================================================================
8039 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8041 // find two non-coincident positions
8042 gp_XYZ orig = _pos.back();
8044 int iPrev = _pos.size() - 2;
8045 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8046 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8047 while ( iPrev >= 0 )
8049 vec = orig - _pos[iPrev];
8050 if ( vec.SquareModulus() > tol*tol )
8060 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8061 segDir.SetDirection( _normal );
8066 gp_Pnt pPrev = _pos[ iPrev ];
8067 if ( !eos._sWOL.IsNull() )
8069 TopLoc_Location loc;
8070 if ( eos.SWOLType() == TopAbs_EDGE )
8073 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8074 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8078 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8079 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8081 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8083 segDir.SetLocation( pPrev );
8084 segDir.SetDirection( vec );
8085 segLen = vec.Modulus();
8091 //================================================================================
8093 * \brief Return the last (or \a which) position of the target node on a FACE.
8094 * \param [in] F - the FACE this _LayerEdge is inflated along
8095 * \param [in] which - index of position
8096 * \return gp_XY - result UV
8098 //================================================================================
8100 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8102 if ( F.IsSame( eos._sWOL )) // F is my FACE
8103 return gp_XY( _pos.back().X(), _pos.back().Y() );
8105 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8106 return gp_XY( 1e100, 1e100 );
8108 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8109 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8110 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8111 if ( !C2d.IsNull() && f <= u && u <= l )
8112 return C2d->Value( u ).XY();
8114 return gp_XY( 1e100, 1e100 );
8117 //================================================================================
8119 * \brief Test intersection of the last segment with a given triangle
8120 * using Moller-Trumbore algorithm
8121 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8123 //================================================================================
8125 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8126 const gp_XYZ& vert0,
8127 const gp_XYZ& vert1,
8128 const gp_XYZ& vert2,
8130 const double& EPSILON) const
8132 const gp_Pnt& orig = lastSegment.Location();
8133 const gp_Dir& dir = lastSegment.Direction();
8135 /* calculate distance from vert0 to ray origin */
8136 //gp_XYZ tvec = orig.XYZ() - vert0;
8138 //if ( tvec * dir > EPSILON )
8139 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8142 gp_XYZ edge1 = vert1 - vert0;
8143 gp_XYZ edge2 = vert2 - vert0;
8145 /* begin calculating determinant - also used to calculate U parameter */
8146 gp_XYZ pvec = dir.XYZ() ^ edge2;
8148 /* if determinant is near zero, ray lies in plane of triangle */
8149 double det = edge1 * pvec;
8151 const double ANGL_EPSILON = 1e-12;
8152 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8155 /* calculate distance from vert0 to ray origin */
8156 gp_XYZ tvec = orig.XYZ() - vert0;
8158 /* calculate U parameter and test bounds */
8159 double u = ( tvec * pvec ) / det;
8160 //if (u < 0.0 || u > 1.0)
8161 if ( u < -EPSILON || u > 1.0 + EPSILON )
8164 /* prepare to test V parameter */
8165 gp_XYZ qvec = tvec ^ edge1;
8167 /* calculate V parameter and test bounds */
8168 double v = (dir.XYZ() * qvec) / det;
8169 //if ( v < 0.0 || u + v > 1.0 )
8170 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8173 /* calculate t, ray intersects triangle */
8174 t = (edge2 * qvec) / det;
8180 //================================================================================
8182 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8183 * neighbor _LayerEdge's by it's own inflation vector.
8184 * \param [in] eov - EOS of the VERTEX
8185 * \param [in] eos - EOS of the FACE
8186 * \param [in] step - inflation step
8187 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8189 //================================================================================
8191 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8192 const _EdgesOnShape* eos,
8194 vector< _LayerEdge* > & badSmooEdges )
8196 // check if any of _neibors is in badSmooEdges
8197 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8198 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8201 // get all edges to move
8203 set< _LayerEdge* > edges;
8205 // find a distance between _LayerEdge on VERTEX and its neighbors
8206 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8208 for ( size_t i = 0; i < _neibors.size(); ++i )
8210 _LayerEdge* nEdge = _neibors[i];
8211 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8213 edges.insert( nEdge );
8214 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8217 // add _LayerEdge's close to curPosV
8221 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8223 _LayerEdge* edgeF = *e;
8224 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8226 _LayerEdge* nEdge = edgeF->_neibors[i];
8227 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8228 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8229 edges.insert( nEdge );
8233 while ( nbE < edges.size() );
8235 // move the target node of the got edges
8237 gp_XYZ prevPosV = PrevPos();
8238 if ( eov->SWOLType() == TopAbs_EDGE )
8240 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8241 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8243 else if ( eov->SWOLType() == TopAbs_FACE )
8245 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8246 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8249 SMDS_FacePosition* fPos;
8250 //double r = 1. - Min( 0.9, step / 10. );
8251 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8253 _LayerEdge* edgeF = *e;
8254 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8255 const gp_XYZ newPosF = curPosV + prevVF;
8256 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8257 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8258 edgeF->_pos.back() = newPosF;
8259 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8261 // set _curvature to make edgeF updated by putOnOffsetSurface()
8262 if ( !edgeF->_curvature )
8263 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
8265 edgeF->_curvature = new _Curvature;
8266 edgeF->_curvature->_r = 0;
8267 edgeF->_curvature->_k = 0;
8268 edgeF->_curvature->_h2lenRatio = 0;
8269 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8272 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8273 // SMESH_TNodeXYZ( _nodes[0] ));
8274 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8276 // _LayerEdge* edgeF = *e;
8277 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8278 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8279 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8280 // edgeF->_pos.back() = newPosF;
8281 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8284 // smooth _LayerEdge's around moved nodes
8285 //size_t nbBadBefore = badSmooEdges.size();
8286 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8288 _LayerEdge* edgeF = *e;
8289 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8290 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8291 //&& !edges.count( edgeF->_neibors[j] ))
8293 _LayerEdge* edgeFN = edgeF->_neibors[j];
8294 edgeFN->Unset( SMOOTHED );
8295 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8298 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8299 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8300 // int nbBadAfter = edgeFN->_simplices.size();
8302 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8304 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8306 // if ( nbBadAfter <= nbBad )
8308 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8309 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8310 // edgeF->_pos.back() = newPosF;
8311 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8312 // nbBad = nbBadAfter;
8316 badSmooEdges.push_back( edgeFN );
8319 // move a bit not smoothed around moved nodes
8320 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8322 // _LayerEdge* edgeF = badSmooEdges[i];
8323 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8324 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8325 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8326 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8327 // edgeF->_pos.back() = newPosF;
8328 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8332 //================================================================================
8334 * \brief Perform smooth of _LayerEdge's based on EDGE's
8335 * \retval bool - true if node has been moved
8337 //================================================================================
8339 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8340 const TopoDS_Face& F,
8341 SMESH_MesherHelper& helper)
8343 ASSERT( IsOnEdge() );
8345 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8346 SMESH_TNodeXYZ oldPos( tgtNode );
8347 double dist01, distNewOld;
8349 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8350 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8351 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8353 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8354 double lenDelta = 0;
8357 //lenDelta = _curvature->lenDelta( _len );
8358 lenDelta = _curvature->lenDeltaByDist( dist01 );
8359 newPos.ChangeCoord() += _normal * lenDelta;
8362 distNewOld = newPos.Distance( oldPos );
8366 if ( _2neibors->_plnNorm )
8368 // put newPos on the plane defined by source node and _plnNorm
8369 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8370 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8371 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8373 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8374 _pos.back() = newPos.XYZ();
8378 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8379 gp_XY uv( Precision::Infinite(), 0 );
8380 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8381 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8383 newPos = surface->Value( uv );
8384 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8387 // commented for IPAL0052478
8388 // if ( _curvature && lenDelta < 0 )
8390 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8391 // _len -= prevPos.Distance( oldPos );
8392 // _len += prevPos.Distance( newPos );
8394 bool moved = distNewOld > dist01/50;
8396 dumpMove( tgtNode ); // debug
8401 //================================================================================
8403 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8405 //================================================================================
8407 void _LayerEdge::SmoothWoCheck()
8409 if ( Is( DIFFICULT ))
8412 bool moved = Is( SMOOTHED );
8413 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8414 moved = _neibors[i]->Is( SMOOTHED );
8418 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8420 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8421 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8422 _pos.back() = newPos;
8424 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8427 //================================================================================
8429 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8431 //================================================================================
8433 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8435 if ( ! Is( NEAR_BOUNDARY ))
8440 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8442 _LayerEdge* eN = _neibors[iN];
8443 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8446 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8447 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8448 eN->_pos.size() != _pos.size() );
8450 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8451 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8452 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8453 if ( eN->_nodes.size() > 1 &&
8454 eN->_simplices[i].Includes( _nodes.back() ) &&
8455 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8460 badNeibors->push_back( eN );
8461 debugMsg("Bad boundary simplex ( "
8462 << " "<< eN->_nodes[0]->GetID()
8463 << " "<< eN->_nodes.back()->GetID()
8464 << " "<< eN->_simplices[i]._nPrev->GetID()
8465 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8476 //================================================================================
8478 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8479 * \retval int - nb of bad simplices around this _LayerEdge
8481 //================================================================================
8483 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8485 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8486 return 0; // shape of simplices not changed
8487 if ( _simplices.size() < 2 )
8488 return 0; // _LayerEdge inflated along EDGE or FACE
8490 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8493 const gp_XYZ& curPos = _pos.back();
8494 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8496 // quality metrics (orientation) of tetras around _tgtNode
8498 double vol, minVolBefore = 1e100;
8499 for ( size_t i = 0; i < _simplices.size(); ++i )
8501 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8502 minVolBefore = Min( minVolBefore, vol );
8504 int nbBad = _simplices.size() - nbOkBefore;
8506 bool bndNeedSmooth = false;
8508 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8512 // evaluate min angle
8513 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8515 size_t nbGoodAngles = _simplices.size();
8517 for ( size_t i = 0; i < _simplices.size(); ++i )
8519 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8522 if ( nbGoodAngles == _simplices.size() )
8528 if ( Is( ON_CONCAVE_FACE ))
8531 if ( step % 2 == 0 )
8534 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8536 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8537 _smooFunction = _funs[ FUN_CENTROIDAL ];
8539 _smooFunction = _funs[ FUN_LAPLACIAN ];
8542 // compute new position for the last _pos using different _funs
8545 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8548 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8549 else if ( _funs[ iFun ] == _smooFunction )
8550 continue; // _smooFunction again
8551 else if ( step > 1 )
8552 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8554 break; // let "easy" functions improve elements around distorted ones
8558 double delta = _curvature->lenDelta( _len );
8560 newPos += _normal * delta;
8563 double segLen = _normal * ( newPos - prevPos );
8564 if ( segLen + delta > 0 )
8565 newPos += _normal * delta;
8567 // double segLenChange = _normal * ( curPos - newPos );
8568 // newPos += 0.5 * _normal * segLenChange;
8572 double minVolAfter = 1e100;
8573 for ( size_t i = 0; i < _simplices.size(); ++i )
8575 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8576 minVolAfter = Min( minVolAfter, vol );
8579 if ( nbOkAfter < nbOkBefore )
8583 ( nbOkAfter == nbOkBefore ) &&
8584 ( minVolAfter <= minVolBefore ))
8587 nbBad = _simplices.size() - nbOkAfter;
8588 minVolBefore = minVolAfter;
8589 nbOkBefore = nbOkAfter;
8592 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8593 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8594 _pos.back() = newPos;
8596 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8597 << (nbBad ? " --BAD" : ""));
8601 continue; // look for a better function
8607 } // loop on smoothing functions
8609 if ( moved ) // notify _neibors
8612 for ( size_t i = 0; i < _neibors.size(); ++i )
8613 if ( !_neibors[i]->Is( MOVED ))
8615 _neibors[i]->Set( MOVED );
8616 toSmooth.push_back( _neibors[i] );
8623 //================================================================================
8625 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8626 * \retval int - nb of bad simplices around this _LayerEdge
8628 //================================================================================
8630 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8632 if ( !_smooFunction )
8633 return 0; // _LayerEdge inflated along EDGE or FACE
8635 return 0; // not inflated
8637 const gp_XYZ& curPos = _pos.back();
8638 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8640 // quality metrics (orientation) of tetras around _tgtNode
8642 double vol, minVolBefore = 1e100;
8643 for ( size_t i = 0; i < _simplices.size(); ++i )
8645 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8646 minVolBefore = Min( minVolBefore, vol );
8648 int nbBad = _simplices.size() - nbOkBefore;
8650 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8652 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8653 _smooFunction = _funs[ FUN_LAPLACIAN ];
8654 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8655 _smooFunction = _funs[ FUN_CENTROIDAL ];
8658 // compute new position for the last _pos using different _funs
8660 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8663 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8664 else if ( _funs[ iFun ] == _smooFunction )
8665 continue; // _smooFunction again
8666 else if ( step > 1 )
8667 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8669 break; // let "easy" functions improve elements around distorted ones
8673 double delta = _curvature->lenDelta( _len );
8675 newPos += _normal * delta;
8678 double segLen = _normal * ( newPos - prevPos );
8679 if ( segLen + delta > 0 )
8680 newPos += _normal * delta;
8682 // double segLenChange = _normal * ( curPos - newPos );
8683 // newPos += 0.5 * _normal * segLenChange;
8687 double minVolAfter = 1e100;
8688 for ( size_t i = 0; i < _simplices.size(); ++i )
8690 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8691 minVolAfter = Min( minVolAfter, vol );
8694 if ( nbOkAfter < nbOkBefore )
8696 if (( isConcaveFace || findBest ) &&
8697 ( nbOkAfter == nbOkBefore ) &&
8698 ( minVolAfter <= minVolBefore )
8702 nbBad = _simplices.size() - nbOkAfter;
8703 minVolBefore = minVolAfter;
8704 nbOkBefore = nbOkAfter;
8706 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8707 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8708 _pos.back() = newPos;
8710 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8711 << ( nbBad ? "--BAD" : ""));
8713 // commented for IPAL0052478
8714 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8715 // _len += prevPos.Distance(newPos);
8717 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8719 //_smooFunction = _funs[ iFun ];
8720 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8721 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8722 // << " minVol: " << minVolAfter
8723 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8725 continue; // look for a better function
8731 } // loop on smoothing functions
8736 //================================================================================
8738 * \brief Chooses a smoothing technic giving a position most close to an initial one.
8739 * For a correct result, _simplices must contain nodes lying on geometry.
8741 //================================================================================
8743 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8744 const TNode2Edge& n2eMap)
8746 if ( _smooFunction ) return;
8748 // use smoothNefPolygon() near concaveVertices
8749 if ( !concaveVertices.empty() )
8751 _smooFunction = _funs[ FUN_CENTROIDAL ];
8753 Set( ON_CONCAVE_FACE );
8755 for ( size_t i = 0; i < _simplices.size(); ++i )
8757 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8759 _smooFunction = _funs[ FUN_NEFPOLY ];
8761 // set FUN_CENTROIDAL to neighbor edges
8762 for ( i = 0; i < _neibors.size(); ++i )
8764 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8766 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8773 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8774 // // where the nodes are smoothed too far along a sphere thus creating
8775 // // inverted _simplices
8776 // double dist[theNbSmooFuns];
8777 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8778 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8780 // double minDist = Precision::Infinite();
8781 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8782 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8784 // gp_Pnt newP = (this->*_funs[i])();
8785 // dist[i] = p.SquareDistance( newP );
8786 // if ( dist[i]*coef[i] < minDist )
8788 // _smooFunction = _funs[i];
8789 // minDist = dist[i]*coef[i];
8795 _smooFunction = _funs[ FUN_LAPLACIAN ];
8798 // for ( size_t i = 0; i < _simplices.size(); ++i )
8799 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8800 // if ( minDim == 0 )
8801 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8802 // else if ( minDim == 1 )
8803 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8807 // for ( int i = 0; i < FUN_NB; ++i )
8809 // //cout << dist[i] << " ";
8810 // if ( _smooFunction == _funs[i] ) {
8812 // //debugMsg( fNames[i] );
8816 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8819 //================================================================================
8821 * \brief Returns a name of _SmooFunction
8823 //================================================================================
8825 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8828 fun = _smooFunction;
8829 for ( int i = 0; i < theNbSmooFuns; ++i )
8830 if ( fun == _funs[i] )
8833 return theNbSmooFuns;
8836 //================================================================================
8838 * \brief Computes a new node position using Laplacian smoothing
8840 //================================================================================
8842 gp_XYZ _LayerEdge::smoothLaplacian()
8844 gp_XYZ newPos (0,0,0);
8845 for ( size_t i = 0; i < _simplices.size(); ++i )
8846 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8847 newPos /= _simplices.size();
8852 //================================================================================
8854 * \brief Computes a new node position using angular-based smoothing
8856 //================================================================================
8858 gp_XYZ _LayerEdge::smoothAngular()
8860 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8861 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8862 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8864 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8866 for ( size_t i = 0; i < _simplices.size(); ++i )
8868 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8869 edgeDir.push_back( p - pPrev );
8870 edgeSize.push_back( edgeDir.back().Magnitude() );
8871 if ( edgeSize.back() < numeric_limits<double>::min() )
8874 edgeSize.pop_back();
8878 edgeDir.back() /= edgeSize.back();
8879 points.push_back( p );
8884 edgeDir.push_back ( edgeDir[0] );
8885 edgeSize.push_back( edgeSize[0] );
8886 pN /= points.size();
8888 gp_XYZ newPos(0,0,0);
8890 for ( size_t i = 0; i < points.size(); ++i )
8892 gp_Vec toN = pN - points[i];
8893 double toNLen = toN.Magnitude();
8894 if ( toNLen < numeric_limits<double>::min() )
8899 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8900 double bisecLen = bisec.SquareMagnitude();
8901 if ( bisecLen < numeric_limits<double>::min() )
8903 gp_Vec norm = edgeDir[i] ^ toN;
8904 bisec = norm ^ edgeDir[i];
8905 bisecLen = bisec.SquareMagnitude();
8907 bisecLen = Sqrt( bisecLen );
8911 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8912 sumSize += bisecLen;
8914 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8915 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8921 // project newPos to an average plane
8923 gp_XYZ norm(0,0,0); // plane normal
8924 points.push_back( points[0] );
8925 for ( size_t i = 1; i < points.size(); ++i )
8927 gp_XYZ vec1 = points[ i-1 ] - pN;
8928 gp_XYZ vec2 = points[ i ] - pN;
8929 gp_XYZ cross = vec1 ^ vec2;
8932 if ( cross * norm < numeric_limits<double>::min() )
8933 norm += cross.Reversed();
8937 catch (Standard_Failure) { // if |cross| == 0.
8940 gp_XYZ vec = newPos - pN;
8941 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8942 newPos = newPos - r * norm;
8947 //================================================================================
8949 * \brief Computes a new node position using weigthed node positions
8951 //================================================================================
8953 gp_XYZ _LayerEdge::smoothLengthWeighted()
8955 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8956 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8958 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8959 for ( size_t i = 0; i < _simplices.size(); ++i )
8961 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8962 edgeSize.push_back( ( p - pPrev ).Modulus() );
8963 if ( edgeSize.back() < numeric_limits<double>::min() )
8965 edgeSize.pop_back();
8969 points.push_back( p );
8973 edgeSize.push_back( edgeSize[0] );
8975 gp_XYZ newPos(0,0,0);
8977 for ( size_t i = 0; i < points.size(); ++i )
8979 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8980 sumSize += edgeSize[i] + edgeSize[i+1];
8986 //================================================================================
8988 * \brief Computes a new node position using angular-based smoothing
8990 //================================================================================
8992 gp_XYZ _LayerEdge::smoothCentroidal()
8994 gp_XYZ newPos(0,0,0);
8995 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8997 for ( size_t i = 0; i < _simplices.size(); ++i )
8999 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9000 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9001 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9002 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9005 newPos += gc * size;
9012 //================================================================================
9014 * \brief Computes a new node position located inside a Nef polygon
9016 //================================================================================
9018 gp_XYZ _LayerEdge::smoothNefPolygon()
9019 #ifdef OLD_NEF_POLYGON
9021 gp_XYZ newPos(0,0,0);
9023 // get a plane to search a solution on
9025 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9027 const double tol = numeric_limits<double>::min();
9028 gp_XYZ center(0,0,0);
9029 for ( i = 0; i < _simplices.size(); ++i )
9031 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9032 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9033 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9035 vecs.back() = vecs[0];
9036 center /= _simplices.size();
9038 gp_XYZ zAxis(0,0,0);
9039 for ( i = 0; i < _simplices.size(); ++i )
9040 zAxis += vecs[i] ^ vecs[i+1];
9043 for ( i = 0; i < _simplices.size(); ++i )
9046 if ( yAxis.SquareModulus() > tol )
9049 gp_XYZ xAxis = yAxis ^ zAxis;
9050 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9051 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9052 // p0.Distance( _simplices[2]._nPrev ));
9053 // gp_XYZ center = smoothLaplacian();
9054 // gp_XYZ xAxis, yAxis, zAxis;
9055 // for ( i = 0; i < _simplices.size(); ++i )
9057 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9058 // if ( xAxis.SquareModulus() > tol*tol )
9061 // for ( i = 1; i < _simplices.size(); ++i )
9063 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9064 // zAxis = xAxis ^ yAxis;
9065 // if ( zAxis.SquareModulus() > tol*tol )
9068 // if ( i == _simplices.size() ) return newPos;
9070 yAxis = zAxis ^ xAxis;
9071 xAxis /= xAxis.Modulus();
9072 yAxis /= yAxis.Modulus();
9074 // get half-planes of _simplices
9076 vector< _halfPlane > halfPlns( _simplices.size() );
9078 for ( size_t i = 0; i < _simplices.size(); ++i )
9080 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9081 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9082 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9083 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9084 gp_XY vec12 = p2 - p1;
9085 double dist12 = vec12.Modulus();
9089 halfPlns[ nbHP ]._pos = p1;
9090 halfPlns[ nbHP ]._dir = vec12;
9091 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9095 // intersect boundaries of half-planes, define state of intersection points
9096 // in relation to all half-planes and calculate internal point of a 2D polygon
9099 gp_XY newPos2D (0,0);
9101 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9102 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9103 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9105 vector< vector< TIntPntState > > allIntPnts( nbHP );
9106 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9108 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9109 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9111 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9112 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9115 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9117 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9119 if ( iHP1 == iHP2 ) continue;
9121 TIntPntState & ips1 = intPnts1[ iHP2 ];
9122 if ( ips1.second == UNDEF )
9124 // find an intersection point of boundaries of iHP1 and iHP2
9126 if ( iHP2 == iPrev ) // intersection with neighbors is known
9127 ips1.first = halfPlns[ iHP1 ]._pos;
9128 else if ( iHP2 == iNext )
9129 ips1.first = halfPlns[ iHP2 ]._pos;
9130 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9131 ips1.second = NO_INT;
9133 // classify the found intersection point
9134 if ( ips1.second != NO_INT )
9136 ips1.second = NOT_OUT;
9137 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9138 if ( i != iHP1 && i != iHP2 &&
9139 halfPlns[ i ].IsOut( ips1.first, tol ))
9140 ips1.second = IS_OUT;
9142 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9143 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9144 TIntPntState & ips2 = intPnts2[ iHP1 ];
9147 if ( ips1.second == NOT_OUT )
9150 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9154 // find a NOT_OUT segment of boundary which is located between
9155 // two NOT_OUT int points
9158 continue; // no such a segment
9162 // sort points along the boundary
9163 map< double, TIntPntState* > ipsByParam;
9164 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9166 TIntPntState & ips1 = intPnts1[ iHP2 ];
9167 if ( ips1.second != NO_INT )
9169 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9170 double param = op * halfPlns[ iHP1 ]._dir;
9171 ipsByParam.insert( make_pair( param, & ips1 ));
9174 // look for two neighboring NOT_OUT points
9176 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9177 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9179 TIntPntState & ips1 = *(u2ips->second);
9180 if ( ips1.second == NOT_OUT )
9181 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9182 else if ( nbNotOut >= 2 )
9189 if ( nbNotOut >= 2 )
9191 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9194 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9201 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9210 #else // OLD_NEF_POLYGON
9211 { ////////////////////////////////// NEW
9212 gp_XYZ newPos(0,0,0);
9214 // get a plane to search a solution on
9217 gp_XYZ center(0,0,0);
9218 for ( i = 0; i < _simplices.size(); ++i )
9219 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9220 center /= _simplices.size();
9222 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9223 for ( i = 0; i < _simplices.size(); ++i )
9224 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9225 vecs.back() = vecs[0];
9227 const double tol = numeric_limits<double>::min();
9228 gp_XYZ zAxis(0,0,0);
9229 for ( i = 0; i < _simplices.size(); ++i )
9231 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9234 if ( cross * zAxis < tol )
9235 zAxis += cross.Reversed();
9239 catch (Standard_Failure) { // if |cross| == 0.
9244 for ( i = 0; i < _simplices.size(); ++i )
9247 if ( yAxis.SquareModulus() > tol )
9250 gp_XYZ xAxis = yAxis ^ zAxis;
9251 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9252 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9253 // p0.Distance( _simplices[2]._nPrev ));
9254 // gp_XYZ center = smoothLaplacian();
9255 // gp_XYZ xAxis, yAxis, zAxis;
9256 // for ( i = 0; i < _simplices.size(); ++i )
9258 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9259 // if ( xAxis.SquareModulus() > tol*tol )
9262 // for ( i = 1; i < _simplices.size(); ++i )
9264 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9265 // zAxis = xAxis ^ yAxis;
9266 // if ( zAxis.SquareModulus() > tol*tol )
9269 // if ( i == _simplices.size() ) return newPos;
9271 yAxis = zAxis ^ xAxis;
9272 xAxis /= xAxis.Modulus();
9273 yAxis /= yAxis.Modulus();
9275 // get half-planes of _simplices
9277 vector< _halfPlane > halfPlns( _simplices.size() );
9279 for ( size_t i = 0; i < _simplices.size(); ++i )
9281 const gp_XYZ& OP1 = vecs[ i ];
9282 const gp_XYZ& OP2 = vecs[ i+1 ];
9283 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9284 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9285 gp_XY vec12 = p2 - p1;
9286 double dist12 = vec12.Modulus();
9290 halfPlns[ nbHP ]._pos = p1;
9291 halfPlns[ nbHP ]._dir = vec12;
9292 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9296 // intersect boundaries of half-planes, define state of intersection points
9297 // in relation to all half-planes and calculate internal point of a 2D polygon
9300 gp_XY newPos2D (0,0);
9302 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9303 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9304 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9306 vector< vector< TIntPntState > > allIntPnts( nbHP );
9307 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9309 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9310 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9312 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9313 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9316 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9318 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9320 if ( iHP1 == iHP2 ) continue;
9322 TIntPntState & ips1 = intPnts1[ iHP2 ];
9323 if ( ips1.second == UNDEF )
9325 // find an intersection point of boundaries of iHP1 and iHP2
9327 if ( iHP2 == iPrev ) // intersection with neighbors is known
9328 ips1.first = halfPlns[ iHP1 ]._pos;
9329 else if ( iHP2 == iNext )
9330 ips1.first = halfPlns[ iHP2 ]._pos;
9331 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9332 ips1.second = NO_INT;
9334 // classify the found intersection point
9335 if ( ips1.second != NO_INT )
9337 ips1.second = NOT_OUT;
9338 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9339 if ( i != iHP1 && i != iHP2 &&
9340 halfPlns[ i ].IsOut( ips1.first, tol ))
9341 ips1.second = IS_OUT;
9343 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9344 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9345 TIntPntState & ips2 = intPnts2[ iHP1 ];
9348 if ( ips1.second == NOT_OUT )
9351 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9355 // find a NOT_OUT segment of boundary which is located between
9356 // two NOT_OUT int points
9359 continue; // no such a segment
9363 // sort points along the boundary
9364 map< double, TIntPntState* > ipsByParam;
9365 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9367 TIntPntState & ips1 = intPnts1[ iHP2 ];
9368 if ( ips1.second != NO_INT )
9370 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9371 double param = op * halfPlns[ iHP1 ]._dir;
9372 ipsByParam.insert( make_pair( param, & ips1 ));
9375 // look for two neighboring NOT_OUT points
9377 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9378 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9380 TIntPntState & ips1 = *(u2ips->second);
9381 if ( ips1.second == NOT_OUT )
9382 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9383 else if ( nbNotOut >= 2 )
9390 if ( nbNotOut >= 2 )
9392 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9395 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9402 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9411 #endif // OLD_NEF_POLYGON
9413 //================================================================================
9415 * \brief Add a new segment to _LayerEdge during inflation
9417 //================================================================================
9419 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9424 if ( len > _maxLen )
9427 Block( eos.GetData() );
9429 const double lenDelta = len - _len;
9430 if ( lenDelta < len * 1e-3 )
9432 Block( eos.GetData() );
9436 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9437 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9439 if ( eos._hyp.IsOffsetMethod() )
9443 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9444 while ( faceIt->more() )
9446 const SMDS_MeshElement* face = faceIt->next();
9447 if ( !eos.GetNormal( face, faceNorm ))
9450 // translate plane of a face
9451 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9453 // find point of intersection of the face plane located at baryCenter
9454 // and _normal located at newXYZ
9455 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9456 double dot = ( faceNorm.XYZ() * _normal );
9457 if ( dot < std::numeric_limits<double>::min() )
9458 dot = lenDelta * 1e-3;
9459 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9460 newXYZ += step * _normal;
9462 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9466 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9469 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9470 _pos.push_back( newXYZ );
9472 if ( !eos._sWOL.IsNull() )
9476 if ( eos.SWOLType() == TopAbs_EDGE )
9478 double u = Precision::Infinite(); // to force projection w/o distance check
9479 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9480 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9481 _pos.back().SetCoord( u, 0, 0 );
9482 if ( _nodes.size() > 1 && uvOK )
9484 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9485 pos->SetUParameter( u );
9490 gp_XY uv( Precision::Infinite(), 0 );
9491 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9492 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9493 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9494 if ( _nodes.size() > 1 && uvOK )
9496 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9497 pos->SetUParameter( uv.X() );
9498 pos->SetVParameter( uv.Y() );
9503 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9507 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9509 Block( eos.GetData() );
9517 if ( eos.ShapeType() != TopAbs_FACE )
9519 for ( size_t i = 0; i < _neibors.size(); ++i )
9520 //if ( _len > _neibors[i]->GetSmooLen() )
9521 _neibors[i]->Set( MOVED );
9525 dumpMove( n ); //debug
9528 //================================================================================
9530 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9532 //================================================================================
9534 void _LayerEdge::Block( _SolidData& data )
9536 //if ( Is( BLOCKED )) return;
9539 SMESH_Comment msg( "#BLOCK shape=");
9540 msg << data.GetShapeEdges( this )->_shapeID
9541 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9542 dumpCmd( msg + " -- BEGIN");
9545 std::queue<_LayerEdge*> queue;
9548 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9549 while ( !queue.empty() )
9551 _LayerEdge* edge = queue.front(); queue.pop();
9552 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9553 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9554 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9556 _LayerEdge* neibor = edge->_neibors[iN];
9557 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9559 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9560 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9561 double minDist = pSrc.SquareDistance( pSrcN );
9562 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9563 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9564 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9565 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9566 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9568 //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9569 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9570 // neibor->_lenFactor / edge->_lenFactor );
9572 if ( neibor->_maxLen > newMaxLen )
9574 neibor->SetMaxLen( newMaxLen );
9575 if ( neibor->_maxLen < neibor->_len )
9577 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9578 int lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9579 while ( neibor->_len > neibor->_maxLen &&
9580 neibor->NbSteps() > lastStep )
9581 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9582 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9583 //neibor->Block( data );
9585 queue.push( neibor );
9589 dumpCmd( msg + " -- END");
9592 //================================================================================
9594 * \brief Remove last inflation step
9596 //================================================================================
9598 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9600 if ( _pos.size() > curStep && _nodes.size() > 1 )
9602 _pos.resize( curStep );
9604 gp_Pnt nXYZ = _pos.back();
9605 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9606 SMESH_TNodeXYZ curXYZ( n );
9607 if ( !eos._sWOL.IsNull() )
9609 TopLoc_Location loc;
9610 if ( eos.SWOLType() == TopAbs_EDGE )
9612 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9613 pos->SetUParameter( nXYZ.X() );
9615 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9616 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9620 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9621 pos->SetUParameter( nXYZ.X() );
9622 pos->SetVParameter( nXYZ.Y() );
9623 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9624 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9627 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9630 if ( restoreLength )
9632 if ( NbSteps() == 0 )
9634 else if ( IsOnFace() && Is( MOVED ))
9635 _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9637 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9643 //================================================================================
9645 * \brief Return index of a _pos distant from _normal
9647 //================================================================================
9649 int _LayerEdge::GetSmoothedPos( const double tol )
9652 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9654 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9655 if ( normDist > tol * tol )
9661 //================================================================================
9663 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9665 //================================================================================
9667 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9669 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9672 // find the 1st smoothed _pos
9673 int iSmoothed = GetSmoothedPos( tol );
9674 if ( !iSmoothed ) return;
9676 //if ( 1 || Is( DISTORTED ))
9678 gp_XYZ normal = _normal;
9679 if ( Is( NORMAL_UPDATED ))
9680 for ( size_t i = 1; i < _pos.size(); ++i )
9682 normal = _pos[i] - _pos[0];
9683 double size = normal.Modulus();
9684 if ( size > RealSmall() )
9690 const double r = 0.2;
9691 for ( int iter = 0; iter < 50; ++iter )
9694 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9696 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9697 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9699 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9700 double newLen = ( 1-r ) * midLen + r * segLen[i];
9701 const_cast< double& >( segLen[i] ) = newLen;
9702 // check angle between normal and (_pos[i+1], _pos[i] )
9703 gp_XYZ posDir = _pos[i+1] - _pos[i];
9704 double size = posDir.SquareModulus();
9705 if ( size > RealSmall() )
9706 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9708 if ( minDot > 0.5 * 0.5 )
9714 // for ( size_t i = 1; i < _pos.size()-1; ++i )
9716 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
9719 // double wgt = segLen[i] / segLen.back();
9720 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9721 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
9722 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
9723 // _pos[i] = newPos;
9728 //================================================================================
9730 * \brief Print flags
9732 //================================================================================
9734 std::string _LayerEdge::DumpFlags() const
9737 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9738 if ( _flags & flag )
9740 EFlags f = (EFlags) flag;
9742 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
9743 case MOVED: dump << "MOVED"; break;
9744 case SMOOTHED: dump << "SMOOTHED"; break;
9745 case DIFFICULT: dump << "DIFFICULT"; break;
9746 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9747 case BLOCKED: dump << "BLOCKED"; break;
9748 case INTERSECTED: dump << "INTERSECTED"; break;
9749 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
9750 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9751 case MARKED: dump << "MARKED"; break;
9752 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
9753 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
9754 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
9755 case DISTORTED: dump << "DISTORTED"; break;
9756 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
9757 case SHRUNK: dump << "SHRUNK"; break;
9758 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
9762 cout << dump << endl;
9767 //================================================================================
9769 * \brief Create layers of prisms
9771 //================================================================================
9773 bool _ViscousBuilder::refine(_SolidData& data)
9775 SMESH_MesherHelper& helper = data.GetHelper();
9776 helper.SetElementsOnShape(false);
9778 Handle(Geom_Curve) curve;
9779 Handle(ShapeAnalysis_Surface) surface;
9780 TopoDS_Edge geomEdge;
9781 TopoDS_Face geomFace;
9782 TopLoc_Location loc;
9785 vector< gp_XYZ > pos3D;
9786 bool isOnEdge, isTooConvexFace = false;
9787 TGeomID prevBaseId = -1;
9788 TNode2Edge* n2eMap = 0;
9789 TNode2Edge::iterator n2e;
9791 // Create intermediate nodes on each _LayerEdge
9793 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9795 _EdgesOnShape& eos = data._edgesOnShape[iS];
9796 if ( eos._edges.empty() ) continue;
9798 if ( eos._edges[0]->_nodes.size() < 2 )
9799 continue; // on _noShrinkShapes
9801 // get data of a shrink shape
9803 geomEdge.Nullify(); geomFace.Nullify();
9804 curve.Nullify(); surface.Nullify();
9805 if ( !eos._sWOL.IsNull() )
9807 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9810 geomEdge = TopoDS::Edge( eos._sWOL );
9811 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9815 geomFace = TopoDS::Face( eos._sWOL );
9816 surface = helper.GetSurface( geomFace );
9819 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9821 geomFace = TopoDS::Face( eos._shape );
9822 surface = helper.GetSurface( geomFace );
9823 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9824 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9825 eos._eosC1[ i ]->_toSmooth = true;
9827 isTooConvexFace = false;
9828 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9829 isTooConvexFace = cf->_isTooCurved;
9832 vector< double > segLen;
9833 for ( size_t i = 0; i < eos._edges.size(); ++i )
9835 _LayerEdge& edge = *eos._edges[i];
9836 if ( edge._pos.size() < 2 )
9839 // get accumulated length of segments
9840 segLen.resize( edge._pos.size() );
9842 if ( eos._sWOL.IsNull() )
9844 bool useNormal = true;
9845 bool usePos = false;
9846 bool smoothed = false;
9847 double preci = 0.1 * edge._len;
9848 if ( eos._toSmooth && edge._pos.size() > 2 )
9850 smoothed = edge.GetSmoothedPos( preci );
9854 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9856 useNormal = usePos = false;
9857 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9858 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9860 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9861 if ( surface->Gap() < 2. * edge._len )
9862 segLen[j] = surface->Gap();
9868 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9870 #ifndef __NODES_AT_POS
9871 useNormal = usePos = false;
9872 edge._pos[1] = edge._pos.back();
9873 edge._pos.resize( 2 );
9875 segLen[ 1 ] = edge._len;
9878 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9880 useNormal = usePos = false;
9881 _LayerEdge tmpEdge; // get original _normal
9882 tmpEdge._nodes.push_back( edge._nodes[0] );
9883 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9886 for ( size_t j = 1; j < edge._pos.size(); ++j )
9887 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9891 for ( size_t j = 1; j < edge._pos.size(); ++j )
9892 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9896 for ( size_t j = 1; j < edge._pos.size(); ++j )
9897 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9901 bool swapped = ( edge._pos.size() > 2 );
9905 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9906 if ( segLen[j] > segLen.back() )
9908 segLen.erase( segLen.begin() + j );
9909 edge._pos.erase( edge._pos.begin() + j );
9912 else if ( segLen[j] < segLen[j-1] )
9914 std::swap( segLen[j], segLen[j-1] );
9915 std::swap( edge._pos[j], edge._pos[j-1] );
9920 // smooth a path formed by edge._pos
9921 #ifndef __NODES_AT_POS
9922 if (( smoothed ) /*&&
9923 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9924 edge.SmoothPos( segLen, preci );
9927 else if ( eos._isRegularSWOL ) // usual SWOL
9929 if ( edge.Is( _LayerEdge::SMOOTHED ))
9931 SMESH_NodeXYZ p0( edge._nodes[0] );
9932 for ( size_t j = 1; j < edge._pos.size(); ++j )
9934 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9935 segLen[j] = ( pj - p0 ) * edge._normal;
9940 for ( size_t j = 1; j < edge._pos.size(); ++j )
9941 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9944 else if ( !surface.IsNull() ) // SWOL surface with singularities
9946 pos3D.resize( edge._pos.size() );
9947 for ( size_t j = 0; j < edge._pos.size(); ++j )
9948 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9950 for ( size_t j = 1; j < edge._pos.size(); ++j )
9951 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9954 // allocate memory for new nodes if it is not yet refined
9955 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9956 if ( edge._nodes.size() == 2 )
9958 #ifdef __NODES_AT_POS
9959 int nbNodes = edge._pos.size();
9961 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9963 edge._nodes.resize( nbNodes, 0 );
9965 edge._nodes.back() = tgtNode;
9967 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9968 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9969 if ( baseShapeId != prevBaseId )
9971 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9972 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9973 prevBaseId = baseShapeId;
9975 _LayerEdge* edgeOnSameNode = 0;
9976 bool useExistingPos = false;
9977 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9979 edgeOnSameNode = n2e->second;
9980 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9981 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9982 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9985 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9986 epos->SetUParameter( otherTgtPos.X() );
9990 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9991 fpos->SetUParameter( otherTgtPos.X() );
9992 fpos->SetVParameter( otherTgtPos.Y() );
9995 // calculate height of the first layer
9997 const double T = segLen.back(); //data._hyp.GetTotalThickness();
9998 const double f = eos._hyp.GetStretchFactor();
9999 const int N = eos._hyp.GetNumberLayers();
10000 const double fPowN = pow( f, N );
10001 if ( fPowN - 1 <= numeric_limits<double>::min() )
10004 h0 = T * ( f - 1 )/( fPowN - 1 );
10006 const double zeroLen = std::numeric_limits<double>::min();
10008 // create intermediate nodes
10009 double hSum = 0, hi = h0/f;
10011 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10013 // compute an intermediate position
10016 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10018 int iPrevSeg = iSeg-1;
10019 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10021 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10022 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10023 #ifdef __NODES_AT_POS
10024 pos = edge._pos[ iStep ];
10026 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10027 if ( !eos._sWOL.IsNull() )
10029 // compute XYZ by parameters <pos>
10034 pos = curve->Value( u ).Transformed(loc);
10036 else if ( eos._isRegularSWOL )
10038 uv.SetCoord( pos.X(), pos.Y() );
10040 pos = surface->Value( pos.X(), pos.Y() );
10044 uv.SetCoord( pos.X(), pos.Y() );
10045 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10046 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10048 pos = surface->Value( uv );
10051 // create or update the node
10054 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10055 if ( !eos._sWOL.IsNull() )
10058 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10060 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10064 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10069 if ( !eos._sWOL.IsNull() )
10071 // make average pos from new and current parameters
10074 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10075 if ( useExistingPos )
10076 u = helper.GetNodeU( geomEdge, node );
10077 pos = curve->Value( u ).Transformed(loc);
10079 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
10080 epos->SetUParameter( u );
10084 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10085 if ( useExistingPos )
10086 uv = helper.GetNodeUV( geomFace, node );
10087 pos = surface->Value( uv );
10089 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
10090 fpos->SetUParameter( uv.X() );
10091 fpos->SetVParameter( uv.Y() );
10094 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10096 } // loop on edge._nodes
10098 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10101 edge._pos.back().SetCoord( u, 0,0);
10103 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10105 if ( edgeOnSameNode )
10106 edgeOnSameNode->_pos.back() = edge._pos.back();
10109 } // loop on eos._edges to create nodes
10112 if ( !getMeshDS()->IsEmbeddedMode() )
10113 // Log node movement
10114 for ( size_t i = 0; i < eos._edges.size(); ++i )
10116 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10117 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10124 helper.SetElementsOnShape(true);
10126 vector< vector<const SMDS_MeshNode*>* > nnVec;
10127 set< vector<const SMDS_MeshNode*>* > nnSet;
10128 set< int > degenEdgeInd;
10129 vector<const SMDS_MeshElement*> degenVols;
10131 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10132 for ( ; exp.More(); exp.Next() )
10134 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10135 if ( data._ignoreFaceIds.count( faceID ))
10137 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10138 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10139 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10140 while ( fIt->more() )
10142 const SMDS_MeshElement* face = fIt->next();
10143 const int nbNodes = face->NbCornerNodes();
10144 nnVec.resize( nbNodes );
10146 degenEdgeInd.clear();
10147 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10148 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10149 for ( int iN = 0; iN < nbNodes; ++iN )
10151 const SMDS_MeshNode* n = nIt->next();
10152 _LayerEdge* edge = data._n2eMap[ n ];
10153 const int i = isReversedFace ? nbNodes-1-iN : iN;
10154 nnVec[ i ] = & edge->_nodes;
10155 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10156 minZ = std::min( minZ, nnVec[ i ]->size() );
10158 if ( helper.HasDegeneratedEdges() )
10159 nnSet.insert( nnVec[ i ]);
10164 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10172 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10173 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10174 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10176 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10178 for ( int iN = 0; iN < nbNodes; ++iN )
10179 if ( nnVec[ iN ]->size() < iZ+1 )
10180 degenEdgeInd.insert( iN );
10182 if ( degenEdgeInd.size() == 1 ) // PYRAM
10184 int i2 = *degenEdgeInd.begin();
10185 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10186 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10187 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10188 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10192 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10193 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10194 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10195 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10196 (*nnVec[ i3 ])[ iZ ]);
10204 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10205 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10206 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10207 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10208 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10210 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10212 for ( int iN = 0; iN < nbNodes; ++iN )
10213 if ( nnVec[ iN ]->size() < iZ+1 )
10214 degenEdgeInd.insert( iN );
10216 switch ( degenEdgeInd.size() )
10220 int i2 = *degenEdgeInd.begin();
10221 int i3 = *degenEdgeInd.rbegin();
10222 bool ok = ( i3 - i2 == 1 );
10223 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10224 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10225 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10227 const SMDS_MeshElement* vol =
10228 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10229 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10231 degenVols.push_back( vol );
10235 default: // degen HEX
10237 const SMDS_MeshElement* vol =
10238 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10239 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10240 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10241 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10242 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10243 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10244 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10245 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10246 degenVols.push_back( vol );
10253 return error("Not supported type of element", data._index);
10255 } // switch ( nbNodes )
10256 } // while ( fIt->more() )
10259 if ( !degenVols.empty() )
10261 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10262 if ( !err || err->IsOK() )
10264 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
10265 "Bad quality volumes created" ));
10266 err->myBadElements.insert( err->myBadElements.end(),
10267 degenVols.begin(),degenVols.end() );
10274 //================================================================================
10276 * \brief Shrink 2D mesh on faces to let space for inflated layers
10278 //================================================================================
10280 bool _ViscousBuilder::shrink(_SolidData& theData)
10282 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10283 // _LayerEdge's inflated along FACE or EDGE)
10284 map< TGeomID, list< _SolidData* > > f2sdMap;
10285 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10287 _SolidData& data = _sdVec[i];
10288 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10289 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10290 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10292 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10294 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10295 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10296 // by StdMeshers_QuadToTriaAdaptor
10297 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10299 SMESH_ProxyMesh::SubMesh* proxySub =
10300 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10301 if ( proxySub->NbElements() == 0 )
10303 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10304 while ( fIt->more() )
10306 const SMDS_MeshElement* f = fIt->next();
10307 // as a result 3D algo will use elements from proxySub and not from smDS
10308 proxySub->AddElement( f );
10309 f->setIsMarked( true );
10311 // Mark nodes on the FACE to discriminate them from nodes
10312 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10313 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10315 const SMDS_MeshNode* n = f->GetNode( iN );
10316 if ( n->GetPosition()->GetDim() == 2 )
10317 n->setIsMarked( true );
10325 SMESH_MesherHelper helper( *_mesh );
10326 helper.ToFixNodeParameters( true );
10329 map< TGeomID, _Shrinker1D > e2shrMap;
10330 vector< _EdgesOnShape* > subEOS;
10331 vector< _LayerEdge* > lEdges;
10333 // loop on FACEs to srink mesh on
10334 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10335 for ( ; f2sd != f2sdMap.end(); ++f2sd )
10337 list< _SolidData* > & dataList = f2sd->second;
10338 if ( dataList.front()->_n2eMap.empty() ||
10339 dataList.back() ->_n2eMap.empty() )
10340 continue; // not yet computed
10341 if ( dataList.front() != &theData &&
10342 dataList.back() != &theData )
10345 _SolidData& data = *dataList.front();
10346 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
10347 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10348 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
10349 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10351 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10353 _shrinkedFaces.Add( F );
10354 helper.SetSubShape( F );
10356 // ===========================
10357 // Prepare data for shrinking
10358 // ===========================
10360 // Collect nodes to smooth (they are marked at the beginning of this method)
10361 vector < const SMDS_MeshNode* > smoothNodes;
10363 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10364 while ( nIt->more() )
10366 const SMDS_MeshNode* n = nIt->next();
10367 if ( n->isMarked() )
10368 smoothNodes.push_back( n );
10371 // Find out face orientation
10372 double refSign = 1;
10373 const set<TGeomID> ignoreShapes;
10375 if ( !smoothNodes.empty() )
10377 vector<_Simplex> simplices;
10378 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10379 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10380 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10381 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10382 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10386 // Find _LayerEdge's inflated along F
10390 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10391 /*complexFirst=*/true); //!!!
10392 while ( subIt->more() )
10394 const TGeomID subID = subIt->next()->GetId();
10395 if ( data._noShrinkShapes.count( subID ))
10397 _EdgesOnShape* eos = data.GetShapeEdges( subID );
10398 if ( !eos || eos->_sWOL.IsNull() )
10399 if ( data2 ) // check in adjacent SOLID
10401 eos = data2->GetShapeEdges( subID );
10402 if ( !eos || eos->_sWOL.IsNull() )
10405 subEOS.push_back( eos );
10407 for ( size_t i = 0; i < eos->_edges.size(); ++i )
10409 lEdges.push_back( eos->_edges[ i ] );
10410 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10415 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10416 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10417 while ( fIt->more() )
10418 if ( const SMDS_MeshElement* f = fIt->next() )
10419 dumpChangeNodes( f );
10422 // Replace source nodes by target nodes in mesh faces to shrink
10423 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10424 const SMDS_MeshNode* nodes[20];
10425 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10427 _EdgesOnShape& eos = * subEOS[ iS ];
10428 for ( size_t i = 0; i < eos._edges.size(); ++i )
10430 _LayerEdge& edge = *eos._edges[i];
10431 const SMDS_MeshNode* srcNode = edge._nodes[0];
10432 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10433 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10434 while ( fIt->more() )
10436 const SMDS_MeshElement* f = fIt->next();
10437 if ( !smDS->Contains( f ) || !f->isMarked() )
10439 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10440 for ( int iN = 0; nIt->more(); ++iN )
10442 const SMDS_MeshNode* n = nIt->next();
10443 nodes[iN] = ( n == srcNode ? tgtNode : n );
10445 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10446 dumpChangeNodes( f );
10452 // find out if a FACE is concave
10453 const bool isConcaveFace = isConcave( F, helper );
10455 // Create _SmoothNode's on face F
10456 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10458 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10459 const bool sortSimplices = isConcaveFace;
10460 for ( size_t i = 0; i < smoothNodes.size(); ++i )
10462 const SMDS_MeshNode* n = smoothNodes[i];
10463 nodesToSmooth[ i ]._node = n;
10464 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10465 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10466 // fix up incorrect uv of nodes on the FACE
10467 helper.GetNodeUV( F, n, 0, &isOkUV);
10472 //if ( nodesToSmooth.empty() ) continue;
10474 // Find EDGE's to shrink and set simpices to LayerEdge's
10475 set< _Shrinker1D* > eShri1D;
10477 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10479 _EdgesOnShape& eos = * subEOS[ iS ];
10480 if ( eos.SWOLType() == TopAbs_EDGE )
10482 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10483 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
10484 eShri1D.insert( & srinker );
10485 srinker.AddEdge( eos._edges[0], eos, helper );
10486 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10487 // restore params of nodes on EGDE if the EDGE has been already
10488 // srinked while srinking other FACE
10489 srinker.RestoreParams();
10491 for ( size_t i = 0; i < eos._edges.size(); ++i )
10493 _LayerEdge& edge = * eos._edges[i];
10494 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10496 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10497 // not-marked nodes are those added by refine()
10498 edge._nodes.back()->setIsMarked( true );
10503 bool toFixTria = false; // to improve quality of trias by diagonal swap
10504 if ( isConcaveFace )
10506 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10507 if ( hasTria != hasQuad ) {
10508 toFixTria = hasTria;
10511 set<int> nbNodesSet;
10512 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10513 while ( fIt->more() && nbNodesSet.size() < 2 )
10514 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10515 toFixTria = ( *nbNodesSet.begin() == 3 );
10519 // ==================
10520 // Perform shrinking
10521 // ==================
10523 bool shrinked = true;
10524 int nbBad, shriStep=0, smooStep=0;
10525 _SmoothNode::SmoothType smoothType
10526 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10527 SMESH_Comment errMsg;
10531 // Move boundary nodes (actually just set new UV)
10532 // -----------------------------------------------
10533 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10535 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10537 _EdgesOnShape& eos = * subEOS[ iS ];
10538 for ( size_t i = 0; i < eos._edges.size(); ++i )
10540 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10545 // Move nodes on EDGE's
10546 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10547 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10548 for ( ; shr != eShri1D.end(); ++shr )
10549 (*shr)->Compute( /*set3D=*/false, helper );
10552 // -----------------
10553 int nbNoImpSteps = 0;
10556 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10558 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10560 int oldBadNb = nbBad;
10563 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10564 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10565 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10567 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10568 smooTy, /*set3D=*/isConcaveFace);
10570 if ( nbBad < oldBadNb )
10580 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10581 if ( shriStep > 200 )
10582 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10583 if ( !errMsg.empty() )
10586 // Fix narrow triangles by swapping diagonals
10587 // ---------------------------------------
10590 set<const SMDS_MeshNode*> usedNodes;
10591 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10593 // update working data
10594 set<const SMDS_MeshNode*>::iterator n;
10595 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10597 n = usedNodes.find( nodesToSmooth[ i ]._node );
10598 if ( n != usedNodes.end())
10600 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10601 nodesToSmooth[ i ]._simplices,
10602 ignoreShapes, NULL,
10603 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10604 usedNodes.erase( n );
10607 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10609 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10610 if ( n != usedNodes.end())
10612 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10613 lEdges[i]->_simplices,
10615 usedNodes.erase( n );
10619 // TODO: check effect of this additional smooth
10620 // additional laplacian smooth to increase allowed shrink step
10621 // for ( int st = 1; st; --st )
10623 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10624 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10626 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10627 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10631 } // while ( shrinked )
10633 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10635 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10638 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10640 vector< const SMDS_MeshElement* > facesToRm;
10643 facesToRm.reserve( psm->NbElements() );
10644 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10645 facesToRm.push_back( ite->next() );
10647 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10648 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10651 for ( size_t i = 0; i < facesToRm.size(); ++i )
10652 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10656 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10657 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10658 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10659 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10660 subEOS[iS]->_edges[i]->_nodes.end() );
10662 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10663 while ( itn->more() ) {
10664 const SMDS_MeshNode* n = itn->next();
10665 if ( !nodesToKeep.count( n ))
10666 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10669 // restore position and UV of target nodes
10671 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10672 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10674 _LayerEdge* edge = subEOS[iS]->_edges[i];
10675 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10676 if ( edge->_pos.empty() ||
10677 edge->Is( _LayerEdge::SHRUNK )) continue;
10678 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10680 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10681 pos->SetUParameter( edge->_pos[0].X() );
10682 pos->SetVParameter( edge->_pos[0].Y() );
10683 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10687 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10688 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10689 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10691 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10692 dumpMove( tgtNode );
10694 // shrink EDGE sub-meshes and set proxy sub-meshes
10695 UVPtStructVec uvPtVec;
10696 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10697 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10699 _Shrinker1D* shr = (*shrIt);
10700 shr->Compute( /*set3D=*/true, helper );
10702 // set proxy mesh of EDGEs w/o layers
10703 map< double, const SMDS_MeshNode* > nodes;
10704 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10705 // remove refinement nodes
10706 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10707 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10708 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10709 if ( u2n->second == sn0 || u2n->second == sn1 )
10711 while ( u2n->second != tn0 && u2n->second != tn1 )
10713 nodes.erase( nodes.begin(), u2n );
10715 u2n = --nodes.end();
10716 if ( u2n->second == sn0 || u2n->second == sn1 )
10718 while ( u2n->second != tn0 && u2n->second != tn1 )
10720 nodes.erase( ++u2n, nodes.end() );
10722 // set proxy sub-mesh
10723 uvPtVec.resize( nodes.size() );
10724 u2n = nodes.begin();
10725 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10726 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10728 uvPtVec[ i ].node = u2n->second;
10729 uvPtVec[ i ].param = u2n->first;
10730 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10732 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10733 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10736 // set proxy mesh of EDGEs with layers
10737 vector< _LayerEdge* > edges;
10738 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10740 _EdgesOnShape& eos = * subEOS[ iS ];
10741 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10743 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10744 data.SortOnEdge( E, eos._edges );
10747 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10748 if ( !eov->_edges.empty() )
10749 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10751 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10753 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10754 if ( !eov->_edges.empty() )
10755 edges.push_back( eov->_edges[0] ); // on last VERTEX
10757 uvPtVec.resize( edges.size() );
10758 for ( size_t i = 0; i < edges.size(); ++i )
10760 uvPtVec[ i ].node = edges[i]->_nodes.back();
10761 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10762 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10764 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10765 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10766 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10768 // temporary clear the FACE sub-mesh from faces made by refine()
10769 vector< const SMDS_MeshElement* > elems;
10770 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10771 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10772 elems.push_back( ite->next() );
10773 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10774 elems.push_back( ite->next() );
10777 // compute the mesh on the FACE
10778 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10779 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10781 // re-fill proxy sub-meshes of the FACE
10782 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10783 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10784 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10785 psm->AddElement( ite->next() );
10788 for ( size_t i = 0; i < elems.size(); ++i )
10789 smDS->AddElement( elems[i] );
10791 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10792 return error( errMsg );
10794 } // end of re-meshing in case of failed smoothing
10797 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10798 bool isStructuredFixed = false;
10799 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10800 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10801 if ( !isStructuredFixed )
10803 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10804 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10806 for ( int st = 3; st; --st )
10809 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10810 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10811 case 3: smoothType = _SmoothNode::ANGULAR; break;
10813 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10814 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10816 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10817 smoothType,/*set3D=*/st==1 );
10822 if ( !getMeshDS()->IsEmbeddedMode() )
10823 // Log node movement
10824 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10826 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10827 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10831 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10832 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10834 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10836 } // loop on FACES to srink mesh on
10839 // Replace source nodes by target nodes in shrinked mesh edges
10841 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10842 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10843 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10848 //================================================================================
10850 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10852 //================================================================================
10854 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10855 _EdgesOnShape& eos,
10856 SMESH_MesherHelper& helper,
10857 const SMESHDS_SubMesh* faceSubMesh)
10859 const SMDS_MeshNode* srcNode = edge._nodes[0];
10860 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10862 if ( eos.SWOLType() == TopAbs_FACE )
10864 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10867 edge.Set( _LayerEdge::SHRUNK );
10868 return srcNode == tgtNode;
10870 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10871 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10872 gp_Vec2d uvDir( srcUV, tgtUV );
10873 double uvLen = uvDir.Magnitude();
10875 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10878 //edge._pos.resize(1);
10879 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10881 // set UV of source node to target node
10882 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10883 pos->SetUParameter( srcUV.X() );
10884 pos->SetVParameter( srcUV.Y() );
10886 else // _sWOL is TopAbs_EDGE
10888 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10891 edge.Set( _LayerEdge::SHRUNK );
10892 return srcNode == tgtNode;
10894 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10895 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10896 if ( !edgeSM || edgeSM->NbElements() == 0 )
10897 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10899 const SMDS_MeshNode* n2 = 0;
10900 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10901 while ( eIt->more() && !n2 )
10903 const SMDS_MeshElement* e = eIt->next();
10904 if ( !edgeSM->Contains(e)) continue;
10905 n2 = e->GetNode( 0 );
10906 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10909 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10911 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10912 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10913 double u2 = helper.GetNodeU( E, n2, srcNode );
10915 //edge._pos.clear();
10917 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10919 // tgtNode is located so that it does not make faces with wrong orientation
10920 edge.Set( _LayerEdge::SHRUNK );
10923 //edge._pos.resize(1);
10924 edge._pos[0].SetCoord( U_TGT, uTgt );
10925 edge._pos[0].SetCoord( U_SRC, uSrc );
10926 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10928 edge._simplices.resize( 1 );
10929 edge._simplices[0]._nPrev = n2;
10931 // set U of source node to the target node
10932 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10933 pos->SetUParameter( uSrc );
10938 //================================================================================
10940 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10942 //================================================================================
10944 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10946 if ( edge._nodes.size() == 1 )
10951 const SMDS_MeshNode* srcNode = edge._nodes[0];
10952 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10953 if ( S.IsNull() ) return;
10957 switch ( S.ShapeType() )
10962 TopLoc_Location loc;
10963 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10964 if ( curve.IsNull() ) return;
10965 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10966 p = curve->Value( ePos->GetUParameter() );
10969 case TopAbs_VERTEX:
10971 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10976 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10977 dumpMove( srcNode );
10981 //================================================================================
10983 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10985 //================================================================================
10987 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10988 SMESH_MesherHelper& helper,
10991 set<const SMDS_MeshNode*> * involvedNodes)
10993 SMESH::Controls::AspectRatio qualifier;
10994 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10995 const double maxAspectRatio = is2D ? 4. : 2;
10996 _NodeCoordHelper xyz( F, helper, is2D );
10998 // find bad triangles
11000 vector< const SMDS_MeshElement* > badTrias;
11001 vector< double > badAspects;
11002 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
11003 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11004 while ( fIt->more() )
11006 const SMDS_MeshElement * f = fIt->next();
11007 if ( f->NbCornerNodes() != 3 ) continue;
11008 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11009 double aspect = qualifier.GetValue( points );
11010 if ( aspect > maxAspectRatio )
11012 badTrias.push_back( f );
11013 badAspects.push_back( aspect );
11018 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11019 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11020 while ( fIt->more() )
11022 const SMDS_MeshElement * f = fIt->next();
11023 if ( f->NbCornerNodes() == 3 )
11024 dumpChangeNodes( f );
11028 if ( badTrias.empty() )
11031 // find couples of faces to swap diagonal
11033 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11034 vector< T2Trias > triaCouples;
11036 TIDSortedElemSet involvedFaces, emptySet;
11037 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11040 double aspRatio [3];
11043 if ( !involvedFaces.insert( badTrias[iTia] ).second )
11045 for ( int iP = 0; iP < 3; ++iP )
11046 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11048 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11049 int bestCouple = -1;
11050 for ( int iSide = 0; iSide < 3; ++iSide )
11052 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11053 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11054 trias [iSide].first = badTrias[iTia];
11055 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11057 if (( ! trias[iSide].second ) ||
11058 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11059 ( ! sm->Contains( trias[iSide].second )))
11062 // aspect ratio of an adjacent tria
11063 for ( int iP = 0; iP < 3; ++iP )
11064 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11065 double aspectInit = qualifier.GetValue( points2 );
11067 // arrange nodes as after diag-swaping
11068 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11069 i3 = helper.WrapIndex( i1-1, 3 );
11071 i3 = helper.WrapIndex( i1+1, 3 );
11073 points1( 1+ iSide ) = points2( 1+ i3 );
11074 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
11076 // aspect ratio after diag-swaping
11077 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11078 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11081 // prevent inversion of a triangle
11082 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11083 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11084 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11087 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11088 bestCouple = iSide;
11091 if ( bestCouple >= 0 )
11093 triaCouples.push_back( trias[bestCouple] );
11094 involvedFaces.insert ( trias[bestCouple].second );
11098 involvedFaces.erase( badTrias[iTia] );
11101 if ( triaCouples.empty() )
11106 SMESH_MeshEditor editor( helper.GetMesh() );
11107 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11108 for ( size_t i = 0; i < triaCouples.size(); ++i )
11110 dumpChangeNodes( triaCouples[i].first );
11111 dumpChangeNodes( triaCouples[i].second );
11112 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11115 if ( involvedNodes )
11116 for ( size_t i = 0; i < triaCouples.size(); ++i )
11118 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11119 triaCouples[i].first->end_nodes() );
11120 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11121 triaCouples[i].second->end_nodes() );
11124 // just for debug dump resulting triangles
11125 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11126 for ( size_t i = 0; i < triaCouples.size(); ++i )
11128 dumpChangeNodes( triaCouples[i].first );
11129 dumpChangeNodes( triaCouples[i].second );
11133 //================================================================================
11135 * \brief Move target node to it's final position on the FACE during shrinking
11137 //================================================================================
11139 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11140 const TopoDS_Face& F,
11141 _EdgesOnShape& eos,
11142 SMESH_MesherHelper& helper )
11145 return false; // already at the target position
11147 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11149 if ( eos.SWOLType() == TopAbs_FACE )
11151 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
11152 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11153 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11154 const double uvLen = tgtUV.Distance( curUV );
11155 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11157 // Select shrinking step such that not to make faces with wrong orientation.
11158 double stepSize = 1e100;
11159 for ( size_t i = 0; i < _simplices.size(); ++i )
11161 if ( !_simplices[i]._nPrev->isMarked() ||
11162 !_simplices[i]._nNext->isMarked() )
11163 continue; // simplex of quadrangle created by addBoundaryElements()
11165 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11166 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11167 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11168 gp_XY dirN = uvN2 - uvN1;
11169 double det = uvDir.Crossed( dirN );
11170 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
11171 gp_XY dirN2Cur = curUV - uvN1;
11172 double step = dirN.Crossed( dirN2Cur ) / det;
11174 stepSize = Min( step, stepSize );
11177 if ( uvLen <= stepSize )
11183 else if ( stepSize > 0 )
11185 newUV = curUV + uvDir.XY() * stepSize * kSafe;
11191 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
11192 pos->SetUParameter( newUV.X() );
11193 pos->SetVParameter( newUV.Y() );
11196 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11197 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11198 dumpMove( tgtNode );
11201 else // _sWOL is TopAbs_EDGE
11203 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11204 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
11205 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
11207 const double u2 = helper.GetNodeU( E, n2, tgtNode );
11208 const double uSrc = _pos[0].Coord( U_SRC );
11209 const double lenTgt = _pos[0].Coord( LEN_TGT );
11211 double newU = _pos[0].Coord( U_TGT );
11212 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11214 Set( _LayerEdge::SHRUNK );
11219 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11221 tgtPos->SetUParameter( newU );
11223 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11224 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11225 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11226 dumpMove( tgtNode );
11233 //================================================================================
11235 * \brief Perform smooth on the FACE
11236 * \retval bool - true if the node has been moved
11238 //================================================================================
11240 bool _SmoothNode::Smooth(int& nbBad,
11241 Handle(Geom_Surface)& surface,
11242 SMESH_MesherHelper& helper,
11243 const double refSign,
11247 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11249 // get uv of surrounding nodes
11250 vector<gp_XY> uv( _simplices.size() );
11251 for ( size_t i = 0; i < _simplices.size(); ++i )
11252 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11254 // compute new UV for the node
11255 gp_XY newPos (0,0);
11256 if ( how == TFI && _simplices.size() == 4 )
11259 for ( size_t i = 0; i < _simplices.size(); ++i )
11260 if ( _simplices[i]._nOpp )
11261 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11263 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11265 newPos = helper.calcTFI ( 0.5, 0.5,
11266 corners[0], corners[1], corners[2], corners[3],
11267 uv[1], uv[2], uv[3], uv[0] );
11269 else if ( how == ANGULAR )
11271 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11273 else if ( how == CENTROIDAL && _simplices.size() > 3 )
11275 // average centers of diagonals wieghted with their reciprocal lengths
11276 if ( _simplices.size() == 4 )
11278 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11279 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11280 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11284 double sumWeight = 0;
11285 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11286 for ( int i = 0; i < nb; ++i )
11289 int iTo = i + _simplices.size() - 1;
11290 for ( int j = iFrom; j < iTo; ++j )
11292 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11293 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11295 newPos += w * ( uv[i]+uv[i2] );
11298 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11303 // Laplacian smooth
11304 for ( size_t i = 0; i < _simplices.size(); ++i )
11306 newPos /= _simplices.size();
11309 // count quality metrics (orientation) of triangles around the node
11310 int nbOkBefore = 0;
11311 gp_XY tgtUV = helper.GetNodeUV( face, _node );
11312 for ( size_t i = 0; i < _simplices.size(); ++i )
11313 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11316 for ( size_t i = 0; i < _simplices.size(); ++i )
11317 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11319 if ( nbOkAfter < nbOkBefore )
11321 nbBad += _simplices.size() - nbOkBefore;
11325 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
11326 pos->SetUParameter( newPos.X() );
11327 pos->SetVParameter( newPos.Y() );
11334 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11335 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11339 nbBad += _simplices.size() - nbOkAfter;
11340 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11343 //================================================================================
11345 * \brief Computes new UV using angle based smoothing technic
11347 //================================================================================
11349 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11350 const gp_XY& uvToFix,
11351 const double refSign)
11353 uv.push_back( uv.front() );
11355 vector< gp_XY > edgeDir ( uv.size() );
11356 vector< double > edgeSize( uv.size() );
11357 for ( size_t i = 1; i < edgeDir.size(); ++i )
11359 edgeDir [i-1] = uv[i] - uv[i-1];
11360 edgeSize[i-1] = edgeDir[i-1].Modulus();
11361 if ( edgeSize[i-1] < numeric_limits<double>::min() )
11362 edgeDir[i-1].SetX( 100 );
11364 edgeDir[i-1] /= edgeSize[i-1] * refSign;
11366 edgeDir.back() = edgeDir.front();
11367 edgeSize.back() = edgeSize.front();
11371 double sumSize = 0;
11372 for ( size_t i = 1; i < edgeDir.size(); ++i )
11374 if ( edgeDir[i-1].X() > 1. ) continue;
11376 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11377 if ( i == edgeDir.size() ) break;
11379 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11380 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
11381 gp_XY bisec = norm1 + norm2;
11382 double bisecSize = bisec.Modulus();
11383 if ( bisecSize < numeric_limits<double>::min() )
11385 bisec = -edgeDir[i1] + edgeDir[i];
11386 bisecSize = bisec.Modulus();
11388 bisec /= bisecSize;
11390 gp_XY dirToN = uvToFix - p;
11391 double distToN = dirToN.Modulus();
11392 if ( bisec * dirToN < 0 )
11393 distToN = -distToN;
11395 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11397 sumSize += edgeSize[i1] + edgeSize[i];
11399 newPos /= /*nbEdges * */sumSize;
11403 //================================================================================
11405 * \brief Delete _SolidData
11407 //================================================================================
11409 _SolidData::~_SolidData()
11411 TNode2Edge::iterator n2e = _n2eMap.begin();
11412 for ( ; n2e != _n2eMap.end(); ++n2e )
11414 _LayerEdge* & e = n2e->second;
11417 delete e->_curvature;
11418 if ( e->_2neibors )
11419 delete e->_2neibors->_plnNorm;
11420 delete e->_2neibors;
11431 //================================================================================
11433 * \brief Keep a _LayerEdge inflated along the EDGE
11435 //================================================================================
11437 void _Shrinker1D::AddEdge( const _LayerEdge* e,
11438 _EdgesOnShape& eos,
11439 SMESH_MesherHelper& helper )
11442 if ( _nodes.empty() )
11444 _edges[0] = _edges[1] = 0;
11447 // check _LayerEdge
11448 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11450 if ( eos.SWOLType() != TopAbs_EDGE )
11451 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11452 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11453 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11455 // store _LayerEdge
11456 _geomEdge = TopoDS::Edge( eos._sWOL );
11458 BRep_Tool::Range( _geomEdge, f,l );
11459 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11460 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11464 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11465 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11467 if ( _nodes.empty() )
11469 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11470 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11472 TopLoc_Location loc;
11473 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11474 GeomAdaptor_Curve aCurve(C, f,l);
11475 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11477 int nbExpectNodes = eSubMesh->NbNodes();
11478 _initU .reserve( nbExpectNodes );
11479 _normPar.reserve( nbExpectNodes );
11480 _nodes .reserve( nbExpectNodes );
11481 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11482 while ( nIt->more() )
11484 const SMDS_MeshNode* node = nIt->next();
11486 // skip refinement nodes
11487 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11488 node == tgtNode0 || node == tgtNode1 )
11490 bool hasMarkedFace = false;
11491 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11492 while ( fIt->more() && !hasMarkedFace )
11493 hasMarkedFace = fIt->next()->isMarked();
11494 if ( !hasMarkedFace )
11497 _nodes.push_back( node );
11498 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11499 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11500 _normPar.push_back( len / totLen );
11505 // remove target node of the _LayerEdge from _nodes
11506 size_t nbFound = 0;
11507 for ( size_t i = 0; i < _nodes.size(); ++i )
11508 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11509 _nodes[i] = 0, nbFound++;
11510 if ( nbFound == _nodes.size() )
11515 //================================================================================
11517 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11519 //================================================================================
11521 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11523 if ( _done || _nodes.empty())
11525 const _LayerEdge* e = _edges[0];
11526 if ( !e ) e = _edges[1];
11529 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11530 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11533 if ( set3D || _done )
11535 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11536 GeomAdaptor_Curve aCurve(C, f,l);
11539 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11541 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11542 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11544 for ( size_t i = 0; i < _nodes.size(); ++i )
11546 if ( !_nodes[i] ) continue;
11547 double len = totLen * _normPar[i];
11548 GCPnts_AbscissaPoint discret( aCurve, len, f );
11549 if ( !discret.IsDone() )
11550 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11551 double u = discret.Parameter();
11552 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11553 pos->SetUParameter( u );
11554 gp_Pnt p = C->Value( u );
11555 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11560 BRep_Tool::Range( _geomEdge, f,l );
11562 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11564 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11566 for ( size_t i = 0; i < _nodes.size(); ++i )
11568 if ( !_nodes[i] ) continue;
11569 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11570 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11571 pos->SetUParameter( u );
11576 //================================================================================
11578 * \brief Restore initial parameters of nodes on EDGE
11580 //================================================================================
11582 void _Shrinker1D::RestoreParams()
11585 for ( size_t i = 0; i < _nodes.size(); ++i )
11587 if ( !_nodes[i] ) continue;
11588 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11589 pos->SetUParameter( _initU[i] );
11594 //================================================================================
11596 * \brief Replace source nodes by target nodes in shrinked mesh edges
11598 //================================================================================
11600 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11602 const SMDS_MeshNode* nodes[3];
11603 for ( int i = 0; i < 2; ++i )
11605 if ( !_edges[i] ) continue;
11607 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11608 if ( !eSubMesh ) return;
11609 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11610 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11611 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11612 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11613 while ( eIt->more() )
11615 const SMDS_MeshElement* e = eIt->next();
11616 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11618 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11619 for ( int iN = 0; iN < e->NbNodes(); ++iN )
11621 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11622 nodes[iN] = ( n == srcNode ? tgtNode : n );
11624 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11629 //================================================================================
11631 * \brief Creates 2D and 1D elements on boundaries of new prisms
11633 //================================================================================
11635 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11637 SMESH_MesherHelper helper( *_mesh );
11639 vector< const SMDS_MeshNode* > faceNodes;
11641 //for ( size_t i = 0; i < _sdVec.size(); ++i )
11643 //_SolidData& data = _sdVec[i];
11644 TopTools_IndexedMapOfShape geomEdges;
11645 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11646 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11648 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11649 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11650 if ( data._noShrinkShapes.count( edgeID ))
11653 // Get _LayerEdge's based on E
11655 map< double, const SMDS_MeshNode* > u2nodes;
11656 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11659 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11660 TNode2Edge & n2eMap = data._n2eMap;
11661 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11663 //check if 2D elements are needed on E
11664 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11665 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11666 ledges.push_back( n2e->second );
11668 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11669 continue; // no layers on E
11670 ledges.push_back( n2eMap[ u2n->second ]);
11672 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11673 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11674 int nbSharedPyram = 0;
11675 SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
11676 while ( vIt->more() )
11678 const SMDS_MeshElement* v = vIt->next();
11679 nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
11681 if ( nbSharedPyram > 1 )
11682 continue; // not free border of the pyramid
11685 faceNodes.push_back( ledges[0]->_nodes[0] );
11686 faceNodes.push_back( ledges[1]->_nodes[0] );
11687 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11688 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11690 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11691 continue; // faces already created
11693 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11694 ledges.push_back( n2eMap[ u2n->second ]);
11696 // Find out orientation and type of face to create
11698 bool reverse = false, isOnFace;
11701 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11702 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11704 F = e2f->second.Oriented( TopAbs_FORWARD );
11705 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11706 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11707 reverse = !reverse, F.Reverse();
11708 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11709 reverse = !reverse;
11711 else if ( !data._ignoreFaceIds.count( e2f->first ))
11713 // find FACE with layers sharing E
11714 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11716 F = *( fIt->next() );
11718 // Find the sub-mesh to add new faces
11719 SMESHDS_SubMesh* sm = 0;
11721 sm = getMeshDS()->MeshElements( F );
11723 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11725 return error("error in addBoundaryElements()", data._index);
11727 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11728 // faces for 3D meshing (PAL23414)
11729 SMESHDS_SubMesh* adjSM = 0;
11732 const TGeomID faceID = sm->GetID();
11733 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11734 while ( const TopoDS_Shape* solid = soIt->next() )
11735 if ( !solid->IsSame( data._solid ))
11737 size_t iData = _solids.FindIndex( *solid ) - 1;
11738 if ( iData < _sdVec.size() &&
11739 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11740 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11742 SMESH_ProxyMesh::SubMesh* proxySub =
11743 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11744 if ( proxySub && proxySub->NbElements() > 0 )
11751 const int dj1 = reverse ? 0 : 1;
11752 const int dj2 = reverse ? 1 : 0;
11753 vector< const SMDS_MeshElement*> ff; // new faces row
11754 SMESHDS_Mesh* m = getMeshDS();
11755 for ( size_t j = 1; j < ledges.size(); ++j )
11757 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11758 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11759 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11760 if ( nn1.size() == nn2.size() )
11763 for ( size_t z = 1; z < nn1.size(); ++z )
11764 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11766 for ( size_t z = 1; z < nn1.size(); ++z )
11767 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11769 else if ( nn1.size() == 1 )
11772 for ( size_t z = 1; z < nn2.size(); ++z )
11773 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11775 for ( size_t z = 1; z < nn2.size(); ++z )
11776 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11781 for ( size_t z = 1; z < nn1.size(); ++z )
11782 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11784 for ( size_t z = 1; z < nn1.size(); ++z )
11785 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11788 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11790 for ( size_t z = 0; z < ff.size(); ++z )
11792 adjSM->AddElement( ff[ z ]);
11798 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11800 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11801 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11802 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11804 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11805 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11807 helper.SetSubShape( eos->_sWOL );
11808 helper.SetElementsOnShape( true );
11809 for ( size_t z = 1; z < nn.size(); ++z )
11810 helper.AddEdge( nn[z-1], nn[z] );
11814 } // loop on EDGE's
11815 } // loop on _SolidData's