1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
109 //================================================================================
114 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
116 const double theMinSmoothCosin = 0.1;
117 const double theSmoothThickToElemSizeRatio = 0.3;
118 const double theMinSmoothTriaAngle = 30;
119 const double theMinSmoothQuadAngle = 45;
121 // what part of thickness is allowed till intersection
122 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123 const double theThickToIntersection = 1.5;
125 bool needSmoothing( double cosin, double tgtThick, double elemSize )
127 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
129 double getSmoothingThickness( double cosin, double elemSize )
131 return theSmoothThickToElemSizeRatio * elemSize / cosin;
135 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
138 struct _MeshOfSolid : public SMESH_ProxyMesh,
139 public SMESH_subMeshEventListenerData
141 bool _n2nMapComputed;
142 SMESH_ComputeErrorPtr _warning;
144 _MeshOfSolid( SMESH_Mesh* mesh)
145 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
147 SMESH_ProxyMesh::setMesh( *mesh );
150 // returns submesh for a geom face
151 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
153 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
156 void setNode2Node(const SMDS_MeshNode* srcNode,
157 const SMDS_MeshNode* proxyNode,
158 const SMESH_ProxyMesh::SubMesh* subMesh)
160 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
163 //--------------------------------------------------------------------------------
165 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166 * It is used to clear an inferior dim sub-meshes modified by viscous layers
168 class _ShrinkShapeListener : SMESH_subMeshEventListener
170 _ShrinkShapeListener()
171 : SMESH_subMeshEventListener(/*isDeletable=*/false,
172 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
174 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175 virtual void ProcessEvent(const int event,
177 SMESH_subMesh* solidSM,
178 SMESH_subMeshEventListenerData* data,
179 const SMESH_Hypothesis* hyp)
181 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
183 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
187 //--------------------------------------------------------------------------------
189 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191 * delete the data as soon as it has been used
193 class _ViscousListener : SMESH_subMeshEventListener
196 SMESH_subMeshEventListener(/*isDeletable=*/false,
197 "StdMeshers_ViscousLayers::_ViscousListener") {}
198 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
200 virtual void ProcessEvent(const int event,
202 SMESH_subMesh* subMesh,
203 SMESH_subMeshEventListenerData* data,
204 const SMESH_Hypothesis* hyp)
206 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
207 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208 SMESH_subMesh::SUBMESH_COMPUTED != event ))
210 // delete SMESH_ProxyMesh containing temporary faces
211 subMesh->DeleteEventListener( this );
214 // Finds or creates proxy mesh of the solid
215 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
216 const TopoDS_Shape& solid,
219 if ( !mesh ) return 0;
220 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222 if ( !data && toCreate )
224 data = new _MeshOfSolid(mesh);
225 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226 sm->SetEventListener( Get(), data, sm );
230 // Removes proxy mesh of the solid
231 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
233 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
237 //================================================================================
239 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240 * the main shape when sub-mesh of the main shape is cleared,
241 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
244 //================================================================================
246 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
248 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249 SMESH_subMeshEventListenerData* data =
250 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
253 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254 data->mySubMeshes.end())
255 data->mySubMeshes.push_back( sub );
259 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
264 //--------------------------------------------------------------------------------
266 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268 * The class is used to check validity of face or volumes around a smoothed node;
269 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
273 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275 _Simplex(const SMDS_MeshNode* nPrev=0,
276 const SMDS_MeshNode* nNext=0,
277 const SMDS_MeshNode* nOpp=0)
278 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
281 const double M[3][3] =
282 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285 vol = ( + M[0][0] * M[1][1] * M[2][2]
286 + M[0][1] * M[1][2] * M[2][0]
287 + M[0][2] * M[1][0] * M[2][1]
288 - M[0][0] * M[1][2] * M[2][1]
289 - M[0][1] * M[1][0] * M[2][2]
290 - M[0][2] * M[1][1] * M[2][0]);
293 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
295 SMESH_TNodeXYZ pSrc( nSrc );
296 return IsForward( &pSrc, &pTgt, vol );
298 bool IsForward(const gp_XY& tgtUV,
299 const SMDS_MeshNode* smoothedNode,
300 const TopoDS_Face& face,
301 SMESH_MesherHelper& helper,
302 const double refSign) const
304 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
308 return d*refSign > 1e-100;
310 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
312 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313 if ( !_nOpp ) // triangle
315 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316 double tp2 = tp.SquareMagnitude();
317 double pn2 = pn.SquareMagnitude();
318 double nt2 = nt.SquareMagnitude();
320 if ( tp2 < pn2 && tp2 < nt2 )
321 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322 else if ( pn2 < nt2 )
323 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
325 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
327 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329 return minAngle < theMaxCos2;
333 SMESH_TNodeXYZ pOpp( _nOpp );
334 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335 double tp2 = tp.SquareMagnitude();
336 double po2 = po.SquareMagnitude();
337 double on2 = on.SquareMagnitude();
338 double nt2 = nt.SquareMagnitude();
339 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
344 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346 return minAngle < theMaxCos2;
349 bool IsNeighbour(const _Simplex& other) const
351 return _nPrev == other._nNext || _nNext == other._nPrev;
353 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354 static void GetSimplices( const SMDS_MeshNode* node,
355 vector<_Simplex>& simplices,
356 const set<TGeomID>& ingnoreShapes,
357 const _SolidData* dataToCheckOri = 0,
358 const bool toSort = false);
359 static void SortSimplices(vector<_Simplex>& simplices);
361 //--------------------------------------------------------------------------------
363 * Structure used to take into account surface curvature while smoothing
368 double _k; // factor to correct node smoothed position
369 double _h2lenRatio; // avgNormProj / (2*avgDist)
370 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
372 static _Curvature* New( double avgNormProj, double avgDist )
375 if ( fabs( avgNormProj / avgDist ) > 1./200 )
378 c->_r = avgDist * avgDist / avgNormProj;
379 c->_k = avgDist * avgDist / c->_r / c->_r;
380 //c->_k = avgNormProj / c->_r;
381 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
384 c->_uv.SetCoord( 0., 0. );
388 double lenDelta(double len) const { return _k * ( _r + len ); }
389 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
391 //--------------------------------------------------------------------------------
395 struct _EdgesOnShape;
397 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
399 //--------------------------------------------------------------------------------
401 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402 * and a node of the most internal layer (_nodes.back())
406 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
408 vector< const SMDS_MeshNode*> _nodes;
410 gp_XYZ _normal; // to boundary of solid
411 vector<gp_XYZ> _pos; // points computed during inflation
412 double _len; // length achived with the last inflation step
413 double _maxLen; // maximal possible length
414 double _cosin; // of angle (_normal ^ surface)
415 double _minAngle; // of _simplices
416 double _lenFactor; // to compute _len taking _cosin into account
419 // simplices connected to the source node (_nodes[0]);
420 // used for smoothing and quality check of _LayerEdge's based on the FACE
421 vector<_Simplex> _simplices;
422 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423 PSmooFun _smooFunction; // smoothing function
424 _Curvature* _curvature;
425 // data for smoothing of _LayerEdge's based on the EDGE
426 _2NearEdges* _2neibors;
428 enum EFlags { TO_SMOOTH = 0x0000001,
429 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
430 SMOOTHED = 0x0000004, // set by this->Smooth()
431 DIFFICULT = 0x0000008, // near concave VERTEX
432 ON_CONCAVE_FACE = 0x0000010,
433 BLOCKED = 0x0000020, // not to inflate any more
434 INTERSECTED = 0x0000040, // close intersection with a face found
435 NORMAL_UPDATED = 0x0000080,
436 MARKED = 0x0000100, // local usage
437 MULTI_NORMAL = 0x0000200, // a normal is invisible by some of surrounding faces
438 NEAR_BOUNDARY = 0x0000400, // is near FACE boundary forcing smooth
439 SMOOTHED_C1 = 0x0000800, // is on _eosC1
440 DISTORTED = 0x0001000, // was bad before smoothing
441 RISKY_SWOL = 0x0002000, // SWOL is parallel to a source FACE
442 UNUSED_FLAG = 0x0100000
444 bool Is ( int flag ) const { return _flags & flag; }
445 void Set ( int flag ) { _flags |= flag; }
446 void Unset( int flag ) { _flags &= ~flag; }
448 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
449 bool SetNewLength2d( Handle(Geom_Surface)& surface,
450 const TopoDS_Face& F,
452 SMESH_MesherHelper& helper );
453 void SetDataByNeighbors( const SMDS_MeshNode* n1,
454 const SMDS_MeshNode* n2,
455 const _EdgesOnShape& eos,
456 SMESH_MesherHelper& helper);
457 void Block( _SolidData& data );
458 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
459 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
460 const TNode2Edge& n2eMap);
461 void SmoothPos( const vector< double >& segLen, const double tol );
462 int GetSmoothedPos( const double tol );
463 int Smooth(const int step, const bool isConcaveFace, bool findBest);
464 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
465 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
466 void SmoothWoCheck();
467 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
468 const TopoDS_Face& F,
469 SMESH_MesherHelper& helper);
470 void MoveNearConcaVer( const _EdgesOnShape* eov,
471 const _EdgesOnShape* eos,
473 vector< _LayerEdge* > & badSmooEdges);
474 bool FindIntersection( SMESH_ElementSearcher& searcher,
476 const double& epsilon,
478 const SMDS_MeshElement** face = 0);
479 bool SegTriaInter( const gp_Ax1& lastSegment,
484 const double& epsilon) const;
485 bool SegTriaInter( const gp_Ax1& lastSegment,
486 const SMDS_MeshNode* n0,
487 const SMDS_MeshNode* n1,
488 const SMDS_MeshNode* n2,
490 const double& epsilon) const
491 { return SegTriaInter( lastSegment,
492 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
495 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
496 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
497 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
498 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
499 bool IsOnEdge() const { return _2neibors; }
500 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
501 void SetCosin( double cosin );
502 void SetNormal( const gp_XYZ& n ) { _normal = n; }
503 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
504 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
505 void SetSmooLen( double len ) { // set _len at which smoothing is needed
506 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
508 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
510 gp_XYZ smoothLaplacian();
511 gp_XYZ smoothAngular();
512 gp_XYZ smoothLengthWeighted();
513 gp_XYZ smoothCentroidal();
514 gp_XYZ smoothNefPolygon();
516 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
517 static const int theNbSmooFuns = FUN_NB;
518 static PSmooFun _funs[theNbSmooFuns];
519 static const char* _funNames[theNbSmooFuns+1];
520 int smooFunID( PSmooFun fun=0) const;
522 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
523 &_LayerEdge::smoothLengthWeighted,
524 &_LayerEdge::smoothCentroidal,
525 &_LayerEdge::smoothNefPolygon,
526 &_LayerEdge::smoothAngular };
527 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
535 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
537 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
538 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
541 //--------------------------------------------------------------------------------
543 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
547 gp_XY _pos, _dir, _inNorm;
548 bool IsOut( const gp_XY p, const double tol ) const
550 return _inNorm * ( p - _pos ) < -tol;
552 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
554 //const double eps = 1e-10;
555 double D = _dir.Crossed( hp._dir );
556 if ( fabs(D) < std::numeric_limits<double>::min())
558 gp_XY vec21 = _pos - hp._pos;
559 double u = hp._dir.Crossed( vec21 ) / D;
560 intPnt = _pos + _dir * u;
564 //--------------------------------------------------------------------------------
566 * Structure used to smooth a _LayerEdge based on an EDGE.
570 double _wgt [2]; // weights of _nodes
571 _LayerEdge* _edges[2];
573 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
576 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
577 const SMDS_MeshNode* tgtNode(bool is2nd) {
578 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
580 const SMDS_MeshNode* srcNode(bool is2nd) {
581 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
584 std::swap( _wgt [0], _wgt [1] );
585 std::swap( _edges[0], _edges[1] );
587 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
588 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
590 bool include( const _LayerEdge* e ) {
591 return ( _edges[0] == e || _edges[1] == e );
596 //--------------------------------------------------------------------------------
598 * \brief Layers parameters got by averaging several hypotheses
602 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
603 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
607 void Add( const StdMeshers_ViscousLayers* hyp )
612 _nbLayers = hyp->GetNumberLayers();
613 //_thickness += hyp->GetTotalThickness();
614 _thickness = Max( _thickness, hyp->GetTotalThickness() );
615 _stretchFactor += hyp->GetStretchFactor();
616 _method = hyp->GetMethod();
619 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621 int GetNumberLayers() const { return _nbLayers; }
622 int GetMethod() const { return _method; }
624 bool UseSurfaceNormal() const
625 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
626 bool ToSmooth() const
627 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628 bool IsOffsetMethod() const
629 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
632 int _nbLayers, _nbHyps, _method;
633 double _thickness, _stretchFactor;
636 //--------------------------------------------------------------------------------
638 * \brief _LayerEdge's on a shape and other shape data
642 vector< _LayerEdge* > _edges;
646 SMESH_subMesh * _subMesh;
647 // face or edge w/o layer along or near which _edges are inflated
649 bool _isRegularSWOL; // w/o singularities
650 // averaged StdMeshers_ViscousLayers parameters
653 _Smoother1D* _edgeSmoother;
654 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
655 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
657 vector< gp_XYZ > _faceNormals; // if _shape is FACE
658 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
660 Handle(ShapeAnalysis_Surface) _offsetSurf;
661 _LayerEdge* _edgeForOffset;
663 _SolidData* _data; // parent SOLID
665 TopAbs_ShapeEnum ShapeType() const
666 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
667 TopAbs_ShapeEnum SWOLType() const
668 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
669 bool HasC1( const _EdgesOnShape* other ) const
670 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
671 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
672 _SolidData& GetData() const { return *_data; }
674 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
677 //--------------------------------------------------------------------------------
679 * \brief Convex FACE whose radius of curvature is less than the thickness of
680 * layers. It is used to detect distortion of prisms based on a convex
681 * FACE and to update normals to enable further increasing the thickness
687 // edges whose _simplices are used to detect prism distortion
688 vector< _LayerEdge* > _simplexTestEdges;
690 // map a sub-shape to _SolidData::_edgesOnShape
691 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
695 bool GetCenterOfCurvature( _LayerEdge* ledge,
696 BRepLProp_SLProps& surfProp,
697 SMESH_MesherHelper& helper,
698 gp_Pnt & center ) const;
699 bool CheckPrisms() const;
702 //--------------------------------------------------------------------------------
704 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
705 * at inflation up to the full thickness. A detected collision
706 * is fixed in updateNormals()
708 struct _CollisionEdges
711 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
712 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
713 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
716 //--------------------------------------------------------------------------------
718 * \brief Data of a SOLID
722 typedef const StdMeshers_ViscousLayers* THyp;
724 TGeomID _index; // SOLID id
725 _MeshOfSolid* _proxyMesh;
727 list< TopoDS_Shape > _hypShapes;
728 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
729 set< TGeomID > _reversedFaceIds;
730 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
732 double _stepSize, _stepSizeCoeff, _geomSize;
733 const SMDS_MeshNode* _stepSizeNodes[2];
735 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
737 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
738 map< TGeomID, TNode2Edge* > _s2neMap;
739 // _LayerEdge's with underlying shapes
740 vector< _EdgesOnShape > _edgesOnShape;
742 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
743 // layers and a FACE w/o layers
744 // value: the shape (FACE or EDGE) to shrink mesh on.
745 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
746 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
748 // Convex FACEs whose radius of curvature is less than the thickness of layers
749 map< TGeomID, _ConvexFace > _convexFaces;
751 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
752 // the adjacent SOLID
753 set< TGeomID > _noShrinkShapes;
755 int _nbShapesToSmooth;
757 //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
759 vector< _CollisionEdges > _collisionEdges;
760 set< TGeomID > _concaveFaces;
762 double _maxThickness; // of all _hyps
763 double _minThickness; // of all _hyps
765 double _epsilon; // precision for SegTriaInter()
767 SMESH_MesherHelper* _helper;
769 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
771 :_solid(s), _proxyMesh(m), _helper(0) {}
774 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
775 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
777 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
778 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
779 return id2face == _convexFaces.end() ? 0 : & id2face->second;
781 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
782 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
783 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
784 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
786 SMESH_MesherHelper& GetHelper() const { return *_helper; }
788 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
789 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
790 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
791 _edgesOnShape[i]._edges[j]->Unset( flag );
793 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
794 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
796 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
798 //--------------------------------------------------------------------------------
800 * \brief Offset plane used in getNormalByOffset()
806 int _faceIndexNext[2];
807 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
810 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
812 void ComputeIntersectionLine( _OffsetPlane& pln,
813 const TopoDS_Edge& E,
814 const TopoDS_Vertex& V );
815 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
816 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
818 //--------------------------------------------------------------------------------
820 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
822 struct _CentralCurveOnEdge
825 vector< gp_Pnt > _curvaCenters;
826 vector< _LayerEdge* > _ledges;
827 vector< gp_XYZ > _normals; // new normal for each of _ledges
828 vector< double > _segLength2;
831 TopoDS_Face _adjFace;
832 bool _adjFaceToSmooth;
834 void Append( const gp_Pnt& center, _LayerEdge* ledge )
836 if ( _curvaCenters.size() > 0 )
837 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
838 _curvaCenters.push_back( center );
839 _ledges.push_back( ledge );
840 _normals.push_back( ledge->_normal );
842 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
843 void SetShapes( const TopoDS_Edge& edge,
844 const _ConvexFace& convFace,
846 SMESH_MesherHelper& helper);
848 //--------------------------------------------------------------------------------
850 * \brief Data of node on a shrinked FACE
854 const SMDS_MeshNode* _node;
855 vector<_Simplex> _simplices; // for quality check
857 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
859 bool Smooth(int& badNb,
860 Handle(Geom_Surface)& surface,
861 SMESH_MesherHelper& helper,
862 const double refSign,
866 gp_XY computeAngularPos(vector<gp_XY>& uv,
867 const gp_XY& uvToFix,
868 const double refSign );
870 //--------------------------------------------------------------------------------
872 * \brief Builder of viscous layers
874 class _ViscousBuilder
879 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
880 const TopoDS_Shape& shape);
881 // check validity of hypotheses
882 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
883 const TopoDS_Shape& shape );
885 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
886 void RestoreListeners();
888 // computes SMESH_ProxyMesh::SubMesh::_n2n;
889 bool MakeN2NMap( _MeshOfSolid* pm );
893 bool findSolidsWithLayers();
894 bool findFacesWithLayers(const bool onlyWith=false);
895 void getIgnoreFaces(const TopoDS_Shape& solid,
896 const StdMeshers_ViscousLayers* hyp,
897 const TopoDS_Shape& hypShape,
898 set<TGeomID>& ignoreFaces);
899 bool makeLayer(_SolidData& data);
900 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
901 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
902 SMESH_MesherHelper& helper, _SolidData& data);
903 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
904 const TopoDS_Face& face,
905 SMESH_MesherHelper& helper,
907 bool shiftInside=false);
908 bool getFaceNormalAtSingularity(const gp_XY& uv,
909 const TopoDS_Face& face,
910 SMESH_MesherHelper& helper,
912 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
913 gp_XYZ getNormalByOffset( _LayerEdge* edge,
914 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
916 bool lastNoOffset = false);
917 bool findNeiborsOnEdge(const _LayerEdge* edge,
918 const SMDS_MeshNode*& n1,
919 const SMDS_MeshNode*& n2,
922 void findSimplexTestEdges( _SolidData& data,
923 vector< vector<_LayerEdge*> >& edgesByGeom);
924 void computeGeomSize( _SolidData& data );
925 bool findShapesToSmooth( _SolidData& data);
926 void limitStepSizeByCurvature( _SolidData& data );
927 void limitStepSize( _SolidData& data,
928 const SMDS_MeshElement* face,
929 const _LayerEdge* maxCosinEdge );
930 void limitStepSize( _SolidData& data, const double minSize);
931 bool inflate(_SolidData& data);
932 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
933 int invalidateBadSmooth( _SolidData& data,
934 SMESH_MesherHelper& helper,
935 vector< _LayerEdge* >& badSmooEdges,
936 vector< _EdgesOnShape* >& eosC1,
938 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
939 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
940 vector< _EdgesOnShape* >& eosC1,
941 int smooStep=0, bool moveAll=false );
942 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
943 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
944 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
945 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
946 SMESH_MesherHelper& helper );
947 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
948 bool updateNormalsOfConvexFaces( _SolidData& data,
949 SMESH_MesherHelper& helper,
951 void updateNormalsOfC1Vertices( _SolidData& data );
952 bool updateNormalsOfSmoothed( _SolidData& data,
953 SMESH_MesherHelper& helper,
955 const double stepSize );
956 bool isNewNormalOk( _SolidData& data,
958 const gp_XYZ& newNormal);
959 bool refine(_SolidData& data);
961 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
962 SMESH_MesherHelper& helper,
963 const SMESHDS_SubMesh* faceSubMesh );
964 void restoreNoShrink( _LayerEdge& edge ) const;
965 void fixBadFaces(const TopoDS_Face& F,
966 SMESH_MesherHelper& helper,
969 set<const SMDS_MeshNode*> * involvedNodes=NULL);
970 bool addBoundaryElements();
972 bool error( const string& text, int solidID=-1 );
973 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
976 void makeGroupOfLE();
979 SMESH_ComputeErrorPtr _error;
981 vector< _SolidData > _sdVec;
984 //--------------------------------------------------------------------------------
986 * \brief Shrinker of nodes on the EDGE
990 TopoDS_Edge _geomEdge;
991 vector<double> _initU;
992 vector<double> _normPar;
993 vector<const SMDS_MeshNode*> _nodes;
994 const _LayerEdge* _edges[2];
997 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
998 void Compute(bool set3D, SMESH_MesherHelper& helper);
999 void RestoreParams();
1000 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1001 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1002 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1003 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1004 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1005 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1007 //--------------------------------------------------------------------------------
1009 * \brief Smoother of _LayerEdge's on EDGE.
1013 struct OffPnt // point of the offsetted EDGE
1015 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1016 double _len; // length reached at previous inflation step
1017 double _param; // on EDGE
1018 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1019 gp_XYZ _edgeDir;// EDGE tangent at _param
1020 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1022 vector< OffPnt > _offPoints;
1023 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1024 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1025 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1026 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1027 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1028 _EdgesOnShape& _eos;
1029 double _curveLen; // length of the EDGE
1031 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1033 SMESH_MesherHelper& helper);
1035 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1036 _EdgesOnShape& eos )
1037 : _anaCurve( curveForSmooth ), _eos( eos )
1040 bool Perform(_SolidData& data,
1041 Handle(ShapeAnalysis_Surface)& surface,
1042 const TopoDS_Face& F,
1043 SMESH_MesherHelper& helper )
1045 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1049 return smoothAnalyticEdge( data, surface, F, helper );
1051 return smoothComplexEdge ( data, surface, F, helper );
1053 void prepare(_SolidData& data );
1055 bool smoothAnalyticEdge( _SolidData& data,
1056 Handle(ShapeAnalysis_Surface)& surface,
1057 const TopoDS_Face& F,
1058 SMESH_MesherHelper& helper);
1060 bool smoothComplexEdge( _SolidData& data,
1061 Handle(ShapeAnalysis_Surface)& surface,
1062 const TopoDS_Face& F,
1063 SMESH_MesherHelper& helper);
1065 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1066 const gp_XYZ& edgeDir);
1068 _LayerEdge* getLEdgeOnV( bool is2nd )
1070 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1072 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1074 //--------------------------------------------------------------------------------
1076 * \brief Class of temporary mesh face.
1077 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1078 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1080 struct _TmpMeshFace : public SMDS_MeshElement
1082 vector<const SMDS_MeshNode* > _nn;
1083 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1084 int id, int faceID=-1, int idInFace=-1):
1085 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1086 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1087 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1088 virtual vtkIdType GetVtkType() const { return -1; }
1089 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1090 virtual SMDSAbs_GeometryType GetGeomType() const
1091 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1092 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1093 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1095 //--------------------------------------------------------------------------------
1097 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1099 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1101 _LayerEdge *_le1, *_le2;
1102 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1103 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1105 _nn[0]=_le1->_nodes[0];
1106 _nn[1]=_le1->_nodes.back();
1107 _nn[2]=_le2->_nodes.back();
1108 _nn[3]=_le2->_nodes[0];
1110 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1112 SMESH_TNodeXYZ p0s( _nn[0] );
1113 SMESH_TNodeXYZ p0t( _nn[1] );
1114 SMESH_TNodeXYZ p1t( _nn[2] );
1115 SMESH_TNodeXYZ p1s( _nn[3] );
1116 gp_XYZ v0 = p0t - p0s;
1117 gp_XYZ v1 = p1t - p1s;
1118 gp_XYZ v01 = p1s - p0s;
1119 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1124 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1126 _nn[0]=le1->_nodes[0];
1127 _nn[1]=le1->_nodes.back();
1128 _nn[2]=le2->_nodes.back();
1129 _nn[3]=le2->_nodes[0];
1133 //--------------------------------------------------------------------------------
1135 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1136 * \warning Location of a surface is ignored
1138 struct _NodeCoordHelper
1140 SMESH_MesherHelper& _helper;
1141 const TopoDS_Face& _face;
1142 Handle(Geom_Surface) _surface;
1143 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1145 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1146 : _helper( helper ), _face( F )
1150 TopLoc_Location loc;
1151 _surface = BRep_Tool::Surface( _face, loc );
1153 if ( _surface.IsNull() )
1154 _fun = & _NodeCoordHelper::direct;
1156 _fun = & _NodeCoordHelper::byUV;
1158 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1161 gp_XYZ direct(const SMDS_MeshNode* n) const
1163 return SMESH_TNodeXYZ( n );
1165 gp_XYZ byUV (const SMDS_MeshNode* n) const
1167 gp_XY uv = _helper.GetNodeUV( _face, n );
1168 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1172 //================================================================================
1174 * \brief Check angle between vectors
1176 //================================================================================
1178 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1180 double dot = v1 * v2; // cos * |v1| * |v2|
1181 double l1 = v1.SquareMagnitude();
1182 double l2 = v2.SquareMagnitude();
1183 return (( dot * cos >= 0 ) &&
1184 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1187 } // namespace VISCOUS_3D
1191 //================================================================================
1192 // StdMeshers_ViscousLayers hypothesis
1194 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1195 :SMESH_Hypothesis(hypId, studyId, gen),
1196 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1197 _method( SURF_OFFSET_SMOOTH )
1199 _name = StdMeshers_ViscousLayers::GetHypType();
1200 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1201 } // --------------------------------------------------------------------------------
1202 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1204 if ( faceIds != _shapeIds )
1205 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1206 if ( _isToIgnoreShapes != toIgnore )
1207 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1211 if ( thickness != _thickness )
1212 _thickness = thickness, NotifySubMeshesHypothesisModification();
1213 } // --------------------------------------------------------------------------------
1214 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1216 if ( _nbLayers != nb )
1217 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1218 } // --------------------------------------------------------------------------------
1219 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1221 if ( _stretchFactor != factor )
1222 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1223 } // --------------------------------------------------------------------------------
1224 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1226 if ( _method != method )
1227 _method = method, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 SMESH_ProxyMesh::Ptr
1230 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1231 const TopoDS_Shape& theShape,
1232 const bool toMakeN2NMap) const
1234 using namespace VISCOUS_3D;
1235 _ViscousBuilder bulder;
1236 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1237 if ( err && !err->IsOK() )
1238 return SMESH_ProxyMesh::Ptr();
1240 vector<SMESH_ProxyMesh::Ptr> components;
1241 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1242 for ( ; exp.More(); exp.Next() )
1244 if ( _MeshOfSolid* pm =
1245 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1247 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1248 if ( !bulder.MakeN2NMap( pm ))
1249 return SMESH_ProxyMesh::Ptr();
1250 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1251 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1253 if ( pm->_warning && !pm->_warning->IsOK() )
1255 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1256 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1257 if ( !smError || smError->IsOK() )
1258 smError = pm->_warning;
1261 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1263 switch ( components.size() )
1267 case 1: return components[0];
1269 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1271 return SMESH_ProxyMesh::Ptr();
1272 } // --------------------------------------------------------------------------------
1273 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1275 save << " " << _nbLayers
1276 << " " << _thickness
1277 << " " << _stretchFactor
1278 << " " << _shapeIds.size();
1279 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1280 save << " " << _shapeIds[i];
1281 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1282 save << " " << _method;
1284 } // --------------------------------------------------------------------------------
1285 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1287 int nbFaces, faceID, shapeToTreat, method;
1288 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1289 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1290 _shapeIds.push_back( faceID );
1291 if ( load >> shapeToTreat ) {
1292 _isToIgnoreShapes = !shapeToTreat;
1293 if ( load >> method )
1294 _method = (ExtrusionMethod) method;
1297 _isToIgnoreShapes = true; // old behavior
1300 } // --------------------------------------------------------------------------------
1301 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1302 const TopoDS_Shape& theShape)
1306 } // --------------------------------------------------------------------------------
1307 SMESH_ComputeErrorPtr
1308 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1309 const TopoDS_Shape& theShape,
1310 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1312 VISCOUS_3D::_ViscousBuilder bulder;
1313 SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1314 if ( err && !err->IsOK() )
1315 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1317 theStatus = SMESH_Hypothesis::HYP_OK;
1321 // --------------------------------------------------------------------------------
1322 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1325 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1326 return IsToIgnoreShapes() ? !isIn : isIn;
1328 // END StdMeshers_ViscousLayers hypothesis
1329 //================================================================================
1331 namespace VISCOUS_3D
1333 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1337 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1338 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1339 gp_Pnt p = BRep_Tool::Pnt( fromV );
1340 double distF = p.SquareDistance( c->Value( f ));
1341 double distL = p.SquareDistance( c->Value( l ));
1342 c->D1(( distF < distL ? f : l), p, dir );
1343 if ( distL < distF ) dir.Reverse();
1346 //--------------------------------------------------------------------------------
1347 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1348 SMESH_MesherHelper& helper)
1351 double f,l; gp_Pnt p;
1352 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1353 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1354 double u = helper.GetNodeU( E, atNode );
1358 //--------------------------------------------------------------------------------
1359 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1360 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1362 //--------------------------------------------------------------------------------
1363 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1364 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1367 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1370 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1371 return getFaceDir( F, v, node, helper, ok );
1373 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1374 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1375 gp_Pnt p; gp_Vec du, dv, norm;
1376 surface->D1( uv.X(),uv.Y(), p, du,dv );
1379 double u = helper.GetNodeU( fromE, node, 0, &ok );
1381 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1382 if ( o == TopAbs_REVERSED )
1385 gp_Vec dir = norm ^ du;
1387 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1388 helper.IsClosedEdge( fromE ))
1390 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1391 else c->D1( f, p, dv );
1392 if ( o == TopAbs_REVERSED )
1394 gp_Vec dir2 = norm ^ dv;
1395 dir = dir.Normalized() + dir2.Normalized();
1399 //--------------------------------------------------------------------------------
1400 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1401 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1402 bool& ok, double* cosin)
1404 TopoDS_Face faceFrw = F;
1405 faceFrw.Orientation( TopAbs_FORWARD );
1406 //double f,l; TopLoc_Location loc;
1407 TopoDS_Edge edges[2]; // sharing a vertex
1410 TopoDS_Vertex VV[2];
1411 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1412 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1414 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1415 if ( SMESH_Algo::isDegenerated( e )) continue;
1416 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1417 if ( VV[1].IsSame( fromV )) {
1418 nbEdges += edges[ 0 ].IsNull();
1421 else if ( VV[0].IsSame( fromV )) {
1422 nbEdges += edges[ 1 ].IsNull();
1427 gp_XYZ dir(0,0,0), edgeDir[2];
1430 // get dirs of edges going fromV
1432 for ( size_t i = 0; i < nbEdges && ok; ++i )
1434 edgeDir[i] = getEdgeDir( edges[i], fromV );
1435 double size2 = edgeDir[i].SquareModulus();
1436 if (( ok = size2 > numeric_limits<double>::min() ))
1437 edgeDir[i] /= sqrt( size2 );
1439 if ( !ok ) return dir;
1441 // get angle between the 2 edges
1443 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1444 if ( Abs( angle ) < 5 * M_PI/180 )
1446 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1450 dir = edgeDir[0] + edgeDir[1];
1455 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1456 *cosin = Cos( angle );
1459 else if ( nbEdges == 1 )
1461 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1462 if ( cosin ) *cosin = 1.;
1472 //================================================================================
1474 * \brief Finds concave VERTEXes of a FACE
1476 //================================================================================
1478 bool getConcaveVertices( const TopoDS_Face& F,
1479 SMESH_MesherHelper& helper,
1480 set< TGeomID >* vertices = 0)
1482 // check angles at VERTEXes
1484 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1485 for ( size_t iW = 0; iW < wires.size(); ++iW )
1487 const int nbEdges = wires[iW]->NbEdges();
1488 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1490 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1492 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1493 int iE2 = ( iE1 + 1 ) % nbEdges;
1494 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1495 iE2 = ( iE2 + 1 ) % nbEdges;
1496 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1497 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1498 wires[iW]->Edge( iE2 ), F, V );
1499 if ( angle < -5. * M_PI / 180. )
1503 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1507 return vertices ? !vertices->empty() : false;
1510 //================================================================================
1512 * \brief Returns true if a FACE is bound by a concave EDGE
1514 //================================================================================
1516 bool isConcave( const TopoDS_Face& F,
1517 SMESH_MesherHelper& helper,
1518 set< TGeomID >* vertices = 0 )
1520 bool isConcv = false;
1521 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1523 gp_Vec2d drv1, drv2;
1525 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1526 for ( ; eExp.More(); eExp.Next() )
1528 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1529 if ( SMESH_Algo::isDegenerated( E )) continue;
1530 // check if 2D curve is concave
1531 BRepAdaptor_Curve2d curve( E, F );
1532 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1533 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1534 curve.Intervals( intervals, GeomAbs_C2 );
1535 bool isConvex = true;
1536 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1538 double u1 = intervals( i );
1539 double u2 = intervals( i+1 );
1540 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1541 double cross = drv1 ^ drv2;
1542 if ( E.Orientation() == TopAbs_REVERSED )
1544 isConvex = ( cross > -1e-9 ); // 0.1 );
1548 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1557 // check angles at VERTEXes
1558 if ( getConcaveVertices( F, helper, vertices ))
1564 //================================================================================
1566 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1567 * \param [in] face - the mesh face to treat
1568 * \param [in] nodeOnEdge - a node on the EDGE
1569 * \param [out] faceSize - the computed distance
1570 * \return bool - true if faceSize computed
1572 //================================================================================
1574 bool getDistFromEdge( const SMDS_MeshElement* face,
1575 const SMDS_MeshNode* nodeOnEdge,
1578 faceSize = Precision::Infinite();
1581 int nbN = face->NbCornerNodes();
1582 int iOnE = face->GetNodeIndex( nodeOnEdge );
1583 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1584 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1585 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1586 face->GetNode( iNext[1] ) };
1587 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1588 double segLen = -1.;
1589 // look for two neighbor not in-FACE nodes of face
1590 for ( int i = 0; i < 2; ++i )
1592 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1593 nNext[i]->GetID() < nodeOnEdge->GetID() )
1595 // look for an in-FACE node
1596 for ( int iN = 0; iN < nbN; ++iN )
1598 if ( iN == iOnE || iN == iNext[i] )
1600 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1601 gp_XYZ v = pInFace - segEnd;
1604 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1605 segLen = segVec.Modulus();
1607 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1608 faceSize = Min( faceSize, distToSeg );
1616 //================================================================================
1618 * \brief Return direction of axis or revolution of a surface
1620 //================================================================================
1622 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1625 switch ( surface.GetType() ) {
1628 gp_Cone cone = surface.Cone();
1629 axis = cone.Axis().Direction();
1632 case GeomAbs_Sphere:
1634 gp_Sphere sphere = surface.Sphere();
1635 axis = sphere.Position().Direction();
1638 case GeomAbs_SurfaceOfRevolution:
1640 axis = surface.AxeOfRevolution().Direction();
1643 //case GeomAbs_SurfaceOfExtrusion:
1644 case GeomAbs_OffsetSurface:
1646 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1647 return getRovolutionAxis( base->Surface(), axis );
1649 default: return false;
1654 //--------------------------------------------------------------------------------
1655 // DEBUG. Dump intermediate node positions into a python script
1656 // HOWTO use: run python commands written in a console to see
1657 // construction steps of viscous layers
1662 PyDump(SMESH_Mesh& m) {
1663 int tag = 3 + m.GetId();
1664 const char* fname = "/tmp/viscous.py";
1665 cout << "execfile('"<<fname<<"')"<<endl;
1666 py = new ofstream(fname);
1667 *py << "import SMESH" << endl
1668 << "from salome.smesh import smeshBuilder" << endl
1669 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1670 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1671 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1676 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1677 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1678 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1679 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1683 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1685 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1686 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1687 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1688 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1689 void _dumpFunction(const string& fun, int ln)
1690 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1691 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1692 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1693 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1694 void _dumpCmd(const string& txt, int ln)
1695 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1696 void dumpFunctionEnd()
1697 { if (py) *py<< " return"<< endl; }
1698 void dumpChangeNodes( const SMDS_MeshElement* f )
1699 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1700 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1701 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1702 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1706 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1707 #define dumpFunction(f) f
1709 #define dumpMoveComm(n,txt)
1710 #define dumpCmd(txt)
1711 #define dumpFunctionEnd()
1712 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1713 #define debugMsg( txt ) {}
1718 using namespace VISCOUS_3D;
1720 //================================================================================
1722 * \brief Constructor of _ViscousBuilder
1724 //================================================================================
1726 _ViscousBuilder::_ViscousBuilder()
1728 _error = SMESH_ComputeError::New(COMPERR_OK);
1732 //================================================================================
1734 * \brief Stores error description and returns false
1736 //================================================================================
1738 bool _ViscousBuilder::error(const string& text, int solidId )
1740 const string prefix = string("Viscous layers builder: ");
1741 _error->myName = COMPERR_ALGO_FAILED;
1742 _error->myComment = prefix + text;
1745 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1746 if ( !sm && !_sdVec.empty() )
1747 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1748 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1750 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1751 if ( smError && smError->myAlgo )
1752 _error->myAlgo = smError->myAlgo;
1754 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1756 // set KO to all solids
1757 for ( size_t i = 0; i < _sdVec.size(); ++i )
1759 if ( _sdVec[i]._index == solidId )
1761 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1762 if ( !sm->IsEmpty() )
1764 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1765 if ( !smError || smError->IsOK() )
1767 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1768 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1772 makeGroupOfLE(); // debug
1777 //================================================================================
1779 * \brief At study restoration, restore event listeners used to clear an inferior
1780 * dim sub-mesh modified by viscous layers
1782 //================================================================================
1784 void _ViscousBuilder::RestoreListeners()
1789 //================================================================================
1791 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1793 //================================================================================
1795 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1797 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1798 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1799 for ( ; fExp.More(); fExp.Next() )
1801 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1802 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1804 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1806 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1809 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1810 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1812 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1813 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1814 while( prxIt->more() )
1816 const SMDS_MeshElement* fSrc = srcIt->next();
1817 const SMDS_MeshElement* fPrx = prxIt->next();
1818 if ( fSrc->NbNodes() != fPrx->NbNodes())
1819 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1820 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1821 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1824 pm->_n2nMapComputed = true;
1828 //================================================================================
1830 * \brief Does its job
1832 //================================================================================
1834 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1835 const TopoDS_Shape& theShape)
1837 // TODO: set priority of solids during Gen::Compute()
1841 // check if proxy mesh already computed
1842 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1844 return error("No SOLID's in theShape"), _error;
1846 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1847 return SMESH_ComputeErrorPtr(); // everything already computed
1849 PyDump debugDump( theMesh );
1851 // TODO: ignore already computed SOLIDs
1852 if ( !findSolidsWithLayers())
1855 if ( !findFacesWithLayers() )
1858 for ( size_t i = 0; i < _sdVec.size(); ++i )
1860 if ( ! makeLayer(_sdVec[i]) )
1863 if ( _sdVec[i]._n2eMap.size() == 0 )
1866 if ( ! inflate(_sdVec[i]) )
1869 if ( ! refine(_sdVec[i]) )
1875 addBoundaryElements();
1877 makeGroupOfLE(); // debug
1883 //================================================================================
1885 * \brief Check validity of hypotheses
1887 //================================================================================
1889 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1890 const TopoDS_Shape& shape )
1894 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1895 return SMESH_ComputeErrorPtr(); // everything already computed
1898 findSolidsWithLayers();
1899 bool ok = findFacesWithLayers( true );
1901 // remove _MeshOfSolid's of _SolidData's
1902 for ( size_t i = 0; i < _sdVec.size(); ++i )
1903 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1908 return SMESH_ComputeErrorPtr();
1911 //================================================================================
1913 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1915 //================================================================================
1917 bool _ViscousBuilder::findSolidsWithLayers()
1920 TopTools_IndexedMapOfShape allSolids;
1921 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1922 _sdVec.reserve( allSolids.Extent());
1924 SMESH_Gen* gen = _mesh->GetGen();
1925 SMESH_HypoFilter filter;
1926 for ( int i = 1; i <= allSolids.Extent(); ++i )
1928 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1929 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1930 if ( !algo ) continue;
1931 // TODO: check if algo is hidden
1932 const list <const SMESHDS_Hypothesis *> & allHyps =
1933 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1934 _SolidData* soData = 0;
1935 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1936 const StdMeshers_ViscousLayers* viscHyp = 0;
1937 for ( ; hyp != allHyps.end(); ++hyp )
1938 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1940 TopoDS_Shape hypShape;
1941 filter.Init( filter.Is( viscHyp ));
1942 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1946 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1949 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1950 soData = & _sdVec.back();
1951 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1952 soData->_helper = new SMESH_MesherHelper( *_mesh );
1953 soData->_helper->SetSubShape( allSolids(i) );
1955 soData->_hyps.push_back( viscHyp );
1956 soData->_hypShapes.push_back( hypShape );
1959 if ( _sdVec.empty() )
1961 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1966 //================================================================================
1970 //================================================================================
1972 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1974 SMESH_MesherHelper helper( *_mesh );
1975 TopExp_Explorer exp;
1976 TopTools_IndexedMapOfShape solids;
1978 // collect all faces-to-ignore defined by hyp
1979 for ( size_t i = 0; i < _sdVec.size(); ++i )
1981 solids.Add( _sdVec[i]._solid );
1983 // get faces-to-ignore defined by each hyp
1984 typedef const StdMeshers_ViscousLayers* THyp;
1985 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1986 list< TFacesOfHyp > ignoreFacesOfHyps;
1987 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
1988 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1989 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1991 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1992 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1995 // fill _SolidData::_face2hyp and check compatibility of hypotheses
1996 const int nbHyps = _sdVec[i]._hyps.size();
1999 // check if two hypotheses define different parameters for the same FACE
2000 list< TFacesOfHyp >::iterator igFacesOfHyp;
2001 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2003 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2005 igFacesOfHyp = ignoreFacesOfHyps.begin();
2006 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2007 if ( ! igFacesOfHyp->first.count( faceID ))
2010 return error(SMESH_Comment("Several hypotheses define "
2011 "Viscous Layers on the face #") << faceID );
2012 hyp = igFacesOfHyp->second;
2015 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2017 _sdVec[i]._ignoreFaceIds.insert( faceID );
2020 // check if two hypotheses define different number of viscous layers for
2021 // adjacent faces of a solid
2022 set< int > nbLayersSet;
2023 igFacesOfHyp = ignoreFacesOfHyps.begin();
2024 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2026 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2028 if ( nbLayersSet.size() > 1 )
2030 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2032 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2033 THyp hyp1 = 0, hyp2 = 0;
2034 while( const TopoDS_Shape* face = fIt->next() )
2036 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2037 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2038 if ( f2h != _sdVec[i]._face2hyp.end() )
2040 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2043 if ( hyp1 && hyp2 &&
2044 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2046 return error("Two hypotheses define different number of "
2047 "viscous layers on adjacent faces");
2051 } // if ( nbHyps > 1 )
2054 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2058 if ( onlyWith ) // is called to check hypotheses compatibility only
2061 // fill _SolidData::_reversedFaceIds
2062 for ( size_t i = 0; i < _sdVec.size(); ++i )
2064 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2065 for ( ; exp.More(); exp.Next() )
2067 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2068 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2069 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2070 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2071 helper.IsReversedSubMesh( face ))
2073 _sdVec[i]._reversedFaceIds.insert( faceID );
2078 // Find faces to shrink mesh on (solution 2 in issue 0020832);
2079 TopTools_IndexedMapOfShape shapes;
2080 for ( size_t i = 0; i < _sdVec.size(); ++i )
2083 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2084 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2086 const TopoDS_Shape& edge = shapes(iE);
2087 // find 2 faces sharing an edge
2089 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2090 while ( fIt->more())
2092 const TopoDS_Shape* f = fIt->next();
2093 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2094 FF[ int( !FF[0].IsNull()) ] = *f;
2096 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2097 // check presence of layers on them
2099 for ( int j = 0; j < 2; ++j )
2100 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2101 if ( ignore[0] == ignore[1] )
2102 continue; // nothing interesting
2103 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2104 // check presence of layers on fWOL within an adjacent SOLID
2105 bool collision = false;
2106 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2107 while ( const TopoDS_Shape* solid = sIt->next() )
2108 if ( !solid->IsSame( _sdVec[i]._solid ))
2110 int iSolid = solids.FindIndex( *solid );
2111 int iFace = getMeshDS()->ShapeToIndex( fWOL );
2112 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2114 //_sdVec[i]._noShrinkShapes.insert( iFace );
2120 if ( !fWOL.IsNull())
2122 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2123 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2126 // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2127 // on the edge but shrink won't be performed
2128 _sdVec[i]._noShrinkShapes.insert( edgeInd );
2133 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2134 // the algo of the SOLID sharing the FACE does not support it
2135 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2136 for ( size_t i = 0; i < _sdVec.size(); ++i )
2138 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2139 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2141 const TopoDS_Shape& fWOL = e2f->second;
2142 const TGeomID edgeID = e2f->first;
2143 bool notShrinkFace = false;
2144 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2145 while ( soIt->more() )
2147 const TopoDS_Shape* solid = soIt->next();
2148 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2149 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2150 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2151 notShrinkFace = true;
2153 for ( ; iSolid < _sdVec.size(); ++iSolid )
2155 if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2156 if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2157 notShrinkFace = false;
2161 if ( notShrinkFace )
2163 _sdVec[i]._noShrinkShapes.insert( edgeID );
2165 // add VERTEXes of the edge in _noShrinkShapes
2166 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2167 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2168 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2170 // check if there is a collision with to-shrink-from EDGEs in iSolid
2171 if ( iSolid == _sdVec.size() )
2172 continue; // no VL in the solid
2174 TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2175 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2177 const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2178 const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2179 if ( eID == edgeID ||
2180 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2181 _sdVec[i]._noShrinkShapes.count( eID ))
2183 for ( int is1st = 0; is1st < 2; ++is1st )
2185 TopoDS_Vertex V = helper.IthVertex( is1st, E );
2186 if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2188 // _sdVec[i]._noShrinkShapes.insert( eID );
2189 // V = helper.IthVertex( !is1st, E );
2190 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2191 //iE = 0; // re-start the loop on EDGEs of fWOL
2192 return error("No way to make a conformal mesh with "
2193 "the given set of faces with layers", _sdVec[i]._index);
2199 } // while ( soIt->more() )
2200 } // loop on _sdVec[i]._shrinkShape2Shape
2201 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2203 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2205 for ( size_t i = 0; i < _sdVec.size(); ++i )
2208 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2209 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2211 const TopoDS_Shape& vertex = shapes(iV);
2212 // find faces WOL sharing the vertex
2213 vector< TopoDS_Shape > facesWOL;
2214 size_t totalNbFaces = 0;
2215 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2216 while ( fIt->more())
2218 const TopoDS_Shape* f = fIt->next();
2219 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2222 const int fID = getMeshDS()->ShapeToIndex( *f );
2223 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2224 !_sdVec[i]._noShrinkShapes.count( fID )*/)
2225 facesWOL.push_back( *f );
2228 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2229 continue; // no layers at this vertex or no WOL
2230 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2231 switch ( facesWOL.size() )
2235 helper.SetSubShape( facesWOL[0] );
2236 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2238 TopoDS_Shape seamEdge;
2239 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2240 while ( eIt->more() && seamEdge.IsNull() )
2242 const TopoDS_Shape* e = eIt->next();
2243 if ( helper.IsRealSeam( *e ) )
2246 if ( !seamEdge.IsNull() )
2248 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2252 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2257 // find an edge shared by 2 faces
2258 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2259 while ( eIt->more())
2261 const TopoDS_Shape* e = eIt->next();
2262 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2263 helper.IsSubShape( *e, facesWOL[1]))
2265 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2271 return error("Not yet supported case", _sdVec[i]._index);
2276 // add FACEs of other SOLIDs to _ignoreFaceIds
2277 for ( size_t i = 0; i < _sdVec.size(); ++i )
2280 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2282 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2284 if ( !shapes.Contains( exp.Current() ))
2285 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2292 //================================================================================
2294 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2296 //================================================================================
2298 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2299 const StdMeshers_ViscousLayers* hyp,
2300 const TopoDS_Shape& hypShape,
2301 set<TGeomID>& ignoreFaceIds)
2303 TopExp_Explorer exp;
2305 vector<TGeomID> ids = hyp->GetBndShapes();
2306 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2308 for ( size_t ii = 0; ii < ids.size(); ++ii )
2310 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2311 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2312 ignoreFaceIds.insert( ids[ii] );
2315 else // FACEs with layers are given
2317 exp.Init( solid, TopAbs_FACE );
2318 for ( ; exp.More(); exp.Next() )
2320 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2321 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2322 ignoreFaceIds.insert( faceInd );
2326 // ignore internal FACEs if inlets and outlets are specified
2327 if ( hyp->IsToIgnoreShapes() )
2329 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2330 TopExp::MapShapesAndAncestors( hypShape,
2331 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2333 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2335 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2336 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2339 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2341 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2346 //================================================================================
2348 * \brief Create the inner surface of the viscous layer and prepare data for infation
2350 //================================================================================
2352 bool _ViscousBuilder::makeLayer(_SolidData& data)
2354 // get all sub-shapes to make layers on
2355 set<TGeomID> subIds, faceIds;
2356 subIds = data._noShrinkShapes;
2357 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2358 for ( ; exp.More(); exp.Next() )
2360 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2361 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2362 faceIds.insert( fSubM->GetId() );
2365 // make a map to find new nodes on sub-shapes shared with other SOLID
2366 map< TGeomID, TNode2Edge* >::iterator s2ne;
2367 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2368 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2370 TGeomID shapeInd = s2s->first;
2371 for ( size_t i = 0; i < _sdVec.size(); ++i )
2373 if ( _sdVec[i]._index == data._index ) continue;
2374 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2375 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2376 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2378 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2384 // Create temporary faces and _LayerEdge's
2386 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2388 data._stepSize = Precision::Infinite();
2389 data._stepSizeNodes[0] = 0;
2391 SMESH_MesherHelper helper( *_mesh );
2392 helper.SetSubShape( data._solid );
2393 helper.SetElementsOnShape( true );
2395 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2396 TNode2Edge::iterator n2e2;
2398 // collect _LayerEdge's of shapes they are based on
2399 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2400 const int nbShapes = getMeshDS()->MaxShapeIndex();
2401 edgesByGeom.resize( nbShapes+1 );
2403 // set data of _EdgesOnShape's
2404 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2406 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2407 while ( smIt->more() )
2410 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2411 !faceIds.count( sm->GetId() ))
2413 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2416 // make _LayerEdge's
2417 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2419 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2420 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2421 SMESH_ProxyMesh::SubMesh* proxySub =
2422 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2424 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2425 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2427 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2428 while ( eIt->more() )
2430 const SMDS_MeshElement* face = eIt->next();
2431 double faceMaxCosin = -1;
2432 _LayerEdge* maxCosinEdge = 0;
2433 int nbDegenNodes = 0;
2435 newNodes.resize( face->NbCornerNodes() );
2436 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2438 const SMDS_MeshNode* n = face->GetNode( i );
2439 const int shapeID = n->getshapeId();
2440 const bool onDegenShap = helper.IsDegenShape( shapeID );
2441 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2446 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2447 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2448 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2449 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2459 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2460 if ( !(*n2e).second )
2463 _LayerEdge* edge = new _LayerEdge();
2464 edge->_nodes.push_back( n );
2466 edgesByGeom[ shapeID ]._edges.push_back( edge );
2467 const bool noShrink = data._noShrinkShapes.count( shapeID );
2469 SMESH_TNodeXYZ xyz( n );
2471 // set edge data or find already refined _LayerEdge and get data from it
2472 if (( !noShrink ) &&
2473 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2474 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2475 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2477 _LayerEdge* foundEdge = (*n2e2).second;
2478 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2479 foundEdge->_pos.push_back( lastPos );
2480 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2481 const_cast< SMDS_MeshNode* >
2482 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2488 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2490 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2493 if ( edge->_nodes.size() < 2 )
2494 edge->Block( data );
2495 //data._noShrinkShapes.insert( shapeID );
2497 dumpMove(edge->_nodes.back());
2499 if ( edge->_cosin > faceMaxCosin )
2501 faceMaxCosin = edge->_cosin;
2502 maxCosinEdge = edge;
2505 newNodes[ i ] = n2e->second->_nodes.back();
2508 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2510 if ( newNodes.size() - nbDegenNodes < 2 )
2513 // create a temporary face
2514 const SMDS_MeshElement* newFace =
2515 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2516 proxySub->AddElement( newFace );
2518 // compute inflation step size by min size of element on a convex surface
2519 if ( faceMaxCosin > theMinSmoothCosin )
2520 limitStepSize( data, face, maxCosinEdge );
2522 } // loop on 2D elements on a FACE
2523 } // loop on FACEs of a SOLID to create _LayerEdge's
2526 // Set _LayerEdge::_neibors
2527 TNode2Edge::iterator n2e;
2528 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2530 _EdgesOnShape& eos = data._edgesOnShape[iS];
2531 for ( size_t i = 0; i < eos._edges.size(); ++i )
2533 _LayerEdge* edge = eos._edges[i];
2534 TIDSortedNodeSet nearNodes;
2535 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2536 while ( fIt->more() )
2538 const SMDS_MeshElement* f = fIt->next();
2539 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2540 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2542 nearNodes.erase( edge->_nodes[0] );
2543 edge->_neibors.reserve( nearNodes.size() );
2544 TIDSortedNodeSet::iterator node = nearNodes.begin();
2545 for ( ; node != nearNodes.end(); ++node )
2546 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2547 edge->_neibors.push_back( n2e->second );
2551 data._epsilon = 1e-7;
2552 if ( data._stepSize < 1. )
2553 data._epsilon *= data._stepSize;
2555 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2558 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2559 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2561 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2562 const SMDS_MeshNode* nn[2];
2563 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2565 _EdgesOnShape& eos = data._edgesOnShape[iS];
2566 for ( size_t i = 0; i < eos._edges.size(); ++i )
2568 _LayerEdge* edge = eos._edges[i];
2569 if ( edge->IsOnEdge() )
2571 // get neighbor nodes
2572 bool hasData = ( edge->_2neibors->_edges[0] );
2573 if ( hasData ) // _LayerEdge is a copy of another one
2575 nn[0] = edge->_2neibors->srcNode(0);
2576 nn[1] = edge->_2neibors->srcNode(1);
2578 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2582 // set neighbor _LayerEdge's
2583 for ( int j = 0; j < 2; ++j )
2585 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2586 return error("_LayerEdge not found by src node", data._index);
2587 edge->_2neibors->_edges[j] = n2e->second;
2590 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2593 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2595 _Simplex& s = edge->_simplices[j];
2596 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2597 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2600 // For an _LayerEdge on a degenerated EDGE, copy some data from
2601 // a corresponding _LayerEdge on a VERTEX
2602 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2603 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2605 // Generally we should not get here
2606 if ( eos.ShapeType() != TopAbs_EDGE )
2608 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2609 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2610 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2612 const _LayerEdge* vEdge = n2e->second;
2613 edge->_normal = vEdge->_normal;
2614 edge->_lenFactor = vEdge->_lenFactor;
2615 edge->_cosin = vEdge->_cosin;
2618 } // loop on data._edgesOnShape._edges
2619 } // loop on data._edgesOnShape
2621 // fix _LayerEdge::_2neibors on EDGEs to smooth
2622 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2623 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2624 // if ( !e2c->second.IsNull() )
2626 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2627 // data.Sort2NeiborsOnEdge( eos->_edges );
2634 //================================================================================
2636 * \brief Compute inflation step size by min size of element on a convex surface
2638 //================================================================================
2640 void _ViscousBuilder::limitStepSize( _SolidData& data,
2641 const SMDS_MeshElement* face,
2642 const _LayerEdge* maxCosinEdge )
2645 double minSize = 10 * data._stepSize;
2646 const int nbNodes = face->NbCornerNodes();
2647 for ( int i = 0; i < nbNodes; ++i )
2649 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2650 const SMDS_MeshNode* curN = face->GetNode( i );
2651 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2652 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2654 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2655 if ( dist < minSize )
2656 minSize = dist, iN = i;
2659 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2660 if ( newStep < data._stepSize )
2662 data._stepSize = newStep;
2663 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2664 data._stepSizeNodes[0] = face->GetNode( iN );
2665 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2669 //================================================================================
2671 * \brief Compute inflation step size by min size of element on a convex surface
2673 //================================================================================
2675 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2677 if ( minSize < data._stepSize )
2679 data._stepSize = minSize;
2680 if ( data._stepSizeNodes[0] )
2683 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2684 data._stepSizeCoeff = data._stepSize / dist;
2689 //================================================================================
2691 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2693 //================================================================================
2695 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2697 SMESH_MesherHelper helper( *_mesh );
2699 const int nbTestPnt = 5; // on a FACE sub-shape
2701 BRepLProp_SLProps surfProp( 2, 1e-6 );
2702 data._convexFaces.clear();
2704 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2706 _EdgesOnShape& eof = data._edgesOnShape[iS];
2707 if ( eof.ShapeType() != TopAbs_FACE ||
2708 data._ignoreFaceIds.count( eof._shapeID ))
2711 TopoDS_Face F = TopoDS::Face( eof._shape );
2712 SMESH_subMesh * sm = eof._subMesh;
2713 const TGeomID faceID = eof._shapeID;
2715 BRepAdaptor_Surface surface( F, false );
2716 surfProp.SetSurface( surface );
2718 bool isTooCurved = false;
2720 _ConvexFace cnvFace;
2721 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2722 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2723 while ( smIt->more() )
2726 const TGeomID subID = sm->GetId();
2727 // find _LayerEdge's of a sub-shape
2729 if (( eos = data.GetShapeEdges( subID )))
2730 cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2733 // check concavity and curvature and limit data._stepSize
2734 const double minCurvature =
2735 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2736 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2737 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2739 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2740 surfProp.SetParameters( uv.X(), uv.Y() );
2741 if ( !surfProp.IsCurvatureDefined() )
2743 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2745 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2748 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2750 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2754 } // loop on sub-shapes of the FACE
2756 if ( !isTooCurved ) continue;
2758 _ConvexFace & convFace =
2759 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2762 convFace._normalsFixed = false;
2764 // skip a closed surface (data._convexFaces is useful anyway)
2765 bool isClosedF = false;
2766 helper.SetSubShape( F );
2767 if ( helper.HasRealSeam() )
2769 // in the closed surface there must be a closed EDGE
2770 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2771 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2775 // limit _LayerEdge::_maxLen on the FACE
2776 const double minCurvature =
2777 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2778 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2779 if ( id2eos != cnvFace._subIdToEOS.end() )
2781 _EdgesOnShape& eos = * id2eos->second;
2782 for ( size_t i = 0; i < eos._edges.size(); ++i )
2784 _LayerEdge* ledge = eos._edges[ i ];
2785 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2786 surfProp.SetParameters( uv.X(), uv.Y() );
2787 if ( !surfProp.IsCurvatureDefined() )
2790 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2791 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2793 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2794 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2800 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2801 // prism distortion.
2802 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2803 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2805 // there are _LayerEdge's on the FACE it-self;
2806 // select _LayerEdge's near EDGEs
2807 _EdgesOnShape& eos = * id2eos->second;
2808 for ( size_t i = 0; i < eos._edges.size(); ++i )
2810 _LayerEdge* ledge = eos._edges[ i ];
2811 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2812 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2814 convFace._simplexTestEdges.push_back( ledge );
2821 // where there are no _LayerEdge's on a _ConvexFace,
2822 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2823 // so that collision of viscous internal faces is not detected by check of
2824 // intersection of _LayerEdge's with the viscous internal faces.
2826 set< const SMDS_MeshNode* > usedNodes;
2828 // look for _LayerEdge's with null _sWOL
2829 id2eos = convFace._subIdToEOS.begin();
2830 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2832 _EdgesOnShape& eos = * id2eos->second;
2833 if ( !eos._sWOL.IsNull() )
2835 for ( size_t i = 0; i < eos._edges.size(); ++i )
2837 _LayerEdge* ledge = eos._edges[ i ];
2838 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2839 if ( !usedNodes.insert( srcNode ).second ) continue;
2841 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2843 usedNodes.insert( ledge->_simplices[i]._nPrev );
2844 usedNodes.insert( ledge->_simplices[i]._nNext );
2846 convFace._simplexTestEdges.push_back( ledge );
2850 } // loop on FACEs of data._solid
2853 //================================================================================
2855 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2857 //================================================================================
2859 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2861 // define allowed thickness
2862 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2864 data._maxThickness = 0;
2865 data._minThickness = 1e100;
2866 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2867 for ( ; hyp != data._hyps.end(); ++hyp )
2869 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2870 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2872 //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2874 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2875 // boundry inclined to the shape at a sharp angle
2877 //list< TGeomID > shapesToSmooth;
2878 TopTools_MapOfShape edgesOfSmooFaces;
2880 SMESH_MesherHelper helper( *_mesh );
2883 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2884 data._nbShapesToSmooth = 0;
2886 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2888 _EdgesOnShape& eos = edgesByGeom[iS];
2889 eos._toSmooth = false;
2890 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2893 double tgtThick = eos._hyp.GetTotalThickness();
2894 TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2895 for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2897 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2898 vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2899 if ( eE.empty() ) continue;
2902 for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2903 if ( eE[i]->_cosin > theMinSmoothCosin )
2905 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2906 while ( fIt->more() && !eos._toSmooth )
2908 const SMDS_MeshElement* face = fIt->next();
2909 if ( face->getshapeId() == eos._shapeID &&
2910 getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2912 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2917 if ( eos._toSmooth )
2919 for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2920 edgesOfSmooFaces.Add( eExp.Current() );
2922 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2924 data._nbShapesToSmooth += eos._toSmooth;
2928 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2930 _EdgesOnShape& eos = edgesByGeom[iS];
2931 eos._edgeSmoother = NULL;
2932 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2933 if ( !eos._hyp.ToSmooth() ) continue;
2935 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2936 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2939 double tgtThick = eos._hyp.GetTotalThickness();
2940 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2942 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2943 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2944 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2945 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2946 double angle = eDir.Angle( eV[0]->_normal );
2947 double cosin = Cos( angle );
2948 double cosinAbs = Abs( cosin );
2949 if ( cosinAbs > theMinSmoothCosin )
2951 // always smooth analytic EDGEs
2952 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2953 eos._toSmooth = ! curve.IsNull();
2955 // compare tgtThick with the length of an end segment
2956 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2957 while ( eIt->more() && !eos._toSmooth )
2959 const SMDS_MeshElement* endSeg = eIt->next();
2960 if ( endSeg->getshapeId() == (int) iS )
2963 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2964 eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2967 if ( eos._toSmooth )
2969 eos._edgeSmoother = new _Smoother1D( curve, eos );
2971 for ( size_t i = 0; i < eos._edges.size(); ++i )
2972 eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2976 data._nbShapesToSmooth += eos._toSmooth;
2980 // Reset _cosin if no smooth is allowed by the user
2981 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2983 _EdgesOnShape& eos = edgesByGeom[iS];
2984 if ( eos._edges.empty() ) continue;
2986 if ( !eos._hyp.ToSmooth() )
2987 for ( size_t i = 0; i < eos._edges.size(); ++i )
2988 eos._edges[i]->SetCosin( 0 );
2992 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2994 TopTools_MapOfShape c1VV;
2996 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2998 _EdgesOnShape& eos = edgesByGeom[iS];
2999 if ( eos._edges.empty() ||
3000 eos.ShapeType() != TopAbs_FACE ||
3004 // check EDGEs of a FACE
3005 TopTools_MapOfShape checkedEE, allVV;
3006 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3007 while ( !smQueue.empty() )
3009 SMESH_subMesh* sm = smQueue.front();
3010 smQueue.pop_front();
3011 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3012 while ( smIt->more() )
3015 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3016 allVV.Add( sm->GetSubShape() );
3017 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3018 !checkedEE.Add( sm->GetSubShape() ))
3021 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3022 vector<_LayerEdge*>& eE = eoe->_edges;
3023 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3026 bool isC1 = true; // check continuity along an EDGE
3027 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3028 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3032 // check that mesh faces are C1 as well
3034 gp_XYZ norm1, norm2;
3035 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3036 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3037 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3039 while ( fIt->more() && isC1 )
3040 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3041 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3046 // add the EDGE and an adjacent FACE to _eosC1
3047 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3048 while ( const TopoDS_Shape* face = fIt->next() )
3050 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3051 if ( !eof ) continue; // other solid
3052 if ( !eos.HasC1( eoe ))
3054 eos._eosC1.push_back( eoe );
3055 eoe->_toSmooth = false;
3056 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3058 if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof ))
3060 eos._eosC1.push_back( eof );
3061 eof->_toSmooth = false;
3062 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3063 smQueue.push_back( eof->_subMesh );
3068 if ( eos._eosC1.empty() )
3071 // check VERTEXes of C1 FACEs
3072 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3073 for ( ; vIt.More(); vIt.Next() )
3075 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3076 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3079 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3080 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3081 while ( const TopoDS_Shape* face = fIt->next() )
3083 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3084 if ( !eof ) continue; // other solid
3085 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3091 eos._eosC1.push_back( eov );
3092 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3093 c1VV.Add( eov->_shape );
3097 } // fill _eosC1 of FACEs
3102 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3104 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3106 _EdgesOnShape& eov = edgesByGeom[iS];
3107 if ( eov._edges.empty() ||
3108 eov.ShapeType() != TopAbs_VERTEX ||
3109 c1VV.Contains( eov._shape ))
3111 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3113 // get directions of surrounding EDGEs
3115 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3116 while ( const TopoDS_Shape* e = fIt->next() )
3118 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3119 if ( !eoe ) continue; // other solid
3120 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3121 if ( !Precision::IsInfinite( eDir.X() ))
3122 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3125 // find EDGEs with C1 directions
3126 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3127 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3128 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3130 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3131 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3134 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3135 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3136 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3137 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3138 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3139 dirOfEdges[i].first = 0;
3140 dirOfEdges[j].first = 0;
3143 } // fill _eosC1 of VERTEXes
3150 //================================================================================
3152 * \brief initialize data of _EdgesOnShape
3154 //================================================================================
3156 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3160 if ( !eos._shape.IsNull() ||
3161 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3164 SMESH_MesherHelper helper( *_mesh );
3167 eos._shapeID = sm->GetId();
3168 eos._shape = sm->GetSubShape();
3169 if ( eos.ShapeType() == TopAbs_FACE )
3170 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3171 eos._toSmooth = false;
3175 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3176 data._shrinkShape2Shape.find( eos._shapeID );
3177 if ( s2s != data._shrinkShape2Shape.end() )
3178 eos._sWOL = s2s->second;
3180 eos._isRegularSWOL = true;
3181 if ( eos.SWOLType() == TopAbs_FACE )
3183 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3184 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3185 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3189 if ( data._hyps.size() == 1 )
3191 eos._hyp = data._hyps.back();
3195 // compute average StdMeshers_ViscousLayers parameters
3196 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3197 if ( eos.ShapeType() == TopAbs_FACE )
3199 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3200 eos._hyp = f2hyp->second;
3204 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3205 while ( const TopoDS_Shape* face = fIt->next() )
3207 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3208 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3209 eos._hyp.Add( f2hyp->second );
3215 if ( ! eos._hyp.UseSurfaceNormal() )
3217 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3219 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3220 eos._faceNormals.resize( smDS->NbElements() );
3222 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3223 for ( int iF = 0; eIt->more(); ++iF )
3225 const SMDS_MeshElement* face = eIt->next();
3226 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3227 eos._faceNormals[iF].SetCoord( 0,0,0 );
3230 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3231 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3232 eos._faceNormals[iF].Reverse();
3234 else // find EOS of adjacent FACEs
3236 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3237 while ( const TopoDS_Shape* face = fIt->next() )
3239 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3240 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3241 if ( eos._faceEOS.back()->_shape.IsNull() )
3242 // avoid using uninitialised _shapeID in GetNormal()
3243 eos._faceEOS.back()->_shapeID = faceID;
3249 //================================================================================
3251 * \brief Returns normal of a face
3253 //================================================================================
3255 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3258 const _EdgesOnShape* eos = 0;
3260 if ( face->getshapeId() == _shapeID )
3266 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3267 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3268 eos = _faceEOS[ iF ];
3272 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3274 norm = eos->_faceNormals[ face->getIdInShape() ];
3278 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3279 << " on _shape #" << _shapeID );
3285 //================================================================================
3287 * \brief Set data of _LayerEdge needed for smoothing
3289 //================================================================================
3291 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3293 SMESH_MesherHelper& helper,
3296 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3299 edge._maxLen = Precision::Infinite();
3302 edge._curvature = 0;
3305 // --------------------------
3306 // Compute _normal and _cosin
3307 // --------------------------
3310 edge._lenFactor = 1.;
3311 edge._normal.SetCoord(0,0,0);
3312 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3314 int totalNbFaces = 0;
3316 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3320 const bool onShrinkShape = !eos._sWOL.IsNull();
3321 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3322 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3324 // get geom FACEs the node lies on
3325 //if ( useGeometry )
3327 set<TGeomID> faceIds;
3328 if ( eos.ShapeType() == TopAbs_FACE )
3330 faceIds.insert( eos._shapeID );
3334 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3335 while ( fIt->more() )
3336 faceIds.insert( fIt->next()->getshapeId() );
3338 set<TGeomID>::iterator id = faceIds.begin();
3339 for ( ; id != faceIds.end(); ++id )
3341 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3342 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3344 F = TopoDS::Face( s );
3345 face2Norm[ totalNbFaces ].first = F;
3353 bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3354 eos.SWOLType() == TopAbs_FACE &&
3357 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3359 if ( eos.SWOLType() == TopAbs_EDGE )
3361 // inflate from VERTEX along EDGE
3362 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3364 else if ( eos.ShapeType() == TopAbs_VERTEX )
3366 // inflate from VERTEX along FACE
3367 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3368 node, helper, normOK, &edge._cosin);
3372 // inflate from EDGE along FACE
3373 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3374 node, helper, normOK);
3377 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3380 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3383 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3385 F = face2Norm[ iF ].first;
3386 geomNorm = getFaceNormal( node, F, helper, normOK );
3387 if ( !normOK ) continue;
3390 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3392 face2Norm[ iF ].second = geomNorm.XYZ();
3393 edge._normal += geomNorm.XYZ();
3395 if ( nbOkNorms == 0 )
3396 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3398 if ( totalNbFaces >= 3 )
3400 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3403 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3405 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3406 edge._normal.SetCoord( 0,0,0 );
3407 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3409 const TopoDS_Face& F = face2Norm[iF].first;
3410 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3411 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3414 face2Norm[ iF ].second = geomNorm.XYZ();
3415 edge._normal += face2Norm[ iF ].second;
3420 else // !useGeometry - get _normal using surrounding mesh faces
3422 edge._normal = getWeigthedNormal( &edge );
3424 // set<TGeomID> faceIds;
3426 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3427 // while ( fIt->more() )
3429 // const SMDS_MeshElement* face = fIt->next();
3430 // if ( eos.GetNormal( face, geomNorm ))
3432 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3433 // continue; // use only one mesh face on FACE
3434 // edge._normal += geomNorm.XYZ();
3441 //if ( eos._hyp.UseSurfaceNormal() )
3443 switch ( eos.ShapeType() )
3450 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3451 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3452 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3453 edge._cosin = Cos( angle );
3456 case TopAbs_VERTEX: {
3457 //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3459 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3460 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3461 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3462 edge._cosin = Cos( angle );
3463 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3464 for ( int iF = totalNbFaces-2; iF >=0; --iF )
3466 F = face2Norm[ iF ].first;
3467 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3469 double angle = inFaceDir.Angle( edge._normal );
3470 double cosin = Cos( angle );
3471 if ( Abs( cosin ) > Abs( edge._cosin ))
3472 edge._cosin = cosin;
3479 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3483 double normSize = edge._normal.SquareModulus();
3484 if ( normSize < numeric_limits<double>::min() )
3485 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3487 edge._normal /= sqrt( normSize );
3489 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3491 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3492 edge._nodes.resize( 1 );
3493 edge._normal.SetCoord( 0,0,0 );
3497 // Set the rest data
3498 // --------------------
3500 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3502 if ( onShrinkShape )
3504 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3505 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3506 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3508 // set initial position which is parameters on _sWOL in this case
3509 if ( eos.SWOLType() == TopAbs_EDGE )
3511 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3512 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3513 if ( edge._nodes.size() > 1 )
3514 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3516 else // eos.SWOLType() == TopAbs_FACE
3518 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3519 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3520 if ( edge._nodes.size() > 1 )
3521 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3524 if ( edge._nodes.size() > 1 )
3526 // check if an angle between a FACE with layers and SWOL is sharp,
3527 // else the edge should not inflate
3529 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3530 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3531 F = face2Norm[iF].first;
3534 geomNorm = getFaceNormal( node, F, helper, normOK );
3535 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3536 geomNorm.Reverse(); // inside the SOLID
3537 if ( geomNorm * edge._normal < -0.001 )
3539 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3540 edge._nodes.resize( 1 );
3542 else if ( edge._lenFactor > 3 )
3544 edge._lenFactor = 2;
3545 edge.Set( _LayerEdge::RISKY_SWOL );
3552 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3554 if ( eos.ShapeType() == TopAbs_FACE )
3557 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3559 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3560 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3565 // Set neighbor nodes for a _LayerEdge based on EDGE
3567 if ( eos.ShapeType() == TopAbs_EDGE /*||
3568 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3570 edge._2neibors = new _2NearEdges;
3571 // target nodes instead of source ones will be set later
3577 //================================================================================
3579 * \brief Return normal to a FACE at a node
3580 * \param [in] n - node
3581 * \param [in] face - FACE
3582 * \param [in] helper - helper
3583 * \param [out] isOK - true or false
3584 * \param [in] shiftInside - to find normal at a position shifted inside the face
3585 * \return gp_XYZ - normal
3587 //================================================================================
3589 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3590 const TopoDS_Face& face,
3591 SMESH_MesherHelper& helper,
3598 // get a shifted position
3599 gp_Pnt p = SMESH_TNodeXYZ( node );
3600 gp_XYZ shift( 0,0,0 );
3601 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3602 switch ( S.ShapeType() ) {
3605 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3610 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3618 p.Translate( shift * 1e-5 );
3620 TopLoc_Location loc;
3621 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3623 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3625 projector.Perform( p );
3626 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3631 Quantity_Parameter U,V;
3632 projector.LowerDistanceParameters(U,V);
3637 uv = helper.GetNodeUV( face, node, 0, &isOK );
3643 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3645 if ( !shiftInside &&
3646 helper.IsDegenShape( node->getshapeId() ) &&
3647 getFaceNormalAtSingularity( uv, face, helper, normal ))
3650 return normal.XYZ();
3653 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3654 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3656 if ( pointKind == IMPOSSIBLE &&
3657 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3659 // probably NormEstim() failed due to a too high tolerance
3660 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3661 isOK = ( pointKind < IMPOSSIBLE );
3663 if ( pointKind < IMPOSSIBLE )
3665 if ( pointKind != REGULAR &&
3667 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3669 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3670 if ( normShift * normal.XYZ() < 0. )
3676 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3678 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3680 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3681 while ( fIt->more() )
3683 const SMDS_MeshElement* f = fIt->next();
3684 if ( f->getshapeId() == faceID )
3686 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3689 TopoDS_Face ff = face;
3690 ff.Orientation( TopAbs_FORWARD );
3691 if ( helper.IsReversedSubMesh( ff ))
3698 return normal.XYZ();
3701 //================================================================================
3703 * \brief Try to get normal at a singularity of a surface basing on it's nature
3705 //================================================================================
3707 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3708 const TopoDS_Face& face,
3709 SMESH_MesherHelper& helper,
3712 BRepAdaptor_Surface surface( face );
3714 if ( !getRovolutionAxis( surface, axis ))
3717 double f,l, d, du, dv;
3718 f = surface.FirstUParameter();
3719 l = surface.LastUParameter();
3720 d = ( uv.X() - f ) / ( l - f );
3721 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3722 f = surface.FirstVParameter();
3723 l = surface.LastVParameter();
3724 d = ( uv.Y() - f ) / ( l - f );
3725 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3728 gp_Pnt2d testUV = uv;
3729 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3731 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3732 for ( int iLoop = 0; true ; ++iLoop )
3734 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3735 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3742 if ( axis * refDir < 0. )
3750 //================================================================================
3752 * \brief Return a normal at a node weighted with angles taken by faces
3754 //================================================================================
3756 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3758 const SMDS_MeshNode* n = edge->_nodes[0];
3760 gp_XYZ resNorm(0,0,0);
3761 SMESH_TNodeXYZ p0( n ), pP, pN;
3762 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3764 pP.Set( edge->_simplices[i]._nPrev );
3765 pN.Set( edge->_simplices[i]._nNext );
3766 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3767 double l0P = v0P.SquareMagnitude();
3768 double l0N = v0N.SquareMagnitude();
3769 double lPN = vPN.SquareMagnitude();
3770 if ( l0P < std::numeric_limits<double>::min() ||
3771 l0N < std::numeric_limits<double>::min() ||
3772 lPN < std::numeric_limits<double>::min() )
3774 double lNorm = norm.SquareMagnitude();
3775 double sin2 = lNorm / l0P / l0N;
3776 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3778 double weight = sin2 * angle / lPN;
3779 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3785 //================================================================================
3787 * \brief Return a normal at a node by getting a common point of offset planes
3788 * defined by the FACE normals
3790 //================================================================================
3792 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3793 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3797 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3799 gp_XYZ resNorm(0,0,0);
3800 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3801 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3803 for ( int i = 0; i < nbFaces; ++i )
3804 resNorm += f2Normal[i].second;
3808 // prepare _OffsetPlane's
3809 vector< _OffsetPlane > pln( nbFaces );
3810 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3812 pln[i]._faceIndex = i;
3813 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3817 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3818 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3821 // intersect neighboring OffsetPlane's
3822 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3823 while ( const TopoDS_Shape* edge = edgeIt->next() )
3825 int f1 = -1, f2 = -1;
3826 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3827 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3828 (( f1 < 0 ) ? f1 : f2 ) = i;
3831 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3834 // get a common point
3835 gp_XYZ commonPnt( 0, 0, 0 );
3838 for ( int i = 0; i < nbFaces; ++i )
3840 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3841 nbPoints += isPointFound;
3843 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3844 if ( nbPoints == 0 )
3847 commonPnt /= nbPoints;
3848 resNorm = commonPnt - p0;
3852 // choose the best among resNorm and wgtNorm
3853 resNorm.Normalize();
3854 wgtNorm.Normalize();
3855 double resMinDot = std::numeric_limits<double>::max();
3856 double wgtMinDot = std::numeric_limits<double>::max();
3857 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3859 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3860 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3863 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3865 edge->Set( _LayerEdge::MULTI_NORMAL );
3868 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3871 //================================================================================
3873 * \brief Compute line of intersection of 2 planes
3875 //================================================================================
3877 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3878 const TopoDS_Edge& E,
3879 const TopoDS_Vertex& V )
3881 int iNext = bool( _faceIndexNext[0] >= 0 );
3882 _faceIndexNext[ iNext ] = pln._faceIndex;
3884 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3885 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3887 gp_XYZ lineDir = n1 ^ n2;
3889 double x = Abs( lineDir.X() );
3890 double y = Abs( lineDir.Y() );
3891 double z = Abs( lineDir.Z() );
3893 int cooMax; // max coordinate
3895 if (x > z) cooMax = 1;
3899 if (y > z) cooMax = 2;
3904 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3906 // parallel planes - intersection is an offset of the common EDGE
3907 gp_Pnt p = BRep_Tool::Pnt( V );
3908 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3909 lineDir = getEdgeDir( E, V );
3913 // the constants in the 2 plane equations
3914 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
3915 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3920 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3921 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3924 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3926 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3929 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3930 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3934 gp_Lin& line = _lines[ iNext ];
3935 line.SetDirection( lineDir );
3936 line.SetLocation ( linePos );
3938 _isLineOK[ iNext ] = true;
3941 iNext = bool( pln._faceIndexNext[0] >= 0 );
3942 pln._lines [ iNext ] = line;
3943 pln._faceIndexNext[ iNext ] = this->_faceIndex;
3944 pln._isLineOK [ iNext ] = true;
3947 //================================================================================
3949 * \brief Computes intersection point of two _lines
3951 //================================================================================
3953 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
3954 const TopoDS_Vertex & V) const
3959 if ( NbLines() == 2 )
3961 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3962 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
3963 if ( Abs( dot01 ) > 0.05 )
3965 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3966 double u1 = - ( lPerp0 * l0l1 ) / dot01;
3967 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3972 gp_Pnt pV ( BRep_Tool::Pnt( V ));
3973 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
3974 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
3975 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
3976 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
3984 //================================================================================
3986 * \brief Find 2 neigbor nodes of a node on EDGE
3988 //================================================================================
3990 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
3991 const SMDS_MeshNode*& n1,
3992 const SMDS_MeshNode*& n2,
3996 const SMDS_MeshNode* node = edge->_nodes[0];
3997 const int shapeInd = eos._shapeID;
3998 SMESHDS_SubMesh* edgeSM = 0;
3999 if ( eos.ShapeType() == TopAbs_EDGE )
4001 edgeSM = eos._subMesh->GetSubMeshDS();
4002 if ( !edgeSM || edgeSM->NbElements() == 0 )
4003 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4007 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4008 while ( eIt->more() && !n2 )
4010 const SMDS_MeshElement* e = eIt->next();
4011 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4012 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4015 if (!edgeSM->Contains(e)) continue;
4019 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4020 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4022 ( iN++ ? n2 : n1 ) = nNeibor;
4025 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4029 //================================================================================
4031 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4033 //================================================================================
4035 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4036 const SMDS_MeshNode* n2,
4037 const _EdgesOnShape& eos,
4038 SMESH_MesherHelper& helper)
4040 if ( eos.ShapeType() != TopAbs_EDGE )
4043 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4044 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4045 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4049 double sumLen = vec1.Modulus() + vec2.Modulus();
4050 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4051 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4052 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4053 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4054 if ( _curvature ) delete _curvature;
4055 _curvature = _Curvature::New( avgNormProj, avgLen );
4056 // if ( _curvature )
4057 // debugMsg( _nodes[0]->GetID()
4058 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4059 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4060 // << _curvature->lenDelta(0) );
4064 if ( eos._sWOL.IsNull() )
4066 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4067 // if ( SMESH_Algo::isDegenerated( E ))
4069 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4070 gp_XYZ plnNorm = dirE ^ _normal;
4071 double proj0 = plnNorm * vec1;
4072 double proj1 = plnNorm * vec2;
4073 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4075 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4076 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4081 //================================================================================
4083 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4084 * this and other _LayerEdge's are inflated along a FACE or an EDGE
4086 //================================================================================
4088 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4090 SMESH_MesherHelper& helper )
4092 _nodes = other._nodes;
4093 _normal = other._normal;
4095 _lenFactor = other._lenFactor;
4096 _cosin = other._cosin;
4097 _2neibors = other._2neibors;
4098 _curvature = 0; std::swap( _curvature, other._curvature );
4099 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4101 gp_XYZ lastPos( 0,0,0 );
4102 if ( eos.SWOLType() == TopAbs_EDGE )
4104 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4105 _pos.push_back( gp_XYZ( u, 0, 0));
4107 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4112 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4113 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4115 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4116 lastPos.SetX( uv.X() );
4117 lastPos.SetY( uv.Y() );
4122 //================================================================================
4124 * \brief Set _cosin and _lenFactor
4126 //================================================================================
4128 void _LayerEdge::SetCosin( double cosin )
4131 cosin = Abs( _cosin );
4132 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4133 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4136 //================================================================================
4138 * \brief Check if another _LayerEdge is a neighbor on EDGE
4140 //================================================================================
4142 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4144 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4145 ( edge->_2neibors && edge->_2neibors->include( this )));
4148 //================================================================================
4150 * \brief Fills a vector<_Simplex >
4152 //================================================================================
4154 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4155 vector<_Simplex>& simplices,
4156 const set<TGeomID>& ingnoreShapes,
4157 const _SolidData* dataToCheckOri,
4161 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4162 while ( fIt->more() )
4164 const SMDS_MeshElement* f = fIt->next();
4165 const TGeomID shapeInd = f->getshapeId();
4166 if ( ingnoreShapes.count( shapeInd )) continue;
4167 const int nbNodes = f->NbCornerNodes();
4168 const int srcInd = f->GetNodeIndex( node );
4169 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4170 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4171 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4172 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4173 std::swap( nPrev, nNext );
4174 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4178 SortSimplices( simplices );
4181 //================================================================================
4183 * \brief Set neighbor simplices side by side
4185 //================================================================================
4187 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4189 vector<_Simplex> sortedSimplices( simplices.size() );
4190 sortedSimplices[0] = simplices[0];
4192 for ( size_t i = 1; i < simplices.size(); ++i )
4194 for ( size_t j = 1; j < simplices.size(); ++j )
4195 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4197 sortedSimplices[i] = simplices[j];
4202 if ( nbFound == simplices.size() - 1 )
4203 simplices.swap( sortedSimplices );
4206 //================================================================================
4208 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4210 //================================================================================
4212 void _ViscousBuilder::makeGroupOfLE()
4215 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4217 if ( _sdVec[i]._n2eMap.empty() ) continue;
4219 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4220 TNode2Edge::iterator n2e;
4221 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4223 _LayerEdge* le = n2e->second;
4224 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4225 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4226 // << ", " << le->_nodes[iN]->GetID() <<"])");
4228 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4229 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4234 dumpFunction( SMESH_Comment("makeNormals") << i );
4235 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4237 _LayerEdge* edge = n2e->second;
4238 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4239 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4240 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4241 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4245 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4246 dumpCmd( "faceId1 = mesh.NbElements()" );
4247 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4248 for ( ; fExp.More(); fExp.Next() )
4250 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4252 if ( sm->NbElements() == 0 ) continue;
4253 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4254 while ( fIt->more())
4256 const SMDS_MeshElement* e = fIt->next();
4257 SMESH_Comment cmd("mesh.AddFace([");
4258 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4259 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4264 dumpCmd( "faceId2 = mesh.NbElements()" );
4265 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4266 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4267 << "'%s-%s' % (faceId1+1, faceId2))");
4273 //================================================================================
4275 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4277 //================================================================================
4279 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4281 data._geomSize = Precision::Infinite();
4282 double intersecDist;
4283 const SMDS_MeshElement* face;
4284 SMESH_MesherHelper helper( *_mesh );
4286 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4287 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4288 data._proxyMesh->GetFaces( data._solid )));
4290 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4292 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4293 if ( eos._edges.empty() )
4295 // get neighbor faces intersection with which should not be considered since
4296 // collisions are avoided by means of smoothing
4297 set< TGeomID > neighborFaces;
4298 if ( eos._hyp.ToSmooth() )
4300 SMESH_subMeshIteratorPtr subIt =
4301 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4302 while ( subIt->more() )
4304 SMESH_subMesh* sm = subIt->next();
4305 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4306 while ( const TopoDS_Shape* face = fIt->next() )
4307 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4310 // find intersections
4311 double thinkness = eos._hyp.GetTotalThickness();
4312 for ( size_t i = 0; i < eos._edges.size(); ++i )
4314 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4315 eos._edges[i]->_maxLen = thinkness;
4316 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4317 if ( intersecDist > 0 && face )
4319 data._geomSize = Min( data._geomSize, intersecDist );
4320 if ( !neighborFaces.count( face->getshapeId() ))
4321 eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4327 //================================================================================
4329 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4331 //================================================================================
4333 bool _ViscousBuilder::inflate(_SolidData& data)
4335 SMESH_MesherHelper helper( *_mesh );
4337 // Limit inflation step size by geometry size found by itersecting
4338 // normals of _LayerEdge's with mesh faces
4339 if ( data._stepSize > 0.3 * data._geomSize )
4340 limitStepSize( data, 0.3 * data._geomSize );
4342 const double tgtThick = data._maxThickness;
4343 if ( data._stepSize > data._minThickness )
4344 limitStepSize( data, data._minThickness );
4346 if ( data._stepSize < 1. )
4347 data._epsilon = data._stepSize * 1e-7;
4349 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4351 findCollisionEdges( data, helper );
4353 limitMaxLenByCurvature( data, helper );
4355 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4356 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4357 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4358 data._edgesOnShape[i]._edges.size() > 0 &&
4359 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4361 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4362 data._edgesOnShape[i]._edges[0]->Block( data );
4365 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4367 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4368 int nbSteps = 0, nbRepeats = 0;
4369 while ( avgThick < 0.99 )
4371 // new target length
4372 double prevThick = curThick;
4373 curThick += data._stepSize;
4374 if ( curThick > tgtThick )
4376 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4380 double stepSize = curThick - prevThick;
4381 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4383 // Elongate _LayerEdge's
4384 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4385 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4387 _EdgesOnShape& eos = data._edgesOnShape[iS];
4388 if ( eos._edges.empty() ) continue;
4390 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4391 for ( size_t i = 0; i < eos._edges.size(); ++i )
4393 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4398 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4401 // Improve and check quality
4402 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4406 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4407 debugMsg("NOT INVALIDATED STEP!");
4408 return error("Smoothing failed", data._index);
4410 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4411 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4413 _EdgesOnShape& eos = data._edgesOnShape[iS];
4414 for ( size_t i = 0; i < eos._edges.size(); ++i )
4415 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4419 break; // no more inflating possible
4423 // Evaluate achieved thickness
4425 int nbActiveEdges = 0;
4426 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4428 _EdgesOnShape& eos = data._edgesOnShape[iS];
4429 if ( eos._edges.empty() ) continue;
4431 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4432 for ( size_t i = 0; i < eos._edges.size(); ++i )
4434 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4435 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4438 avgThick /= data._n2eMap.size();
4439 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4441 #ifdef BLOCK_INFLATION
4442 if ( nbActiveEdges == 0 )
4444 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4448 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4450 debugMsg( "-- Stop inflation since "
4451 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4452 << tgtThick * avgThick << " ) * " << safeFactor );
4457 limitStepSize( data, 0.25 * distToIntersection );
4458 if ( data._stepSizeNodes[0] )
4459 data._stepSize = data._stepSizeCoeff *
4460 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4462 } // while ( avgThick < 0.99 )
4465 return error("failed at the very first inflation step", data._index);
4467 if ( avgThick < 0.99 )
4469 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4471 data._proxyMesh->_warning.reset
4472 ( new SMESH_ComputeError (COMPERR_WARNING,
4473 SMESH_Comment("Thickness ") << tgtThick <<
4474 " of viscous layers not reached,"
4475 " average reached thickness is " << avgThick*tgtThick));
4479 // Restore position of src nodes moved by inflation on _noShrinkShapes
4480 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4481 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4483 _EdgesOnShape& eos = data._edgesOnShape[iS];
4484 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4485 for ( size_t i = 0; i < eos._edges.size(); ++i )
4487 restoreNoShrink( *eos._edges[ i ] );
4492 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4495 //================================================================================
4497 * \brief Improve quality of layer inner surface and check intersection
4499 //================================================================================
4501 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4503 double & distToIntersection)
4505 if ( data._nbShapesToSmooth == 0 )
4506 return true; // no shapes needing smoothing
4508 bool moved, improved;
4510 vector< _LayerEdge* > movedEdges, badEdges;
4511 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4512 vector< bool > isConcaveFace;
4514 SMESH_MesherHelper helper(*_mesh);
4515 Handle(ShapeAnalysis_Surface) surface;
4518 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4520 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4522 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4524 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4525 if ( !eos._toSmooth ||
4526 eos.ShapeType() != shapeType ||
4527 eos._edges.empty() )
4530 // already smoothed?
4531 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4532 // if ( !toSmooth ) continue;
4534 if ( !eos._hyp.ToSmooth() )
4536 // smooth disabled by the user; check validy only
4537 if ( !isFace ) continue;
4539 for ( size_t i = 0; i < eos._edges.size(); ++i )
4541 _LayerEdge* edge = eos._edges[i];
4542 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4543 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4545 // debugMsg( "-- Stop inflation. Bad simplex ("
4546 // << " "<< edge->_nodes[0]->GetID()
4547 // << " "<< edge->_nodes.back()->GetID()
4548 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4549 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4551 badEdges.push_back( edge );
4554 if ( !badEdges.empty() )
4558 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4562 continue; // goto the next EDGE or FACE
4566 if ( eos.SWOLType() == TopAbs_FACE )
4568 if ( !F.IsSame( eos._sWOL )) {
4569 F = TopoDS::Face( eos._sWOL );
4570 helper.SetSubShape( F );
4571 surface = helper.GetSurface( F );
4576 F.Nullify(); surface.Nullify();
4578 const TGeomID sInd = eos._shapeID;
4580 // perform smoothing
4582 if ( eos.ShapeType() == TopAbs_EDGE )
4584 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4586 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4588 // smooth on EDGE's (normally we should not get here)
4592 for ( size_t i = 0; i < eos._edges.size(); ++i )
4594 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4596 dumpCmd( SMESH_Comment("# end step ")<<step);
4598 while ( moved && step++ < 5 );
4603 else // smooth on FACE
4606 eosC1.push_back( & eos );
4607 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4610 isConcaveFace.resize( eosC1.size() );
4611 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4613 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4614 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4615 for ( size_t i = 0; i < edges.size(); ++i )
4616 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4617 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4618 movedEdges.push_back( edges[i] );
4620 makeOffsetSurface( *eosC1[ iEOS ], helper );
4623 int step = 0, stepLimit = 5, nbBad = 0;
4624 while (( ++step <= stepLimit ) || improved )
4626 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4627 <<"_InfStep"<<infStep<<"_"<<step); // debug
4628 int oldBadNb = nbBad;
4631 #ifdef INCREMENTAL_SMOOTH
4632 bool findBest = false; // ( step == stepLimit );
4633 for ( size_t i = 0; i < movedEdges.size(); ++i )
4635 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4636 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4637 badEdges.push_back( movedEdges[i] );
4640 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4641 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4643 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4644 for ( size_t i = 0; i < edges.size(); ++i )
4646 edges[i]->Unset( _LayerEdge::SMOOTHED );
4647 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4648 badEdges.push_back( eos._edges[i] );
4652 nbBad = badEdges.size();
4655 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4657 if ( !badEdges.empty() && step >= stepLimit / 2 )
4659 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4662 // resolve hard smoothing situation around concave VERTEXes
4663 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4665 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4666 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4667 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4670 // look for the best smooth of _LayerEdge's neighboring badEdges
4672 for ( size_t i = 0; i < badEdges.size(); ++i )
4674 _LayerEdge* ledge = badEdges[i];
4675 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4677 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4678 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4680 ledge->Unset( _LayerEdge::SMOOTHED );
4681 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4683 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4686 if ( nbBad == oldBadNb &&
4688 step < stepLimit ) // smooth w/o chech of validity
4691 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4692 <<"_InfStep"<<infStep<<"_"<<step); // debug
4693 for ( size_t i = 0; i < movedEdges.size(); ++i )
4695 movedEdges[i]->SmoothWoCheck();
4697 if ( stepLimit < 9 )
4701 improved = ( nbBad < oldBadNb );
4705 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4706 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4708 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4711 } // smoothing steps
4713 // project -- to prevent intersections or fix bad simplices
4714 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4716 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4717 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4720 //if ( !badEdges.empty() )
4723 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4725 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4727 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4729 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4730 edge->CheckNeiborsOnBoundary( & badEdges );
4731 if (( nbBad > 0 ) ||
4732 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4734 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4735 gp_XYZ prevXYZ = edge->PrevCheckPos();
4736 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4737 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4739 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4740 << " "<< tgtXYZ._node->GetID()
4741 << " "<< edge->_simplices[j]._nPrev->GetID()
4742 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4743 badEdges.push_back( edge );
4750 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4751 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4757 } // // smooth on FACE's
4759 } // smooth on [ EDGEs, FACEs ]
4761 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4763 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4765 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4766 if ( eos.ShapeType() == TopAbs_FACE ||
4767 eos._edges.empty() ||
4768 !eos._sWOL.IsNull() )
4772 for ( size_t i = 0; i < eos._edges.size(); ++i )
4774 _LayerEdge* edge = eos._edges[i];
4775 if ( edge->_nodes.size() < 2 ) continue;
4776 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4777 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4778 //const gp_XYZ& prevXYZ = edge->PrevPos();
4779 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4780 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4782 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4783 << " "<< tgtXYZ._node->GetID()
4784 << " "<< edge->_simplices[j]._nPrev->GetID()
4785 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4786 badEdges.push_back( edge );
4791 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4793 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4799 // Check if the last segments of _LayerEdge intersects 2D elements;
4800 // checked elements are either temporary faces or faces on surfaces w/o the layers
4802 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4803 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4804 data._proxyMesh->GetFaces( data._solid )) );
4806 #ifdef BLOCK_INFLATION
4807 const bool toBlockInfaltion = true;
4809 const bool toBlockInfaltion = false;
4811 distToIntersection = Precision::Infinite();
4813 const SMDS_MeshElement* intFace = 0;
4814 const SMDS_MeshElement* closestFace = 0;
4816 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4818 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4819 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4821 for ( size_t i = 0; i < eos._edges.size(); ++i )
4823 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4824 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4826 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4829 // commented due to "Illegal hash-positionPosition" error in NETGEN
4830 // on Debian60 on viscous_layers_01/B2 case
4831 // Collision; try to deflate _LayerEdge's causing it
4832 // badEdges.clear();
4833 // badEdges.push_back( eos._edges[i] );
4834 // eosC1[0] = & eos;
4835 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4839 // badEdges.clear();
4840 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4842 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4844 // const SMDS_MeshElement* srcFace =
4845 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4846 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4847 // while ( nIt->more() )
4849 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4850 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4851 // if ( n2e != data._n2eMap.end() )
4852 // badEdges.push_back( n2e->second );
4855 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4860 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4867 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4872 const bool isShorterDist = ( distToIntersection > dist );
4873 if ( toBlockInfaltion || isShorterDist )
4875 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4876 // lying on this _ConvexFace
4877 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4878 if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4881 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4882 // ( avoid limiting the thickness on the case of issue 22576)
4883 if ( intFace->getshapeId() == eos._shapeID )
4886 // ignore intersection with intFace of an adjacent FACE
4889 bool toIgnore = false;
4890 if ( eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4892 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4893 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4895 TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4896 for ( ; !toIgnore && edge.More(); edge.Next() )
4897 // is adjacent - has a common EDGE
4898 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4900 if ( toIgnore ) // check angle between normals
4903 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4904 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
4908 if ( !toIgnore ) // check if the edge is a neighbor of intFace
4910 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
4912 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4913 toIgnore = ( nInd >= 0 );
4920 // intersection not ignored
4922 if ( toBlockInfaltion &&
4923 dist < ( eos._edges[i]->_len * theThickToIntersection ))
4925 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4926 eos._edges[i]->Block( data ); // not to inflate
4928 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4930 // block _LayerEdge's, on top of which intFace is
4931 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4933 const SMDS_MeshElement* srcFace =
4934 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4935 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4936 while ( nIt->more() )
4938 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4939 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4940 if ( n2e != data._n2eMap.end() )
4941 n2e->second->Block( data );
4947 if ( isShorterDist )
4949 distToIntersection = dist;
4951 closestFace = intFace;
4954 } // if ( toBlockInfaltion || isShorterDist )
4955 } // loop on eos._edges
4956 } // loop on data._edgesOnShape
4958 if ( closestFace && le )
4961 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4962 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4963 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4964 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4965 << ") distance = " << distToIntersection<< endl;
4972 //================================================================================
4974 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4975 * \param [in,out] badSmooEdges - _LayerEdge's to fix
4976 * \return int - resulting nb of bad _LayerEdge's
4978 //================================================================================
4980 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
4981 SMESH_MesherHelper& helper,
4982 vector< _LayerEdge* >& badSmooEdges,
4983 vector< _EdgesOnShape* >& eosC1,
4986 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4988 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4991 INVALIDATED = _LayerEdge::UNUSED_FLAG,
4992 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
4993 ADDED = _LayerEdge::UNUSED_FLAG * 4
4995 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
4998 bool haveInvalidated = true;
4999 while ( haveInvalidated )
5001 haveInvalidated = false;
5002 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5004 _LayerEdge* edge = badSmooEdges[i];
5005 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5007 bool invalidated = false;
5008 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5010 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5011 edge->Block( data );
5012 edge->Set( INVALIDATED );
5013 edge->Unset( TO_INVALIDATE );
5015 haveInvalidated = true;
5018 // look for _LayerEdge's of bad _simplices
5020 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5021 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5022 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5023 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5025 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5026 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5030 _LayerEdge* ee[2] = { 0,0 };
5031 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5032 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5033 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5035 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5036 while ( maxNbSteps > edge->NbSteps() && isBad )
5039 for ( int iE = 0; iE < 2; ++iE )
5041 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5042 ee[ iE ]->NbSteps() > 1 )
5044 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5045 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5046 ee[ iE ]->Block( data );
5047 ee[ iE ]->Set( INVALIDATED );
5048 haveInvalidated = true;
5051 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5052 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5056 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5057 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5058 ee[0]->Set( ADDED );
5059 ee[1]->Set( ADDED );
5062 ee[0]->Set( TO_INVALIDATE );
5063 ee[1]->Set( TO_INVALIDATE );
5067 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5069 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5070 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5071 edge->Block( data );
5072 edge->Set( INVALIDATED );
5073 edge->Unset( TO_INVALIDATE );
5074 haveInvalidated = true;
5076 } // loop on badSmooEdges
5077 } // while ( haveInvalidated )
5079 // re-smooth on analytical EDGEs
5080 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5082 _LayerEdge* edge = badSmooEdges[i];
5083 if ( !edge->Is( INVALIDATED )) continue;
5085 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5086 if ( eos->ShapeType() == TopAbs_VERTEX )
5088 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5089 while ( const TopoDS_Shape* e = eIt->next() )
5090 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5091 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5093 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5094 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5095 // F = TopoDS::Face( eoe->_sWOL );
5096 // surface = helper.GetSurface( F );
5098 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5099 eoe->_edgeSmoother->_anaCurve.Nullify();
5105 // check result of invalidation
5108 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5110 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5112 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5113 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5114 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5115 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5116 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5117 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5120 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5121 << " "<< tgtXYZ._node->GetID()
5122 << " "<< edge->_simplices[j]._nPrev->GetID()
5123 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5132 //================================================================================
5134 * \brief Create an offset surface
5136 //================================================================================
5138 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5140 if ( eos._offsetSurf.IsNull() ||
5141 eos._edgeForOffset == 0 ||
5142 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5145 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5148 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5149 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5150 double offset = baseSurface->Gap();
5152 eos._offsetSurf.Nullify();
5156 BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5157 if ( !offsetMaker.IsDone() ) return;
5159 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5160 if ( !fExp.More() ) return;
5162 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5163 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5164 if ( surf.IsNull() ) return;
5166 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5168 catch ( Standard_Failure )
5173 //================================================================================
5175 * \brief Put nodes of a curved FACE to its offset surface
5177 //================================================================================
5179 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5181 vector< _EdgesOnShape* >& eosC1,
5185 _EdgesOnShape * eof = & eos;
5186 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5189 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5191 if ( eosC1[i]->_offsetSurf.IsNull() ||
5192 eosC1[i]->ShapeType() != TopAbs_FACE ||
5193 eosC1[i]->_edgeForOffset == 0 ||
5194 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5196 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5201 eof->_offsetSurf.IsNull() ||
5202 eof->ShapeType() != TopAbs_FACE ||
5203 eof->_edgeForOffset == 0 ||
5204 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5207 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5208 for ( size_t i = 0; i < eos._edges.size(); ++i )
5210 _LayerEdge* edge = eos._edges[i];
5211 edge->Unset( _LayerEdge::MARKED );
5212 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5214 if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5217 int nbBlockedAround = 0;
5218 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5219 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5220 if ( nbBlockedAround > 1 )
5223 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5224 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5225 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5226 edge->_curvature->_uv = uv;
5227 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5229 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5230 gp_XYZ prevP = edge->PrevCheckPos();
5233 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5235 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5239 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5240 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5241 edge->_pos.back() = newP;
5243 edge->Set( _LayerEdge::MARKED );
5248 // dumpMove() for debug
5250 for ( ; i < eos._edges.size(); ++i )
5251 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5253 if ( i < eos._edges.size() )
5255 dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5256 << "_InfStep" << infStep << "_" << smooStep );
5257 for ( ; i < eos._edges.size(); ++i )
5259 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5260 dumpMove( eos._edges[i]->_nodes.back() );
5267 //================================================================================
5269 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5270 * _LayerEdge's to be in a consequent order
5272 //================================================================================
5274 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5276 SMESH_MesherHelper& helper)
5278 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5280 TopLoc_Location loc; double f,l;
5282 Handle(Geom_Line) line;
5283 Handle(Geom_Circle) circle;
5284 bool isLine, isCirc;
5285 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5287 // check if the EDGE is a line
5288 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5289 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5290 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5292 line = Handle(Geom_Line)::DownCast( curve );
5293 circle = Handle(Geom_Circle)::DownCast( curve );
5294 isLine = (!line.IsNull());
5295 isCirc = (!circle.IsNull());
5297 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5299 isLine = SMESH_Algo::IsStraight( E );
5302 line = new Geom_Line( gp::OX() ); // only type does matter
5304 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5309 else //////////////////////////////////////////////////////////////////////// 2D case
5311 if ( !eos._isRegularSWOL ) // 23190
5314 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5316 // check if the EDGE is a line
5317 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5318 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5319 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5321 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5322 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5323 isLine = (!line2d.IsNull());
5324 isCirc = (!circle2d.IsNull());
5326 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5329 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5330 while ( nIt->more() )
5331 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5332 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5334 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5335 for ( int i = 0; i < 2 && !isLine; ++i )
5336 isLine = ( size.Coord( i+1 ) <= lineTol );
5338 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5344 line = new Geom_Line( gp::OX() ); // only type does matter
5348 gp_Pnt2d p = circle2d->Location();
5349 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5350 circle = new Geom_Circle( ax, 1.); // only center position does matter
5359 return Handle(Geom_Curve)();
5362 //================================================================================
5364 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5366 //================================================================================
5368 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5369 Handle(ShapeAnalysis_Surface)& surface,
5370 const TopoDS_Face& F,
5371 SMESH_MesherHelper& helper)
5373 if ( !isAnalytic() ) return false;
5375 const size_t iFrom = 0, iTo = _eos._edges.size();
5377 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5379 if ( F.IsNull() ) // 3D
5381 SMESH_TNodeXYZ p0 ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5382 SMESH_TNodeXYZ p1 ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5383 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5384 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5385 gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5386 _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5387 _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5388 bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5389 vLE0->Is( _LayerEdge::BLOCKED ) ||
5390 vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5391 vLE1->Is( _LayerEdge::BLOCKED ));
5392 for ( size_t i = iFrom; i < iTo; ++i )
5394 _LayerEdge* edge = _eos._edges[i];
5395 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5396 newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5398 if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5400 gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5401 double shift = ( lineDir * ( newPos - pSrc0 ) -
5402 lineDir * ( curPos - pSrc0 ));
5403 newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5405 if ( edge->Is( _LayerEdge::BLOCKED ))
5407 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5408 double curThick = pSrc.SquareDistance( tgtNode );
5409 double newThink = ( pSrc - newPos ).SquareModulus();
5410 if ( newThink > curThick )
5413 edge->_pos.back() = newPos;
5414 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5415 dumpMove( tgtNode );
5420 _LayerEdge* e0 = getLEdgeOnV( 0 );
5421 _LayerEdge* e1 = getLEdgeOnV( 1 );
5422 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5423 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5424 if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5426 int iPeriodic = helper.GetPeriodicIndex();
5427 if ( iPeriodic == 1 || iPeriodic == 2 )
5429 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5430 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5431 std::swap( uv0, uv1 );
5434 const gp_XY rangeUV = uv1 - uv0;
5435 for ( size_t i = iFrom; i < iTo; ++i )
5437 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5438 gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5439 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5441 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5442 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5443 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5444 dumpMove( tgtNode );
5446 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5447 pos->SetUParameter( newUV.X() );
5448 pos->SetVParameter( newUV.Y() );
5454 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5456 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5457 gp_Pnt center3D = circle->Location();
5459 if ( F.IsNull() ) // 3D
5461 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5462 return true; // closed EDGE - nothing to do
5464 // circle is a real curve of EDGE
5465 gp_Circ circ = circle->Circ();
5467 // new center is shifted along its axis
5468 const gp_Dir& axis = circ.Axis().Direction();
5469 _LayerEdge* e0 = getLEdgeOnV(0);
5470 _LayerEdge* e1 = getLEdgeOnV(1);
5471 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5472 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5473 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5474 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5475 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5477 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5479 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5480 gp_Circ newCirc( newAxis, newRadius );
5481 gp_Vec vecC1 ( newCenter, p1 );
5483 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5487 for ( size_t i = iFrom; i < iTo; ++i )
5489 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5490 double u = uLast * _leParams[i];
5491 gp_Pnt p = ElCLib::Value( u, newCirc );
5492 _eos._edges[i]->_pos.back() = p.XYZ();
5494 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5495 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5496 dumpMove( tgtNode );
5502 const gp_XY center( center3D.X(), center3D.Y() );
5504 _LayerEdge* e0 = getLEdgeOnV(0);
5505 _LayerEdge* eM = _eos._edges[ 0 ];
5506 _LayerEdge* e1 = getLEdgeOnV(1);
5507 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5508 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5509 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5510 gp_Vec2d vec0( center, uv0 );
5511 gp_Vec2d vecM( center, uvM );
5512 gp_Vec2d vec1( center, uv1 );
5513 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5514 double uMidl = vec0.Angle( vecM );
5515 if ( uLast * uMidl <= 0. )
5516 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5517 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5519 gp_Ax2d axis( center, vec0 );
5520 gp_Circ2d circ( axis, radius );
5521 for ( size_t i = iFrom; i < iTo; ++i )
5523 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5524 double newU = uLast * _leParams[i];
5525 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5526 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5528 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5529 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5530 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5531 dumpMove( tgtNode );
5533 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5534 pos->SetUParameter( newUV.X() );
5535 pos->SetVParameter( newUV.Y() );
5544 //================================================================================
5546 * \brief smooth _LayerEdge's on a an EDGE
5548 //================================================================================
5550 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5551 Handle(ShapeAnalysis_Surface)& surface,
5552 const TopoDS_Face& F,
5553 SMESH_MesherHelper& helper)
5555 if ( _offPoints.empty() )
5558 // move _offPoints along normals of _LayerEdge's
5560 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5561 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5562 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5563 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5564 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5565 _leOnV[0]._len = e[0]->_len;
5566 _leOnV[1]._len = e[1]->_len;
5567 for ( size_t i = 0; i < _offPoints.size(); i++ )
5569 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5570 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5571 const double w0 = _offPoints[i]._2edges._wgt[0];
5572 const double w1 = _offPoints[i]._2edges._wgt[1];
5573 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5574 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5575 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5576 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5577 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5578 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5580 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5581 _offPoints[i]._len = avgLen;
5585 if ( !surface.IsNull() ) // project _offPoints to the FACE
5587 fTol = 100 * BRep_Tool::Tolerance( F );
5588 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5590 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5591 //if ( surface->Gap() < 0.5 * segLen )
5592 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5594 for ( size_t i = 1; i < _offPoints.size(); ++i )
5596 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5597 //if ( surface->Gap() < 0.5 * segLen )
5598 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5602 // project tgt nodes of extreme _LayerEdge's to the offset segments
5604 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5605 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5607 gp_Pnt pExtreme[2], pProj[2];
5608 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5610 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5611 int i = _iSeg[ is2nd ];
5612 int di = is2nd ? -1 : +1;
5613 bool projected = false;
5614 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5617 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5618 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5619 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5620 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5621 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5622 if ( dist < distMin || projected )
5625 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5628 else if ( dist > distPrev )
5630 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5636 while ( !projected &&
5637 i >= 0 && i+1 < (int)_offPoints.size() );
5641 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5644 _iSeg[1] = _offPoints.size()-2;
5645 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5650 if ( _iSeg[0] > _iSeg[1] )
5652 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5656 // adjust length of extreme LE (test viscous_layers_01/B7)
5657 gp_Vec vDiv0( pExtreme[0], pProj[0] );
5658 gp_Vec vDiv1( pExtreme[1], pProj[1] );
5659 double d0 = vDiv0.Magnitude();
5660 double d1 = vDiv1.Magnitude();
5661 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5662 else e[0]->_len -= d0;
5663 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5664 else e[1]->_len -= d1;
5666 // compute normalized length of the offset segments located between the projections
5668 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5669 vector< double > len( nbSeg + 1 );
5671 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5672 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5674 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5676 len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5678 // d0 *= e[0]->_lenFactor;
5679 // d1 *= e[1]->_lenFactor;
5680 double fullLen = len.back() - d0 - d1;
5681 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5682 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5684 // temporary replace extreme _offPoints by pExtreme
5685 gp_XYZ op[2] = { _offPoints[ _iSeg[0] ]._xyz,
5686 _offPoints[ _iSeg[1]+1 ]._xyz };
5687 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
5688 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5690 // distribute tgt nodes of _LayerEdge's between the projections
5693 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5695 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5696 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5698 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5699 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
5700 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5702 if ( surface.IsNull() )
5704 _eos._edges[i]->_pos.back() = p;
5706 else // project a new node position to a FACE
5708 gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5709 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5711 p = surface->Value( uv2 ).XYZ();
5712 _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5714 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5715 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5716 dumpMove( tgtNode );
5719 _offPoints[ _iSeg[0] ]._xyz = op[0];
5720 _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5725 //================================================================================
5727 * \brief Prepare for smoothing
5729 //================================================================================
5731 void _Smoother1D::prepare(_SolidData& data)
5733 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5734 _curveLen = SMESH_Algo::EdgeLength( E );
5736 // sort _LayerEdge's by position on the EDGE
5737 data.SortOnEdge( E, _eos._edges );
5739 // compute normalized param of _eos._edges on EDGE
5740 _leParams.resize( _eos._edges.size() + 1 );
5743 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5745 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5747 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5748 curLen = p.Distance( pPrev );
5749 _leParams[i+1] = _leParams[i] + curLen;
5752 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5753 for ( size_t i = 0; i < _leParams.size()-1; ++i )
5754 _leParams[i] = _leParams[i+1] / fullLen;
5760 // divide E to have offset segments with low deflection
5761 BRepAdaptor_Curve c3dAdaptor( E );
5762 const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5763 const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5764 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5765 if ( discret.NbPoints() <= 2 )
5767 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5771 const double u0 = c3dAdaptor.FirstParameter();
5772 gp_Pnt p; gp_Vec tangent;
5773 _offPoints.resize( discret.NbPoints() );
5774 for ( size_t i = 0; i < _offPoints.size(); i++ )
5776 double u = discret.Parameter( i+1 );
5777 c3dAdaptor.D1( u, p, tangent );
5778 _offPoints[i]._xyz = p.XYZ();
5779 _offPoints[i]._edgeDir = tangent.XYZ();
5780 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5783 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5786 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5787 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5788 _2NearEdges tmp2edges;
5789 tmp2edges._edges[1] = _eos._edges[0];
5790 _leOnV[0]._2neibors = & tmp2edges;
5791 _leOnV[0]._nodes = leOnV[0]->_nodes;
5792 _leOnV[1]._nodes = leOnV[1]->_nodes;
5793 _LayerEdge* eNext, *ePrev = & _leOnV[0];
5794 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5796 // find _LayerEdge's located before and after an offset point
5797 // (_eos._edges[ iLE ] is next after ePrev)
5798 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5799 ePrev = _eos._edges[ iLE++ ];
5800 eNext = ePrev->_2neibors->_edges[1];
5802 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5803 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5804 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5805 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5808 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5809 for ( size_t i = 0; i < _offPoints.size(); i++ )
5810 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5811 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5813 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5814 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5815 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5818 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5820 int iLBO = _offPoints.size() - 2; // last but one
5822 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5823 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5825 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5826 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5827 _leOnV[ 0 ]._len = 0;
5828 _leOnV[ 1 ]._len = 0;
5829 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
5830 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5833 _iSeg[1] = _offPoints.size()-2;
5835 // initialize OffPnt::_len
5836 for ( size_t i = 0; i < _offPoints.size(); ++i )
5837 _offPoints[i]._len = 0;
5839 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5841 _leOnV[0]._len = leOnV[0]->_len;
5842 _leOnV[1]._len = leOnV[1]->_len;
5843 for ( size_t i = 0; i < _offPoints.size(); i++ )
5845 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5846 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5847 const double w0 = _offPoints[i]._2edges._wgt[0];
5848 const double w1 = _offPoints[i]._2edges._wgt[1];
5849 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5850 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5851 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5852 _offPoints[i]._xyz = avgXYZ;
5853 _offPoints[i]._len = avgLen;
5858 //================================================================================
5860 * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5862 //================================================================================
5864 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5865 const gp_XYZ& edgeDir)
5867 gp_XYZ cross = normal ^ edgeDir;
5868 gp_XYZ norm = edgeDir ^ cross;
5869 double size = norm.Modulus();
5874 //================================================================================
5876 * \brief Sort _LayerEdge's by a parameter on a given EDGE
5878 //================================================================================
5880 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
5881 vector< _LayerEdge* >& edges)
5883 map< double, _LayerEdge* > u2edge;
5884 for ( size_t i = 0; i < edges.size(); ++i )
5885 u2edge.insert( u2edge.end(),
5886 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5888 ASSERT( u2edge.size() == edges.size() );
5889 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5890 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5891 edges[i] = u2e->second;
5893 Sort2NeiborsOnEdge( edges );
5896 //================================================================================
5898 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5900 //================================================================================
5902 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5904 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5906 for ( size_t i = 0; i < edges.size()-1; ++i )
5907 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5908 edges[i]->_2neibors->reverse();
5910 const size_t iLast = edges.size() - 1;
5911 if ( edges.size() > 1 &&
5912 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5913 edges[iLast]->_2neibors->reverse();
5916 //================================================================================
5918 * \brief Return _EdgesOnShape* corresponding to the shape
5920 //================================================================================
5922 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5924 if ( shapeID < (int)_edgesOnShape.size() &&
5925 _edgesOnShape[ shapeID ]._shapeID == shapeID )
5926 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5928 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5929 if ( _edgesOnShape[i]._shapeID == shapeID )
5930 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5935 //================================================================================
5937 * \brief Return _EdgesOnShape* corresponding to the shape
5939 //================================================================================
5941 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5943 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5944 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5947 //================================================================================
5949 * \brief Prepare data of the _LayerEdge for smoothing on FACE
5951 //================================================================================
5953 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5955 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5957 set< TGeomID > vertices;
5959 if ( eos->ShapeType() == TopAbs_FACE )
5961 // check FACE concavity and get concave VERTEXes
5962 F = TopoDS::Face( eos->_shape );
5963 if ( isConcave( F, helper, &vertices ))
5964 _concaveFaces.insert( eos->_shapeID );
5966 // set eos._eosConcaVer
5967 eos->_eosConcaVer.clear();
5968 eos->_eosConcaVer.reserve( vertices.size() );
5969 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5971 _EdgesOnShape* eov = GetShapeEdges( *v );
5972 if ( eov && eov->_edges.size() == 1 )
5974 eos->_eosConcaVer.push_back( eov );
5975 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5976 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5980 // SetSmooLen() to _LayerEdge's on FACE
5981 for ( size_t i = 0; i < eos->_edges.size(); ++i )
5983 eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5985 SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5986 while ( smIt->more() ) // loop on sub-shapes of the FACE
5988 _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5989 if ( !eoe ) continue;
5991 vector<_LayerEdge*>& eE = eoe->_edges;
5992 for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5994 if ( eE[iE]->_cosin <= theMinSmoothCosin )
5997 SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5998 while ( segIt->more() )
6000 const SMDS_MeshElement* seg = segIt->next();
6001 if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6003 if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6004 continue; // not to check a seg twice
6005 for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6007 _LayerEdge* eN = eE[iE]->_neibors[iN];
6008 if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6010 double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6011 double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6012 eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6013 eN->Set( _LayerEdge::NEAR_BOUNDARY );
6018 } // if ( eos->ShapeType() == TopAbs_FACE )
6020 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6022 eos->_edges[i]->_smooFunction = 0;
6023 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6025 bool isCurved = false;
6026 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6028 _LayerEdge* edge = eos->_edges[i];
6030 // get simplices sorted
6031 _Simplex::SortSimplices( edge->_simplices );
6033 // smoothing function
6034 edge->ChooseSmooFunction( vertices, _n2eMap );
6037 double avgNormProj = 0, avgLen = 0;
6038 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6040 _Simplex& s = edge->_simplices[iS];
6042 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6043 avgNormProj += edge->_normal * vec;
6044 avgLen += vec.Modulus();
6045 if ( substituteSrcNodes )
6047 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6048 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6051 avgNormProj /= edge->_simplices.size();
6052 avgLen /= edge->_simplices.size();
6053 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6056 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6058 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6059 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6061 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6065 // prepare for putOnOffsetSurface()
6066 if (( eos->ShapeType() == TopAbs_FACE ) &&
6067 ( isCurved || !eos->_eosConcaVer.empty() ))
6069 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6070 eos->_edgeForOffset = 0;
6072 double maxCosin = -1;
6073 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6075 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6076 if ( !eoe || eoe->_edges.empty() ) continue;
6078 vector<_LayerEdge*>& eE = eoe->_edges;
6079 _LayerEdge* e = eE[ eE.size() / 2 ];
6080 if ( e->_cosin > maxCosin )
6082 eos->_edgeForOffset = e;
6083 maxCosin = e->_cosin;
6089 //================================================================================
6091 * \brief Add faces for smoothing
6093 //================================================================================
6095 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6096 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6098 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6099 for ( ; eos != eosToSmooth.end(); ++eos )
6101 if ( !*eos || (*eos)->_toSmooth ) continue;
6103 (*eos)->_toSmooth = true;
6105 if ( (*eos)->ShapeType() == TopAbs_FACE )
6107 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6108 (*eos)->_toSmooth = true;
6112 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6113 if ( edgesNoAnaSmooth )
6114 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6116 if ( (*eos)->_edgeSmoother )
6117 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6121 //================================================================================
6123 * \brief Limit _LayerEdge::_maxLen according to local curvature
6125 //================================================================================
6127 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6129 // find intersection of neighbor _LayerEdge's to limit _maxLen
6130 // according to local curvature (IPAL52648)
6132 // This method must be called after findCollisionEdges() where _LayerEdge's
6133 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6135 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6137 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6138 if ( eosI._edges.empty() ) continue;
6139 if ( !eosI._hyp.ToSmooth() )
6141 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6143 _LayerEdge* eI = eosI._edges[i];
6144 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6146 _LayerEdge* eN = eI->_neibors[iN];
6147 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6149 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6150 limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6155 else if ( eosI.ShapeType() == TopAbs_EDGE )
6157 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6158 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6160 _LayerEdge* e0 = eosI._edges[0];
6161 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6163 _LayerEdge* eI = eosI._edges[i];
6164 limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6171 //================================================================================
6173 * \brief Limit _LayerEdge::_maxLen according to local curvature
6175 //================================================================================
6177 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6179 _EdgesOnShape& eos1,
6180 _EdgesOnShape& eos2,
6181 SMESH_MesherHelper& helper )
6183 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6184 double norSize = plnNorm.SquareModulus();
6185 if ( norSize < std::numeric_limits<double>::min() )
6186 return; // parallel normals
6188 // find closest points of skew _LayerEdge's
6189 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6190 gp_XYZ dir12 = src2 - src1;
6191 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6192 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6193 double dot1 = perp2 * e1->_normal;
6194 double dot2 = perp1 * e2->_normal;
6195 double u1 = ( perp2 * dir12 ) / dot1;
6196 double u2 = - ( perp1 * dir12 ) / dot2;
6197 if ( u1 > 0 && u2 > 0 )
6199 double ovl = ( u1 * e1->_normal * dir12 -
6200 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6201 if ( ovl > theSmoothThickToElemSizeRatio )
6203 e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6204 e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6209 //================================================================================
6211 * \brief Fill data._collisionEdges
6213 //================================================================================
6215 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6217 data._collisionEdges.clear();
6219 // set the full thickness of the layers to LEs
6220 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6222 _EdgesOnShape& eos = data._edgesOnShape[iS];
6223 if ( eos._edges.empty() ) continue;
6224 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6226 for ( size_t i = 0; i < eos._edges.size(); ++i )
6228 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6229 double maxLen = eos._edges[i]->_maxLen;
6230 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6231 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6232 eos._edges[i]->_maxLen = maxLen;
6236 // make temporary quadrangles got by extrusion of
6237 // mesh edges along _LayerEdge._normal's
6239 vector< const SMDS_MeshElement* > tmpFaces;
6241 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6243 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6244 if ( eos.ShapeType() != TopAbs_EDGE )
6246 if ( eos._edges.empty() )
6248 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6249 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6250 while ( smIt->more() )
6251 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6252 if ( eov->_edges.size() == 1 )
6253 edge[ bool( edge[0]) ] = eov->_edges[0];
6257 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6258 tmpFaces.push_back( f );
6261 for ( size_t i = 0; i < eos._edges.size(); ++i )
6263 _LayerEdge* edge = eos._edges[i];
6264 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6266 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6267 if ( src2->GetPosition()->GetDim() > 0 &&
6268 src2->GetID() < edge->_nodes[0]->GetID() )
6269 continue; // avoid using same segment twice
6271 // a _LayerEdge containg tgt2
6272 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6274 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6275 tmpFaces.push_back( f );
6280 // Find _LayerEdge's intersecting tmpFaces.
6282 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6284 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6285 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6287 double dist1, dist2, segLen, eps = 0.5;
6288 _CollisionEdges collEdges;
6289 vector< const SMDS_MeshElement* > suspectFaces;
6290 const double angle45 = Cos( 45. * M_PI / 180. );
6292 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6294 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6295 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6297 // find sub-shapes whose VL can influence VL on eos
6298 set< TGeomID > neighborShapes;
6299 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6300 while ( const TopoDS_Shape* face = fIt->next() )
6302 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6303 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6305 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6306 while ( subIt->more() )
6307 neighborShapes.insert( subIt->next()->GetId() );
6310 if ( eos.ShapeType() == TopAbs_VERTEX )
6312 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6313 while ( const TopoDS_Shape* edge = eIt->next() )
6314 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6316 // find intersecting _LayerEdge's
6317 for ( size_t i = 0; i < eos._edges.size(); ++i )
6319 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6320 _LayerEdge* edge = eos._edges[i];
6321 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6324 gp_Vec eSegDir0, eSegDir1;
6325 if ( edge->IsOnEdge() )
6327 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6328 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6329 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6331 suspectFaces.clear();
6332 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6333 SMDSAbs_Face, suspectFaces );
6334 collEdges._intEdges.clear();
6335 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6337 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6338 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6339 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6340 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6341 if ( edge->IsOnEdge() ) {
6342 if ( edge->_2neibors->include( f->_le1 ) ||
6343 edge->_2neibors->include( f->_le2 )) continue;
6346 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6347 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6349 dist1 = dist2 = Precision::Infinite();
6350 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6351 dist1 = Precision::Infinite();
6352 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6353 dist2 = Precision::Infinite();
6354 if (( dist1 > segLen ) && ( dist2 > segLen ))
6357 if ( edge->IsOnEdge() )
6359 // skip perpendicular EDGEs
6360 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6361 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6362 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6363 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6364 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6369 // either limit inflation of edges or remember them for updating _normal
6370 // double dot = edge->_normal * f->GetDir();
6373 collEdges._intEdges.push_back( f->_le1 );
6374 collEdges._intEdges.push_back( f->_le2 );
6378 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6379 // edge->_maxLen = Min( shortLen, edge->_maxLen );
6383 if ( !collEdges._intEdges.empty() )
6385 collEdges._edge = edge;
6386 data._collisionEdges.push_back( collEdges );
6391 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6394 // restore the zero thickness
6395 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6397 _EdgesOnShape& eos = data._edgesOnShape[iS];
6398 if ( eos._edges.empty() ) continue;
6399 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6401 for ( size_t i = 0; i < eos._edges.size(); ++i )
6403 eos._edges[i]->InvalidateStep( 1, eos );
6404 eos._edges[i]->_len = 0;
6409 //================================================================================
6411 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6412 * _LayerEdge's on neighbor EDGE's
6414 //================================================================================
6416 bool _ViscousBuilder::updateNormals( _SolidData& data,
6417 SMESH_MesherHelper& helper,
6421 updateNormalsOfC1Vertices( data );
6423 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6426 // map to store new _normal and _cosin for each intersected edge
6427 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6428 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6429 _LayerEdge zeroEdge;
6430 zeroEdge._normal.SetCoord( 0,0,0 );
6431 zeroEdge._maxLen = Precision::Infinite();
6432 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6434 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6436 double segLen, dist1, dist2, dist;
6437 vector< pair< _LayerEdge*, double > > intEdgesDist;
6438 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6440 for ( int iter = 0; iter < 5; ++iter )
6442 edge2newEdge.clear();
6444 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6446 _CollisionEdges& ce = data._collisionEdges[iE];
6447 _LayerEdge* edge1 = ce._edge;
6448 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6449 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6450 if ( !eos1 ) continue;
6452 // detect intersections
6453 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6454 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6456 intEdgesDist.clear();
6457 double minIntDist = Precision::Infinite();
6458 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6460 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6461 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6462 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6464 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6465 double fact = ( 1.1 + dot * dot );
6466 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6467 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6468 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6469 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6470 dist1 = dist2 = Precision::Infinite();
6471 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
6472 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6475 if ( dist > testLen || dist <= 0 )
6478 if ( dist > testLen || dist <= 0 )
6481 // choose a closest edge
6482 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6483 double d1 = intP.SquareDistance( pSrc0 );
6484 double d2 = intP.SquareDistance( pSrc1 );
6485 int iClose = i + ( d2 < d1 );
6486 _LayerEdge* edge2 = ce._intEdges[iClose];
6487 edge2->Unset( _LayerEdge::MARKED );
6489 // choose a closest edge among neighbors
6490 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6491 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6492 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6494 _LayerEdge * edgeJ = intEdgesDist[j].first;
6495 if ( edge2->IsNeiborOnEdge( edgeJ ))
6497 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6498 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6501 intEdgesDist.push_back( make_pair( edge2, dist ));
6502 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6504 // iClose = i + !( d2 < d1 );
6505 // intEdges.push_back( ce._intEdges[iClose] );
6506 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6508 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6513 // compute new _normals
6514 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6516 _LayerEdge* edge2 = intEdgesDist[i].first;
6517 double distWgt = edge1->_len / intEdgesDist[i].second;
6518 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6519 // edge2->Is( _LayerEdge::BLOCKED )) continue;
6520 if ( edge2->Is( _LayerEdge::MARKED )) continue;
6521 edge2->Set( _LayerEdge::MARKED );
6524 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6526 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6527 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6528 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6529 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6530 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6531 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6532 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6533 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6534 newNormal.Normalize();
6538 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6539 if ( cos1 < theMinSmoothCosin )
6541 newCos = cos2 * sgn1;
6543 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6545 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6549 newCos = edge1->_cosin;
6552 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6553 e2neIt->second._normal += distWgt * newNormal;
6554 e2neIt->second._cosin = newCos;
6555 e2neIt->second._maxLen = 0.7 * minIntDist / edge1->_lenFactor;
6556 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6557 e2neIt->second._normal += dir2;
6558 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6559 e2neIt->second._normal += distWgt * newNormal;
6560 e2neIt->second._cosin = edge2->_cosin;
6561 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6562 e2neIt->second._normal += dir1;
6566 if ( edge2newEdge.empty() )
6567 break; //return true;
6569 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6571 // Update data of edges depending on a new _normal
6574 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6576 _LayerEdge* edge = e2neIt->first;
6577 if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6578 _LayerEdge& newEdge = e2neIt->second;
6579 _EdgesOnShape* eos = data.GetShapeEdges( edge );
6581 // Check if a new _normal is OK:
6582 newEdge._normal.Normalize();
6583 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6585 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6587 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6588 edge->_maxLen = newEdge._maxLen;
6589 edge->SetNewLength( newEdge._maxLen, *eos, helper );
6591 continue; // the new _normal is bad
6593 // the new _normal is OK
6595 // find shapes that need smoothing due to change of _normal
6596 if ( edge->_cosin < theMinSmoothCosin &&
6597 newEdge._cosin > theMinSmoothCosin )
6599 if ( eos->_sWOL.IsNull() )
6601 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6602 while ( fIt->more() )
6603 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6605 else // edge inflates along a FACE
6607 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6608 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6609 while ( const TopoDS_Shape* E = eIt->next() )
6611 if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6613 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6614 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6615 if ( angle < M_PI / 2 )
6616 shapesToSmooth.insert( data.GetShapeEdges( *E ));
6621 double len = edge->_len;
6622 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6623 edge->SetNormal( newEdge._normal );
6624 edge->SetCosin( newEdge._cosin );
6625 edge->SetNewLength( len, *eos, helper );
6626 edge->Set( _LayerEdge::MARKED );
6627 edge->Set( _LayerEdge::NORMAL_UPDATED );
6628 edgesNoAnaSmooth.insert( eos );
6631 // Update normals and other dependent data of not intersecting _LayerEdge's
6632 // neighboring the intersecting ones
6634 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6636 _LayerEdge* edge1 = e2neIt->first;
6637 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6638 if ( !edge1->Is( _LayerEdge::MARKED ))
6641 if ( edge1->IsOnEdge() )
6643 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6644 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6645 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6648 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6650 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6652 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6653 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6654 continue; // j-th neighbor is also intersected
6655 _LayerEdge* prevEdge = edge1;
6656 const int nbSteps = 10;
6657 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6659 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6660 neighbor->Is( _LayerEdge::MARKED ))
6662 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6663 if ( !eos ) continue;
6664 _LayerEdge* nextEdge = neighbor;
6665 if ( neighbor->_2neibors )
6668 nextEdge = neighbor->_2neibors->_edges[iNext];
6669 if ( nextEdge == prevEdge )
6670 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6672 double r = double(step-1)/nbSteps/(iter+1);
6673 if ( !nextEdge->_2neibors )
6676 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6677 newNorm.Normalize();
6678 if ( !isNewNormalOk( data, *neighbor, newNorm ))
6681 double len = neighbor->_len;
6682 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6683 neighbor->SetNormal( newNorm );
6684 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6685 if ( neighbor->_2neibors )
6686 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6687 neighbor->SetNewLength( len, *eos, helper );
6688 neighbor->Set( _LayerEdge::MARKED );
6689 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6690 edgesNoAnaSmooth.insert( eos );
6692 if ( !neighbor->_2neibors )
6693 break; // neighbor is on VERTEX
6695 // goto the next neighbor
6696 prevEdge = neighbor;
6697 neighbor = nextEdge;
6704 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6709 //================================================================================
6711 * \brief Check if a new normal is OK
6713 //================================================================================
6715 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
6717 const gp_XYZ& newNormal)
6719 // check a min angle between the newNormal and surrounding faces
6720 vector<_Simplex> simplices;
6721 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6722 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6723 double newMinDot = 1, curMinDot = 1;
6724 for ( size_t i = 0; i < simplices.size(); ++i )
6726 n1.Set( simplices[i]._nPrev );
6727 n2.Set( simplices[i]._nNext );
6728 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6729 double normLen2 = normFace.SquareModulus();
6730 if ( normLen2 < std::numeric_limits<double>::min() )
6732 normFace /= Sqrt( normLen2 );
6733 newMinDot = Min( newNormal * normFace, newMinDot );
6734 curMinDot = Min( edge._normal * normFace, curMinDot );
6737 if ( newMinDot < 0.5 )
6739 ok = ( newMinDot >= curMinDot * 0.9 );
6740 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6741 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6742 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6748 //================================================================================
6750 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6752 //================================================================================
6754 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
6755 SMESH_MesherHelper& helper,
6757 const double stepSize )
6759 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6760 return true; // no shapes needing smoothing
6762 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6764 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6765 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
6766 !eos._hyp.ToSmooth() ||
6767 eos.ShapeType() != TopAbs_FACE ||
6768 eos._edges.empty() )
6771 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6772 if ( !toSmooth ) continue;
6774 for ( size_t i = 0; i < eos._edges.size(); ++i )
6776 _LayerEdge* edge = eos._edges[i];
6777 if ( !edge->Is( _LayerEdge::SMOOTHED ))
6779 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6782 const gp_XYZ& pPrev = edge->PrevPos();
6783 const gp_XYZ& pLast = edge->_pos.back();
6784 gp_XYZ stepVec = pLast - pPrev;
6785 double realStepSize = stepVec.Modulus();
6786 if ( realStepSize < numeric_limits<double>::min() )
6789 edge->_lenFactor = realStepSize / stepSize;
6790 edge->_normal = stepVec / realStepSize;
6791 edge->Set( _LayerEdge::NORMAL_UPDATED );
6798 //================================================================================
6800 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6802 //================================================================================
6804 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6806 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6808 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6809 if ( eov._eosC1.empty() ||
6810 eov.ShapeType() != TopAbs_VERTEX ||
6811 eov._edges.empty() )
6814 gp_XYZ newNorm = eov._edges[0]->_normal;
6815 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6816 bool normChanged = false;
6818 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6820 _EdgesOnShape* eoe = eov._eosC1[i];
6821 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6822 const double eLen = SMESH_Algo::EdgeLength( e );
6823 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
6824 if ( oppV.IsSame( eov._shape ))
6825 oppV = SMESH_MesherHelper::IthVertex( 1, e );
6826 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6827 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6828 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6830 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6831 if ( curThickOpp + curThick < eLen )
6834 double wgt = 2. * curThick / eLen;
6835 newNorm += wgt * eovOpp->_edges[0]->_normal;
6840 eov._edges[0]->SetNormal( newNorm.Normalized() );
6841 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6846 //================================================================================
6848 * \brief Modify normals of _LayerEdge's on _ConvexFace's
6850 //================================================================================
6852 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
6853 SMESH_MesherHelper& helper,
6856 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6859 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6860 for ( ; id2face != data._convexFaces.end(); ++id2face )
6862 _ConvexFace & convFace = (*id2face).second;
6863 if ( convFace._normalsFixed )
6864 continue; // already fixed
6865 if ( convFace.CheckPrisms() )
6866 continue; // nothing to fix
6868 convFace._normalsFixed = true;
6870 BRepAdaptor_Surface surface ( convFace._face, false );
6871 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
6873 // check if the convex FACE is of spherical shape
6875 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6879 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6880 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6882 _EdgesOnShape& eos = *(id2eos->second);
6883 if ( eos.ShapeType() == TopAbs_VERTEX )
6885 _LayerEdge* ledge = eos._edges[ 0 ];
6886 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6887 centersBox.Add( center );
6889 for ( size_t i = 0; i < eos._edges.size(); ++i )
6890 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6892 if ( centersBox.IsVoid() )
6894 debugMsg( "Error: centersBox.IsVoid()" );
6897 const bool isSpherical =
6898 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6900 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6901 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6905 // set _LayerEdge::_normal as average of all normals
6907 // WARNING: different density of nodes on EDGEs is not taken into account that
6908 // can lead to an improper new normal
6910 gp_XYZ avgNormal( 0,0,0 );
6912 id2eos = convFace._subIdToEOS.begin();
6913 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6915 _EdgesOnShape& eos = *(id2eos->second);
6916 // set data of _CentralCurveOnEdge
6917 if ( eos.ShapeType() == TopAbs_EDGE )
6919 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6920 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6921 if ( !eos._sWOL.IsNull() )
6922 ceCurve._adjFace.Nullify();
6924 ceCurve._ledges.insert( ceCurve._ledges.end(),
6925 eos._edges.begin(), eos._edges.end());
6927 // summarize normals
6928 for ( size_t i = 0; i < eos._edges.size(); ++i )
6929 avgNormal += eos._edges[ i ]->_normal;
6931 double normSize = avgNormal.SquareModulus();
6932 if ( normSize < 1e-200 )
6934 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6937 avgNormal /= Sqrt( normSize );
6939 // compute new _LayerEdge::_cosin on EDGEs
6940 double avgCosin = 0;
6943 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6945 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6946 if ( ceCurve._adjFace.IsNull() )
6948 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6950 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6951 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6954 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6955 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6956 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6962 avgCosin /= nbCosin;
6964 // set _LayerEdge::_normal = avgNormal
6965 id2eos = convFace._subIdToEOS.begin();
6966 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6968 _EdgesOnShape& eos = *(id2eos->second);
6969 if ( eos.ShapeType() != TopAbs_EDGE )
6970 for ( size_t i = 0; i < eos._edges.size(); ++i )
6971 eos._edges[ i ]->_cosin = avgCosin;
6973 for ( size_t i = 0; i < eos._edges.size(); ++i )
6975 eos._edges[ i ]->SetNormal( avgNormal );
6976 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6980 else // if ( isSpherical )
6982 // We suppose that centers of curvature at all points of the FACE
6983 // lie on some curve, let's call it "central curve". For all _LayerEdge's
6984 // having a common center of curvature we define the same new normal
6985 // as a sum of normals of _LayerEdge's on EDGEs among them.
6987 // get all centers of curvature for each EDGE
6989 helper.SetSubShape( convFace._face );
6990 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6992 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6993 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6995 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6997 // set adjacent FACE
6998 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7000 // get _LayerEdge's of the EDGE
7001 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7002 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7003 if ( !eos || eos->_edges.empty() )
7005 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7006 for ( int iV = 0; iV < 2; ++iV )
7008 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7009 TGeomID vID = meshDS->ShapeToIndex( v );
7010 eos = data.GetShapeEdges( vID );
7011 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7013 edgeLEdge = &vertexLEdges[0];
7014 edgeLEdgeEnd = edgeLEdge + 2;
7016 centerCurves[ iE ]._adjFace.Nullify();
7020 if ( ! eos->_toSmooth )
7021 data.SortOnEdge( edge, eos->_edges );
7022 edgeLEdge = &eos->_edges[ 0 ];
7023 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7024 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7025 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7027 if ( ! eos->_sWOL.IsNull() )
7028 centerCurves[ iE ]._adjFace.Nullify();
7031 // Get curvature centers
7035 if ( edgeLEdge[0]->IsOnEdge() &&
7036 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7038 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7039 centersBox.Add( center );
7041 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7042 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7043 { // EDGE or VERTEXes
7044 centerCurves[ iE ].Append( center, *edgeLEdge );
7045 centersBox.Add( center );
7047 if ( edgeLEdge[-1]->IsOnEdge() &&
7048 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7050 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7051 centersBox.Add( center );
7053 centerCurves[ iE ]._isDegenerated =
7054 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7056 } // loop on EDGES of convFace._face to set up data of centerCurves
7058 // Compute new normals for _LayerEdge's on EDGEs
7060 double avgCosin = 0;
7063 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7065 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7066 if ( ceCurve._isDegenerated )
7068 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7069 vector< gp_XYZ > & newNormals = ceCurve._normals;
7070 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7073 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7076 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7078 if ( isOK && !ceCurve._adjFace.IsNull() )
7080 // compute new _LayerEdge::_cosin
7081 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7082 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7085 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7086 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7087 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7093 // set new normals to _LayerEdge's of NOT degenerated central curves
7094 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7096 if ( centerCurves[ iE ]._isDegenerated )
7098 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7100 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7101 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7104 // set new normals to _LayerEdge's of degenerated central curves
7105 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7107 if ( !centerCurves[ iE ]._isDegenerated ||
7108 centerCurves[ iE ]._ledges.size() < 3 )
7110 // new normal is an average of new normals at VERTEXes that
7111 // was computed on non-degenerated _CentralCurveOnEdge's
7112 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7113 centerCurves[ iE ]._ledges.back ()->_normal );
7114 double sz = newNorm.Modulus();
7118 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7119 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7120 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7122 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7123 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7124 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7128 // Find new normals for _LayerEdge's based on FACE
7131 avgCosin /= nbCosin;
7132 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7133 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7134 if ( id2eos != convFace._subIdToEOS.end() )
7138 _EdgesOnShape& eos = * ( id2eos->second );
7139 for ( size_t i = 0; i < eos._edges.size(); ++i )
7141 _LayerEdge* ledge = eos._edges[ i ];
7142 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7144 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7146 iE = iE % centerCurves.size();
7147 if ( centerCurves[ iE ]._isDegenerated )
7149 newNorm.SetCoord( 0,0,0 );
7150 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7152 ledge->SetNormal( newNorm );
7153 ledge->_cosin = avgCosin;
7154 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7161 } // not a quasi-spherical FACE
7163 // Update _LayerEdge's data according to a new normal
7165 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7166 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7168 id2eos = convFace._subIdToEOS.begin();
7169 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7171 _EdgesOnShape& eos = * ( id2eos->second );
7172 for ( size_t i = 0; i < eos._edges.size(); ++i )
7174 _LayerEdge* & ledge = eos._edges[ i ];
7175 double len = ledge->_len;
7176 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7177 ledge->SetCosin( ledge->_cosin );
7178 ledge->SetNewLength( len, eos, helper );
7180 if ( eos.ShapeType() != TopAbs_FACE )
7181 for ( size_t i = 0; i < eos._edges.size(); ++i )
7183 _LayerEdge* ledge = eos._edges[ i ];
7184 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7186 _LayerEdge* neibor = ledge->_neibors[iN];
7187 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7189 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7190 neibor->Set( _LayerEdge::MOVED );
7191 neibor->SetSmooLen( neibor->_len );
7195 } // loop on sub-shapes of convFace._face
7197 // Find FACEs adjacent to convFace._face that got necessity to smooth
7198 // as a result of normals modification
7200 set< _EdgesOnShape* > adjFacesToSmooth;
7201 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7203 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7204 centerCurves[ iE ]._adjFaceToSmooth )
7206 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7208 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7210 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7215 data.AddShapesToSmooth( adjFacesToSmooth );
7220 } // loop on data._convexFaces
7225 //================================================================================
7227 * \brief Finds a center of curvature of a surface at a _LayerEdge
7229 //================================================================================
7231 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7232 BRepLProp_SLProps& surfProp,
7233 SMESH_MesherHelper& helper,
7234 gp_Pnt & center ) const
7236 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7237 surfProp.SetParameters( uv.X(), uv.Y() );
7238 if ( !surfProp.IsCurvatureDefined() )
7241 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7242 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7243 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7244 if ( surfCurvatureMin > surfCurvatureMax )
7245 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7247 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7252 //================================================================================
7254 * \brief Check that prisms are not distorted
7256 //================================================================================
7258 bool _ConvexFace::CheckPrisms() const
7261 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7263 const _LayerEdge* edge = _simplexTestEdges[i];
7264 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7265 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7266 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7268 debugMsg( "Bad simplex of _simplexTestEdges ("
7269 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7270 << " "<< edge->_simplices[j]._nPrev->GetID()
7271 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7278 //================================================================================
7280 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7281 * stored in this _CentralCurveOnEdge.
7282 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7283 * \param [in,out] newNormal - current normal at this point, to be redefined
7284 * \return bool - true if succeeded.
7286 //================================================================================
7288 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7290 if ( this->_isDegenerated )
7293 // find two centers the given one lies between
7295 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7297 double sl2 = 1.001 * _segLength2[ i ];
7299 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7303 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7304 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7309 double r = d1 / ( d1 + d2 );
7310 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7311 ( r ) * _ledges[ i+1 ]->_normal );
7315 double sz = newNormal.Modulus();
7324 //================================================================================
7326 * \brief Set shape members
7328 //================================================================================
7330 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7331 const _ConvexFace& convFace,
7333 SMESH_MesherHelper& helper)
7337 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7338 while ( const TopoDS_Shape* F = fIt->next())
7339 if ( !convFace._face.IsSame( *F ))
7341 _adjFace = TopoDS::Face( *F );
7342 _adjFaceToSmooth = false;
7343 // _adjFace already in a smoothing queue ?
7344 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7345 _adjFaceToSmooth = eos->_toSmooth;
7350 //================================================================================
7352 * \brief Looks for intersection of it's last segment with faces
7353 * \param distance - returns shortest distance from the last node to intersection
7355 //================================================================================
7357 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7359 const double& epsilon,
7361 const SMDS_MeshElement** intFace)
7363 vector< const SMDS_MeshElement* > suspectFaces;
7365 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7366 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7368 bool segmentIntersected = false;
7369 distance = Precision::Infinite();
7370 int iFace = -1; // intersected face
7371 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7373 const SMDS_MeshElement* face = suspectFaces[j];
7374 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7375 face->GetNodeIndex( _nodes[0] ) >= 0 )
7376 continue; // face sharing _LayerEdge node
7377 const int nbNodes = face->NbCornerNodes();
7378 bool intFound = false;
7380 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7383 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7387 const SMDS_MeshNode* tria[3];
7390 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7393 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7399 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7400 segmentIntersected = true;
7401 if ( distance > dist )
7402 distance = dist, iFace = j;
7405 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7409 if ( segmentIntersected )
7412 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7413 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7414 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7415 << ", intersection with face ("
7416 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7417 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7418 << ") distance = " << distance << endl;
7422 return segmentIntersected;
7425 //================================================================================
7427 * \brief Returns a point used to check orientation of _simplices
7429 //================================================================================
7431 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7433 size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7435 if ( !eos || eos->_sWOL.IsNull() )
7438 if ( eos->SWOLType() == TopAbs_EDGE )
7440 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7442 //else // TopAbs_FACE
7444 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7447 //================================================================================
7449 * \brief Returns size and direction of the last segment
7451 //================================================================================
7453 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7455 // find two non-coincident positions
7456 gp_XYZ orig = _pos.back();
7458 int iPrev = _pos.size() - 2;
7459 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7460 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7461 while ( iPrev >= 0 )
7463 vec = orig - _pos[iPrev];
7464 if ( vec.SquareModulus() > tol*tol )
7474 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7475 segDir.SetDirection( _normal );
7480 gp_Pnt pPrev = _pos[ iPrev ];
7481 if ( !eos._sWOL.IsNull() )
7483 TopLoc_Location loc;
7484 if ( eos.SWOLType() == TopAbs_EDGE )
7487 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7488 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7492 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7493 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7495 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7497 segDir.SetLocation( pPrev );
7498 segDir.SetDirection( vec );
7499 segLen = vec.Modulus();
7505 //================================================================================
7507 * \brief Return the last position of the target node on a FACE.
7508 * \param [in] F - the FACE this _LayerEdge is inflated along
7509 * \return gp_XY - result UV
7511 //================================================================================
7513 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7515 if ( F.IsSame( eos._sWOL )) // F is my FACE
7516 return gp_XY( _pos.back().X(), _pos.back().Y() );
7518 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7519 return gp_XY( 1e100, 1e100 );
7521 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7522 double f, l, u = _pos.back().X();
7523 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7524 if ( !C2d.IsNull() && f <= u && u <= l )
7525 return C2d->Value( u ).XY();
7527 return gp_XY( 1e100, 1e100 );
7530 //================================================================================
7532 * \brief Test intersection of the last segment with a given triangle
7533 * using Moller-Trumbore algorithm
7534 * Intersection is detected if distance to intersection is less than _LayerEdge._len
7536 //================================================================================
7538 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7539 const gp_XYZ& vert0,
7540 const gp_XYZ& vert1,
7541 const gp_XYZ& vert2,
7543 const double& EPSILON) const
7545 const gp_Pnt& orig = lastSegment.Location();
7546 const gp_Dir& dir = lastSegment.Direction();
7548 /* calculate distance from vert0 to ray origin */
7549 gp_XYZ tvec = orig.XYZ() - vert0;
7551 //if ( tvec * dir > EPSILON )
7552 // intersected face is at back side of the temporary face this _LayerEdge belongs to
7555 gp_XYZ edge1 = vert1 - vert0;
7556 gp_XYZ edge2 = vert2 - vert0;
7558 /* begin calculating determinant - also used to calculate U parameter */
7559 gp_XYZ pvec = dir.XYZ() ^ edge2;
7561 /* if determinant is near zero, ray lies in plane of triangle */
7562 double det = edge1 * pvec;
7564 const double ANGL_EPSILON = 1e-12;
7565 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7568 /* calculate U parameter and test bounds */
7569 double u = ( tvec * pvec ) / det;
7570 //if (u < 0.0 || u > 1.0)
7571 if ( u < -EPSILON || u > 1.0 + EPSILON )
7574 /* prepare to test V parameter */
7575 gp_XYZ qvec = tvec ^ edge1;
7577 /* calculate V parameter and test bounds */
7578 double v = (dir.XYZ() * qvec) / det;
7579 //if ( v < 0.0 || u + v > 1.0 )
7580 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7583 /* calculate t, ray intersects triangle */
7584 t = (edge2 * qvec) / det;
7590 //================================================================================
7592 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7593 * neighbor _LayerEdge's by it's own inflation vector.
7594 * \param [in] eov - EOS of the VERTEX
7595 * \param [in] eos - EOS of the FACE
7596 * \param [in] step - inflation step
7597 * \param [in,out] badSmooEdges - not untangled _LayerEdge's
7599 //================================================================================
7601 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
7602 const _EdgesOnShape* eos,
7604 vector< _LayerEdge* > & badSmooEdges )
7606 // check if any of _neibors is in badSmooEdges
7607 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7608 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7611 // get all edges to move
7613 set< _LayerEdge* > edges;
7615 // find a distance between _LayerEdge on VERTEX and its neighbors
7616 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
7618 for ( size_t i = 0; i < _neibors.size(); ++i )
7620 _LayerEdge* nEdge = _neibors[i];
7621 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7623 edges.insert( nEdge );
7624 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7627 // add _LayerEdge's close to curPosV
7631 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7633 _LayerEdge* edgeF = *e;
7634 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7636 _LayerEdge* nEdge = edgeF->_neibors[i];
7637 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7638 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7639 edges.insert( nEdge );
7643 while ( nbE < edges.size() );
7645 // move the target node of the got edges
7647 gp_XYZ prevPosV = PrevPos();
7648 if ( eov->SWOLType() == TopAbs_EDGE )
7650 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7651 prevPosV = curve.Value( prevPosV.X() ).XYZ();
7653 else if ( eov->SWOLType() == TopAbs_FACE )
7655 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7656 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7659 SMDS_FacePosition* fPos;
7660 //double r = 1. - Min( 0.9, step / 10. );
7661 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7663 _LayerEdge* edgeF = *e;
7664 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
7665 const gp_XYZ newPosF = curPosV + prevVF;
7666 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7667 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7668 edgeF->_pos.back() = newPosF;
7669 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7671 // set _curvature to make edgeF updated by putOnOffsetSurface()
7672 if ( !edgeF->_curvature )
7673 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7675 edgeF->_curvature = new _Curvature;
7676 edgeF->_curvature->_r = 0;
7677 edgeF->_curvature->_k = 0;
7678 edgeF->_curvature->_h2lenRatio = 0;
7679 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7682 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7683 // SMESH_TNodeXYZ( _nodes[0] ));
7684 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7686 // _LayerEdge* edgeF = *e;
7687 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7688 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7689 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7690 // edgeF->_pos.back() = newPosF;
7691 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7694 // smooth _LayerEdge's around moved nodes
7695 //size_t nbBadBefore = badSmooEdges.size();
7696 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7698 _LayerEdge* edgeF = *e;
7699 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7700 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7701 //&& !edges.count( edgeF->_neibors[j] ))
7703 _LayerEdge* edgeFN = edgeF->_neibors[j];
7704 edgeFN->Unset( SMOOTHED );
7705 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7708 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7709 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7710 // int nbBadAfter = edgeFN->_simplices.size();
7712 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7714 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7716 // if ( nbBadAfter <= nbBad )
7718 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7719 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7720 // edgeF->_pos.back() = newPosF;
7721 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7722 // nbBad = nbBadAfter;
7726 badSmooEdges.push_back( edgeFN );
7729 // move a bit not smoothed around moved nodes
7730 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7732 // _LayerEdge* edgeF = badSmooEdges[i];
7733 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7734 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7735 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7736 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7737 // edgeF->_pos.back() = newPosF;
7738 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7742 //================================================================================
7744 * \brief Perform smooth of _LayerEdge's based on EDGE's
7745 * \retval bool - true if node has been moved
7747 //================================================================================
7749 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7750 const TopoDS_Face& F,
7751 SMESH_MesherHelper& helper)
7753 ASSERT( IsOnEdge() );
7755 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7756 SMESH_TNodeXYZ oldPos( tgtNode );
7757 double dist01, distNewOld;
7759 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7760 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7761 dist01 = p0.Distance( _2neibors->tgtNode(1) );
7763 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7764 double lenDelta = 0;
7767 //lenDelta = _curvature->lenDelta( _len );
7768 lenDelta = _curvature->lenDeltaByDist( dist01 );
7769 newPos.ChangeCoord() += _normal * lenDelta;
7772 distNewOld = newPos.Distance( oldPos );
7776 if ( _2neibors->_plnNorm )
7778 // put newPos on the plane defined by source node and _plnNorm
7779 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7780 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7781 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7783 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7784 _pos.back() = newPos.XYZ();
7788 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7789 gp_XY uv( Precision::Infinite(), 0 );
7790 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7791 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7793 newPos = surface->Value( uv );
7794 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7797 // commented for IPAL0052478
7798 // if ( _curvature && lenDelta < 0 )
7800 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7801 // _len -= prevPos.Distance( oldPos );
7802 // _len += prevPos.Distance( newPos );
7804 bool moved = distNewOld > dist01/50;
7806 dumpMove( tgtNode ); // debug
7811 //================================================================================
7813 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7815 //================================================================================
7817 void _LayerEdge::SmoothWoCheck()
7819 if ( Is( DIFFICULT ))
7822 bool moved = Is( SMOOTHED );
7823 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
7824 moved = _neibors[i]->Is( SMOOTHED );
7828 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7830 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7831 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7832 _pos.back() = newPos;
7834 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7837 //================================================================================
7839 * \brief Checks validity of _neibors on EDGEs and VERTEXes
7841 //================================================================================
7843 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7845 if ( ! Is( NEAR_BOUNDARY ))
7850 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7852 _LayerEdge* eN = _neibors[iN];
7853 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7856 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7857 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7858 eN->_pos.size() != _pos.size() );
7860 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7861 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7862 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7863 if ( eN->_nodes.size() > 1 &&
7864 eN->_simplices[i].Includes( _nodes.back() ) &&
7865 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7870 badNeibors->push_back( eN );
7871 debugMsg("Bad boundary simplex ( "
7872 << " "<< eN->_nodes[0]->GetID()
7873 << " "<< eN->_nodes.back()->GetID()
7874 << " "<< eN->_simplices[i]._nPrev->GetID()
7875 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7886 //================================================================================
7888 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7889 * \retval int - nb of bad simplices around this _LayerEdge
7891 //================================================================================
7893 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7895 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7896 return 0; // shape of simplices not changed
7897 if ( _simplices.size() < 2 )
7898 return 0; // _LayerEdge inflated along EDGE or FACE
7900 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7903 const gp_XYZ& curPos = _pos.back();
7904 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7906 // quality metrics (orientation) of tetras around _tgtNode
7908 double vol, minVolBefore = 1e100;
7909 for ( size_t i = 0; i < _simplices.size(); ++i )
7911 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7912 minVolBefore = Min( minVolBefore, vol );
7914 int nbBad = _simplices.size() - nbOkBefore;
7916 bool bndNeedSmooth = false;
7918 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7922 // evaluate min angle
7923 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7925 size_t nbGoodAngles = _simplices.size();
7927 for ( size_t i = 0; i < _simplices.size(); ++i )
7929 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7932 if ( nbGoodAngles == _simplices.size() )
7938 if ( Is( ON_CONCAVE_FACE ))
7941 if ( step % 2 == 0 )
7944 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7946 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7947 _smooFunction = _funs[ FUN_CENTROIDAL ];
7949 _smooFunction = _funs[ FUN_LAPLACIAN ];
7952 // compute new position for the last _pos using different _funs
7955 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7958 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7959 else if ( _funs[ iFun ] == _smooFunction )
7960 continue; // _smooFunction again
7961 else if ( step > 1 )
7962 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7964 break; // let "easy" functions improve elements around distorted ones
7968 double delta = _curvature->lenDelta( _len );
7970 newPos += _normal * delta;
7973 double segLen = _normal * ( newPos - prevPos );
7974 if ( segLen + delta > 0 )
7975 newPos += _normal * delta;
7977 // double segLenChange = _normal * ( curPos - newPos );
7978 // newPos += 0.5 * _normal * segLenChange;
7982 double minVolAfter = 1e100;
7983 for ( size_t i = 0; i < _simplices.size(); ++i )
7985 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7986 minVolAfter = Min( minVolAfter, vol );
7989 if ( nbOkAfter < nbOkBefore )
7993 ( nbOkAfter == nbOkBefore ) &&
7994 ( minVolAfter <= minVolBefore ))
7997 nbBad = _simplices.size() - nbOkAfter;
7998 minVolBefore = minVolAfter;
7999 nbOkBefore = nbOkAfter;
8002 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8003 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8004 _pos.back() = newPos;
8006 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8007 << (nbBad ? " --BAD" : ""));
8011 continue; // look for a better function
8017 } // loop on smoothing functions
8019 if ( moved ) // notify _neibors
8022 for ( size_t i = 0; i < _neibors.size(); ++i )
8023 if ( !_neibors[i]->Is( MOVED ))
8025 _neibors[i]->Set( MOVED );
8026 toSmooth.push_back( _neibors[i] );
8033 //================================================================================
8035 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8036 * \retval int - nb of bad simplices around this _LayerEdge
8038 //================================================================================
8040 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8042 if ( !_smooFunction )
8043 return 0; // _LayerEdge inflated along EDGE or FACE
8045 return 0; // not inflated
8047 const gp_XYZ& curPos = _pos.back();
8048 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8050 // quality metrics (orientation) of tetras around _tgtNode
8052 double vol, minVolBefore = 1e100;
8053 for ( size_t i = 0; i < _simplices.size(); ++i )
8055 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8056 minVolBefore = Min( minVolBefore, vol );
8058 int nbBad = _simplices.size() - nbOkBefore;
8060 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8062 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8063 _smooFunction = _funs[ FUN_LAPLACIAN ];
8064 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8065 _smooFunction = _funs[ FUN_CENTROIDAL ];
8068 // compute new position for the last _pos using different _funs
8070 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8073 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8074 else if ( _funs[ iFun ] == _smooFunction )
8075 continue; // _smooFunction again
8076 else if ( step > 1 )
8077 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8079 break; // let "easy" functions improve elements around distorted ones
8083 double delta = _curvature->lenDelta( _len );
8085 newPos += _normal * delta;
8088 double segLen = _normal * ( newPos - prevPos );
8089 if ( segLen + delta > 0 )
8090 newPos += _normal * delta;
8092 // double segLenChange = _normal * ( curPos - newPos );
8093 // newPos += 0.5 * _normal * segLenChange;
8097 double minVolAfter = 1e100;
8098 for ( size_t i = 0; i < _simplices.size(); ++i )
8100 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8101 minVolAfter = Min( minVolAfter, vol );
8104 if ( nbOkAfter < nbOkBefore )
8106 if (( isConcaveFace || findBest ) &&
8107 ( nbOkAfter == nbOkBefore ) &&
8108 ( minVolAfter <= minVolBefore )
8112 nbBad = _simplices.size() - nbOkAfter;
8113 minVolBefore = minVolAfter;
8114 nbOkBefore = nbOkAfter;
8116 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8117 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8118 _pos.back() = newPos;
8120 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8121 << ( nbBad ? "--BAD" : ""));
8123 // commented for IPAL0052478
8124 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8125 // _len += prevPos.Distance(newPos);
8127 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8129 //_smooFunction = _funs[ iFun ];
8130 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8131 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8132 // << " minVol: " << minVolAfter
8133 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8135 continue; // look for a better function
8141 } // loop on smoothing functions
8146 //================================================================================
8148 * \brief Chooses a smoothing technic giving a position most close to an initial one.
8149 * For a correct result, _simplices must contain nodes lying on geometry.
8151 //================================================================================
8153 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8154 const TNode2Edge& n2eMap)
8156 if ( _smooFunction ) return;
8158 // use smoothNefPolygon() near concaveVertices
8159 if ( !concaveVertices.empty() )
8161 _smooFunction = _funs[ FUN_CENTROIDAL ];
8163 Set( ON_CONCAVE_FACE );
8165 for ( size_t i = 0; i < _simplices.size(); ++i )
8167 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8169 _smooFunction = _funs[ FUN_NEFPOLY ];
8171 // set FUN_CENTROIDAL to neighbor edges
8172 for ( i = 0; i < _neibors.size(); ++i )
8174 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8176 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8183 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8184 // // where the nodes are smoothed too far along a sphere thus creating
8185 // // inverted _simplices
8186 // double dist[theNbSmooFuns];
8187 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8188 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8190 // double minDist = Precision::Infinite();
8191 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8192 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8194 // gp_Pnt newP = (this->*_funs[i])();
8195 // dist[i] = p.SquareDistance( newP );
8196 // if ( dist[i]*coef[i] < minDist )
8198 // _smooFunction = _funs[i];
8199 // minDist = dist[i]*coef[i];
8205 _smooFunction = _funs[ FUN_LAPLACIAN ];
8208 // for ( size_t i = 0; i < _simplices.size(); ++i )
8209 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8210 // if ( minDim == 0 )
8211 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8212 // else if ( minDim == 1 )
8213 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8217 // for ( int i = 0; i < FUN_NB; ++i )
8219 // //cout << dist[i] << " ";
8220 // if ( _smooFunction == _funs[i] ) {
8222 // //debugMsg( fNames[i] );
8226 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8229 //================================================================================
8231 * \brief Returns a name of _SmooFunction
8233 //================================================================================
8235 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8238 fun = _smooFunction;
8239 for ( int i = 0; i < theNbSmooFuns; ++i )
8240 if ( fun == _funs[i] )
8243 return theNbSmooFuns;
8246 //================================================================================
8248 * \brief Computes a new node position using Laplacian smoothing
8250 //================================================================================
8252 gp_XYZ _LayerEdge::smoothLaplacian()
8254 gp_XYZ newPos (0,0,0);
8255 for ( size_t i = 0; i < _simplices.size(); ++i )
8256 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8257 newPos /= _simplices.size();
8262 //================================================================================
8264 * \brief Computes a new node position using angular-based smoothing
8266 //================================================================================
8268 gp_XYZ _LayerEdge::smoothAngular()
8270 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8271 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8272 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8274 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8276 for ( size_t i = 0; i < _simplices.size(); ++i )
8278 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8279 edgeDir.push_back( p - pPrev );
8280 edgeSize.push_back( edgeDir.back().Magnitude() );
8281 if ( edgeSize.back() < numeric_limits<double>::min() )
8284 edgeSize.pop_back();
8288 edgeDir.back() /= edgeSize.back();
8289 points.push_back( p );
8294 edgeDir.push_back ( edgeDir[0] );
8295 edgeSize.push_back( edgeSize[0] );
8296 pN /= points.size();
8298 gp_XYZ newPos(0,0,0);
8300 for ( size_t i = 0; i < points.size(); ++i )
8302 gp_Vec toN = pN - points[i];
8303 double toNLen = toN.Magnitude();
8304 if ( toNLen < numeric_limits<double>::min() )
8309 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8310 double bisecLen = bisec.SquareMagnitude();
8311 if ( bisecLen < numeric_limits<double>::min() )
8313 gp_Vec norm = edgeDir[i] ^ toN;
8314 bisec = norm ^ edgeDir[i];
8315 bisecLen = bisec.SquareMagnitude();
8317 bisecLen = Sqrt( bisecLen );
8321 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8322 sumSize += bisecLen;
8324 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8325 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8331 // project newPos to an average plane
8333 gp_XYZ norm(0,0,0); // plane normal
8334 points.push_back( points[0] );
8335 for ( size_t i = 1; i < points.size(); ++i )
8337 gp_XYZ vec1 = points[ i-1 ] - pN;
8338 gp_XYZ vec2 = points[ i ] - pN;
8339 gp_XYZ cross = vec1 ^ vec2;
8342 if ( cross * norm < numeric_limits<double>::min() )
8343 norm += cross.Reversed();
8347 catch (Standard_Failure) { // if |cross| == 0.
8350 gp_XYZ vec = newPos - pN;
8351 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8352 newPos = newPos - r * norm;
8357 //================================================================================
8359 * \brief Computes a new node position using weigthed node positions
8361 //================================================================================
8363 gp_XYZ _LayerEdge::smoothLengthWeighted()
8365 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8366 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8368 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8369 for ( size_t i = 0; i < _simplices.size(); ++i )
8371 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8372 edgeSize.push_back( ( p - pPrev ).Modulus() );
8373 if ( edgeSize.back() < numeric_limits<double>::min() )
8375 edgeSize.pop_back();
8379 points.push_back( p );
8383 edgeSize.push_back( edgeSize[0] );
8385 gp_XYZ newPos(0,0,0);
8387 for ( size_t i = 0; i < points.size(); ++i )
8389 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8390 sumSize += edgeSize[i] + edgeSize[i+1];
8396 //================================================================================
8398 * \brief Computes a new node position using angular-based smoothing
8400 //================================================================================
8402 gp_XYZ _LayerEdge::smoothCentroidal()
8404 gp_XYZ newPos(0,0,0);
8405 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8407 for ( size_t i = 0; i < _simplices.size(); ++i )
8409 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8410 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8411 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8412 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8415 newPos += gc * size;
8422 //================================================================================
8424 * \brief Computes a new node position located inside a Nef polygon
8426 //================================================================================
8428 gp_XYZ _LayerEdge::smoothNefPolygon()
8429 #ifdef OLD_NEF_POLYGON
8431 gp_XYZ newPos(0,0,0);
8433 // get a plane to seach a solution on
8435 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8437 const double tol = numeric_limits<double>::min();
8438 gp_XYZ center(0,0,0);
8439 for ( i = 0; i < _simplices.size(); ++i )
8441 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8442 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8443 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8445 vecs.back() = vecs[0];
8446 center /= _simplices.size();
8448 gp_XYZ zAxis(0,0,0);
8449 for ( i = 0; i < _simplices.size(); ++i )
8450 zAxis += vecs[i] ^ vecs[i+1];
8453 for ( i = 0; i < _simplices.size(); ++i )
8456 if ( yAxis.SquareModulus() > tol )
8459 gp_XYZ xAxis = yAxis ^ zAxis;
8460 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8461 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8462 // p0.Distance( _simplices[2]._nPrev ));
8463 // gp_XYZ center = smoothLaplacian();
8464 // gp_XYZ xAxis, yAxis, zAxis;
8465 // for ( i = 0; i < _simplices.size(); ++i )
8467 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8468 // if ( xAxis.SquareModulus() > tol*tol )
8471 // for ( i = 1; i < _simplices.size(); ++i )
8473 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8474 // zAxis = xAxis ^ yAxis;
8475 // if ( zAxis.SquareModulus() > tol*tol )
8478 // if ( i == _simplices.size() ) return newPos;
8480 yAxis = zAxis ^ xAxis;
8481 xAxis /= xAxis.Modulus();
8482 yAxis /= yAxis.Modulus();
8484 // get half-planes of _simplices
8486 vector< _halfPlane > halfPlns( _simplices.size() );
8488 for ( size_t i = 0; i < _simplices.size(); ++i )
8490 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8491 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8492 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8493 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8494 gp_XY vec12 = p2 - p1;
8495 double dist12 = vec12.Modulus();
8499 halfPlns[ nbHP ]._pos = p1;
8500 halfPlns[ nbHP ]._dir = vec12;
8501 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8505 // intersect boundaries of half-planes, define state of intersection points
8506 // in relation to all half-planes and calculate internal point of a 2D polygon
8509 gp_XY newPos2D (0,0);
8511 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8512 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8513 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8515 vector< vector< TIntPntState > > allIntPnts( nbHP );
8516 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8518 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8519 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8521 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8522 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8525 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8527 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8529 if ( iHP1 == iHP2 ) continue;
8531 TIntPntState & ips1 = intPnts1[ iHP2 ];
8532 if ( ips1.second == UNDEF )
8534 // find an intersection point of boundaries of iHP1 and iHP2
8536 if ( iHP2 == iPrev ) // intersection with neighbors is known
8537 ips1.first = halfPlns[ iHP1 ]._pos;
8538 else if ( iHP2 == iNext )
8539 ips1.first = halfPlns[ iHP2 ]._pos;
8540 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8541 ips1.second = NO_INT;
8543 // classify the found intersection point
8544 if ( ips1.second != NO_INT )
8546 ips1.second = NOT_OUT;
8547 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8548 if ( i != iHP1 && i != iHP2 &&
8549 halfPlns[ i ].IsOut( ips1.first, tol ))
8550 ips1.second = IS_OUT;
8552 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8553 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8554 TIntPntState & ips2 = intPnts2[ iHP1 ];
8557 if ( ips1.second == NOT_OUT )
8560 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8564 // find a NOT_OUT segment of boundary which is located between
8565 // two NOT_OUT int points
8568 continue; // no such a segment
8572 // sort points along the boundary
8573 map< double, TIntPntState* > ipsByParam;
8574 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8576 TIntPntState & ips1 = intPnts1[ iHP2 ];
8577 if ( ips1.second != NO_INT )
8579 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8580 double param = op * halfPlns[ iHP1 ]._dir;
8581 ipsByParam.insert( make_pair( param, & ips1 ));
8584 // look for two neighboring NOT_OUT points
8586 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8587 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8589 TIntPntState & ips1 = *(u2ips->second);
8590 if ( ips1.second == NOT_OUT )
8591 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8592 else if ( nbNotOut >= 2 )
8599 if ( nbNotOut >= 2 )
8601 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8604 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8611 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8620 #else // OLD_NEF_POLYGON
8621 { ////////////////////////////////// NEW
8622 gp_XYZ newPos(0,0,0);
8624 // get a plane to seach a solution on
8627 gp_XYZ center(0,0,0);
8628 for ( i = 0; i < _simplices.size(); ++i )
8629 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8630 center /= _simplices.size();
8632 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8633 for ( i = 0; i < _simplices.size(); ++i )
8634 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8635 vecs.back() = vecs[0];
8637 const double tol = numeric_limits<double>::min();
8638 gp_XYZ zAxis(0,0,0);
8639 for ( i = 0; i < _simplices.size(); ++i )
8641 gp_XYZ cross = vecs[i] ^ vecs[i+1];
8644 if ( cross * zAxis < tol )
8645 zAxis += cross.Reversed();
8649 catch (Standard_Failure) { // if |cross| == 0.
8654 for ( i = 0; i < _simplices.size(); ++i )
8657 if ( yAxis.SquareModulus() > tol )
8660 gp_XYZ xAxis = yAxis ^ zAxis;
8661 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8662 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8663 // p0.Distance( _simplices[2]._nPrev ));
8664 // gp_XYZ center = smoothLaplacian();
8665 // gp_XYZ xAxis, yAxis, zAxis;
8666 // for ( i = 0; i < _simplices.size(); ++i )
8668 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8669 // if ( xAxis.SquareModulus() > tol*tol )
8672 // for ( i = 1; i < _simplices.size(); ++i )
8674 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8675 // zAxis = xAxis ^ yAxis;
8676 // if ( zAxis.SquareModulus() > tol*tol )
8679 // if ( i == _simplices.size() ) return newPos;
8681 yAxis = zAxis ^ xAxis;
8682 xAxis /= xAxis.Modulus();
8683 yAxis /= yAxis.Modulus();
8685 // get half-planes of _simplices
8687 vector< _halfPlane > halfPlns( _simplices.size() );
8689 for ( size_t i = 0; i < _simplices.size(); ++i )
8691 const gp_XYZ& OP1 = vecs[ i ];
8692 const gp_XYZ& OP2 = vecs[ i+1 ];
8693 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8694 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8695 gp_XY vec12 = p2 - p1;
8696 double dist12 = vec12.Modulus();
8700 halfPlns[ nbHP ]._pos = p1;
8701 halfPlns[ nbHP ]._dir = vec12;
8702 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8706 // intersect boundaries of half-planes, define state of intersection points
8707 // in relation to all half-planes and calculate internal point of a 2D polygon
8710 gp_XY newPos2D (0,0);
8712 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8713 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8714 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8716 vector< vector< TIntPntState > > allIntPnts( nbHP );
8717 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8719 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8720 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8722 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8723 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8726 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8728 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8730 if ( iHP1 == iHP2 ) continue;
8732 TIntPntState & ips1 = intPnts1[ iHP2 ];
8733 if ( ips1.second == UNDEF )
8735 // find an intersection point of boundaries of iHP1 and iHP2
8737 if ( iHP2 == iPrev ) // intersection with neighbors is known
8738 ips1.first = halfPlns[ iHP1 ]._pos;
8739 else if ( iHP2 == iNext )
8740 ips1.first = halfPlns[ iHP2 ]._pos;
8741 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8742 ips1.second = NO_INT;
8744 // classify the found intersection point
8745 if ( ips1.second != NO_INT )
8747 ips1.second = NOT_OUT;
8748 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8749 if ( i != iHP1 && i != iHP2 &&
8750 halfPlns[ i ].IsOut( ips1.first, tol ))
8751 ips1.second = IS_OUT;
8753 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8754 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8755 TIntPntState & ips2 = intPnts2[ iHP1 ];
8758 if ( ips1.second == NOT_OUT )
8761 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8765 // find a NOT_OUT segment of boundary which is located between
8766 // two NOT_OUT int points
8769 continue; // no such a segment
8773 // sort points along the boundary
8774 map< double, TIntPntState* > ipsByParam;
8775 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8777 TIntPntState & ips1 = intPnts1[ iHP2 ];
8778 if ( ips1.second != NO_INT )
8780 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8781 double param = op * halfPlns[ iHP1 ]._dir;
8782 ipsByParam.insert( make_pair( param, & ips1 ));
8785 // look for two neighboring NOT_OUT points
8787 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8788 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8790 TIntPntState & ips1 = *(u2ips->second);
8791 if ( ips1.second == NOT_OUT )
8792 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8793 else if ( nbNotOut >= 2 )
8800 if ( nbNotOut >= 2 )
8802 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8805 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8812 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8821 #endif // OLD_NEF_POLYGON
8823 //================================================================================
8825 * \brief Add a new segment to _LayerEdge during inflation
8827 //================================================================================
8829 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8834 if ( len > _maxLen )
8837 Block( eos.GetData() );
8839 const double lenDelta = len - _len;
8840 if ( lenDelta < len * 1e-3 )
8842 Block( eos.GetData() );
8846 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8847 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8849 if ( eos._hyp.IsOffsetMethod() )
8853 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8854 while ( faceIt->more() )
8856 const SMDS_MeshElement* face = faceIt->next();
8857 if ( !eos.GetNormal( face, faceNorm ))
8860 // translate plane of a face
8861 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8863 // find point of intersection of the face plane located at baryCenter
8864 // and _normal located at newXYZ
8865 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8866 double dot = ( faceNorm.XYZ() * _normal );
8867 if ( dot < std::numeric_limits<double>::min() )
8868 dot = lenDelta * 1e-3;
8869 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8870 newXYZ += step * _normal;
8872 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8876 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8879 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8880 _pos.push_back( newXYZ );
8882 if ( !eos._sWOL.IsNull() )
8886 if ( eos.SWOLType() == TopAbs_EDGE )
8888 double u = Precision::Infinite(); // to force projection w/o distance check
8889 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8890 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8891 _pos.back().SetCoord( u, 0, 0 );
8892 if ( _nodes.size() > 1 && uvOK )
8894 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8895 pos->SetUParameter( u );
8900 gp_XY uv( Precision::Infinite(), 0 );
8901 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8902 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8903 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8904 if ( _nodes.size() > 1 && uvOK )
8906 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8907 pos->SetUParameter( uv.X() );
8908 pos->SetVParameter( uv.Y() );
8913 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8917 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8919 Block( eos.GetData() );
8927 if ( eos.ShapeType() != TopAbs_FACE )
8929 for ( size_t i = 0; i < _neibors.size(); ++i )
8930 //if ( _len > _neibors[i]->GetSmooLen() )
8931 _neibors[i]->Set( MOVED );
8935 dumpMove( n ); //debug
8938 //================================================================================
8940 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8942 //================================================================================
8944 void _LayerEdge::Block( _SolidData& data )
8946 //if ( Is( BLOCKED )) return;
8950 std::queue<_LayerEdge*> queue;
8953 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8954 while ( !queue.empty() )
8956 _LayerEdge* edge = queue.front(); queue.pop();
8957 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8958 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8959 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8961 _LayerEdge* neibor = edge->_neibors[iN];
8962 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
8964 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8965 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8966 double minDist = pSrc.SquareDistance( pSrcN );
8967 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
8968 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
8969 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
8970 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8971 if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
8973 newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
8975 if ( neibor->_maxLen > newMaxLen )
8977 neibor->_maxLen = newMaxLen;
8978 if ( neibor->_maxLen < neibor->_len )
8980 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8981 while ( neibor->_len > neibor->_maxLen &&
8982 neibor->NbSteps() > 1 )
8983 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8984 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8985 //neibor->Block( data );
8987 queue.push( neibor );
8993 //================================================================================
8995 * \brief Remove last inflation step
8997 //================================================================================
8999 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9001 if ( _pos.size() > curStep && _nodes.size() > 1 )
9003 _pos.resize( curStep );
9005 gp_Pnt nXYZ = _pos.back();
9006 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9007 SMESH_TNodeXYZ curXYZ( n );
9008 if ( !eos._sWOL.IsNull() )
9010 TopLoc_Location loc;
9011 if ( eos.SWOLType() == TopAbs_EDGE )
9013 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9014 pos->SetUParameter( nXYZ.X() );
9016 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9017 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9021 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9022 pos->SetUParameter( nXYZ.X() );
9023 pos->SetVParameter( nXYZ.Y() );
9024 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9025 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9028 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9031 if ( restoreLength )
9033 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9038 //================================================================================
9040 * \brief Return index of a _pos distant from _normal
9042 //================================================================================
9044 int _LayerEdge::GetSmoothedPos( const double tol )
9047 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9049 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9050 if ( normDist > tol * tol )
9056 //================================================================================
9058 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9060 //================================================================================
9062 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9064 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9067 // find the 1st smoothed _pos
9068 int iSmoothed = GetSmoothedPos( tol );
9069 if ( !iSmoothed ) return;
9071 //if ( 1 || Is( DISTORTED ))
9073 gp_XYZ normal = _normal;
9074 if ( Is( NORMAL_UPDATED ))
9075 for ( size_t i = 1; i < _pos.size(); ++i )
9077 normal = _pos[i] - _pos[0];
9078 double size = normal.Modulus();
9079 if ( size > RealSmall() )
9085 const double r = 0.2;
9086 for ( int iter = 0; iter < 50; ++iter )
9089 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9091 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9092 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9094 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9095 double newLen = ( 1-r ) * midLen + r * segLen[i];
9096 const_cast< double& >( segLen[i] ) = newLen;
9097 // check angle between normal and (_pos[i+1], _pos[i] )
9098 gp_XYZ posDir = _pos[i+1] - _pos[i];
9099 double size = posDir.SquareModulus();
9100 if ( size > RealSmall() )
9101 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9103 if ( minDot > 0.5 * 0.5 )
9109 // for ( size_t i = 1; i < _pos.size()-1; ++i )
9111 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
9114 // double wgt = segLen[i] / segLen.back();
9115 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9116 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
9117 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
9118 // _pos[i] = newPos;
9123 //================================================================================
9125 * \brief Create layers of prisms
9127 //================================================================================
9129 bool _ViscousBuilder::refine(_SolidData& data)
9131 SMESH_MesherHelper& helper = data.GetHelper();
9132 helper.SetElementsOnShape(false);
9134 Handle(Geom_Curve) curve;
9135 Handle(ShapeAnalysis_Surface) surface;
9136 TopoDS_Edge geomEdge;
9137 TopoDS_Face geomFace;
9138 TopLoc_Location loc;
9141 vector< gp_XYZ > pos3D;
9143 TGeomID prevBaseId = -1;
9144 TNode2Edge* n2eMap = 0;
9145 TNode2Edge::iterator n2e;
9147 // Create intermediate nodes on each _LayerEdge
9149 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9151 _EdgesOnShape& eos = data._edgesOnShape[iS];
9152 if ( eos._edges.empty() ) continue;
9154 if ( eos._edges[0]->_nodes.size() < 2 )
9155 continue; // on _noShrinkShapes
9157 // get data of a shrink shape
9159 geomEdge.Nullify(); geomFace.Nullify();
9160 curve.Nullify(); surface.Nullify();
9161 if ( !eos._sWOL.IsNull() )
9163 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9166 geomEdge = TopoDS::Edge( eos._sWOL );
9167 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9171 geomFace = TopoDS::Face( eos._sWOL );
9172 surface = helper.GetSurface( geomFace );
9175 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9177 geomFace = TopoDS::Face( eos._shape );
9178 surface = helper.GetSurface( geomFace );
9179 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9180 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9182 eos._eosC1[ i ]->_toSmooth = true;
9183 for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9184 eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9188 vector< double > segLen;
9189 for ( size_t i = 0; i < eos._edges.size(); ++i )
9191 _LayerEdge& edge = *eos._edges[i];
9192 if ( edge._pos.size() < 2 )
9195 // get accumulated length of segments
9196 segLen.resize( edge._pos.size() );
9198 if ( eos._sWOL.IsNull() )
9200 bool useNormal = true;
9201 bool usePos = false;
9202 bool smoothed = false;
9203 double preci = 0.1 * edge._len;
9204 if ( eos._toSmooth && edge._pos.size() > 2 )
9206 smoothed = edge.GetSmoothedPos( preci );
9210 if ( !surface.IsNull() &&
9211 !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9213 useNormal = usePos = false;
9214 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9215 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9217 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9218 if ( surface->Gap() < 2. * edge._len )
9219 segLen[j] = surface->Gap();
9225 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9227 #ifndef __NODES_AT_POS
9228 useNormal = usePos = false;
9229 edge._pos[1] = edge._pos.back();
9230 edge._pos.resize( 2 );
9232 segLen[ 1 ] = edge._len;
9235 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9237 useNormal = usePos = false;
9238 _LayerEdge tmpEdge; // get original _normal
9239 tmpEdge._nodes.push_back( edge._nodes[0] );
9240 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9243 for ( size_t j = 1; j < edge._pos.size(); ++j )
9244 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9248 for ( size_t j = 1; j < edge._pos.size(); ++j )
9249 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9253 for ( size_t j = 1; j < edge._pos.size(); ++j )
9254 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9258 bool swapped = ( edge._pos.size() > 2 );
9262 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9263 if ( segLen[j] > segLen.back() )
9265 segLen.erase( segLen.begin() + j );
9266 edge._pos.erase( edge._pos.begin() + j );
9269 else if ( segLen[j] < segLen[j-1] )
9271 std::swap( segLen[j], segLen[j-1] );
9272 std::swap( edge._pos[j], edge._pos[j-1] );
9277 // smooth a path formed by edge._pos
9278 #ifndef __NODES_AT_POS
9279 if (( smoothed ) /*&&
9280 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9281 edge.SmoothPos( segLen, preci );
9284 else if ( eos._isRegularSWOL ) // usual SWOL
9286 for ( size_t j = 1; j < edge._pos.size(); ++j )
9287 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9289 else if ( !surface.IsNull() ) // SWOL surface with singularities
9291 pos3D.resize( edge._pos.size() );
9292 for ( size_t j = 0; j < edge._pos.size(); ++j )
9293 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9295 for ( size_t j = 1; j < edge._pos.size(); ++j )
9296 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9299 // allocate memory for new nodes if it is not yet refined
9300 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9301 if ( edge._nodes.size() == 2 )
9303 #ifdef __NODES_AT_POS
9304 int nbNodes = edge._pos.size();
9306 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9308 edge._nodes.resize( nbNodes, 0 );
9310 edge._nodes.back() = tgtNode;
9312 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9313 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9314 if ( baseShapeId != prevBaseId )
9316 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9317 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9318 prevBaseId = baseShapeId;
9320 _LayerEdge* edgeOnSameNode = 0;
9321 bool useExistingPos = false;
9322 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9324 edgeOnSameNode = n2e->second;
9325 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9326 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9327 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9330 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9331 epos->SetUParameter( otherTgtPos.X() );
9335 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9336 fpos->SetUParameter( otherTgtPos.X() );
9337 fpos->SetVParameter( otherTgtPos.Y() );
9340 // calculate height of the first layer
9342 const double T = segLen.back(); //data._hyp.GetTotalThickness();
9343 const double f = eos._hyp.GetStretchFactor();
9344 const int N = eos._hyp.GetNumberLayers();
9345 const double fPowN = pow( f, N );
9346 if ( fPowN - 1 <= numeric_limits<double>::min() )
9349 h0 = T * ( f - 1 )/( fPowN - 1 );
9351 const double zeroLen = std::numeric_limits<double>::min();
9353 // create intermediate nodes
9354 double hSum = 0, hi = h0/f;
9356 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9358 // compute an intermediate position
9361 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9363 int iPrevSeg = iSeg-1;
9364 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9366 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9367 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9368 #ifdef __NODES_AT_POS
9369 pos = edge._pos[ iStep ];
9371 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9372 if ( !eos._sWOL.IsNull() )
9374 // compute XYZ by parameters <pos>
9379 pos = curve->Value( u ).Transformed(loc);
9381 else if ( eos._isRegularSWOL )
9383 uv.SetCoord( pos.X(), pos.Y() );
9385 pos = surface->Value( pos.X(), pos.Y() );
9389 uv.SetCoord( pos.X(), pos.Y() );
9390 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9391 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9393 pos = surface->Value( uv );
9396 // create or update the node
9399 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9400 if ( !eos._sWOL.IsNull() )
9403 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9405 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9409 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9414 if ( !eos._sWOL.IsNull() )
9416 // make average pos from new and current parameters
9419 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9420 if ( useExistingPos )
9421 u = helper.GetNodeU( geomEdge, node );
9422 pos = curve->Value( u ).Transformed(loc);
9424 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9425 epos->SetUParameter( u );
9429 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9430 if ( useExistingPos )
9431 uv = helper.GetNodeUV( geomFace, node );
9432 pos = surface->Value( uv );
9434 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9435 fpos->SetUParameter( uv.X() );
9436 fpos->SetVParameter( uv.Y() );
9439 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9441 } // loop on edge._nodes
9443 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9446 edge._pos.back().SetCoord( u, 0,0);
9448 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9450 if ( edgeOnSameNode )
9451 edgeOnSameNode->_pos.back() = edge._pos.back();
9454 } // loop on eos._edges to create nodes
9457 if ( !getMeshDS()->IsEmbeddedMode() )
9458 // Log node movement
9459 for ( size_t i = 0; i < eos._edges.size(); ++i )
9461 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9462 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9469 helper.SetElementsOnShape(true);
9471 vector< vector<const SMDS_MeshNode*>* > nnVec;
9472 set< vector<const SMDS_MeshNode*>* > nnSet;
9473 set< int > degenEdgeInd;
9474 vector<const SMDS_MeshElement*> degenVols;
9475 vector<int> isRiskySWOL;
9477 TopExp_Explorer exp( data._solid, TopAbs_FACE );
9478 for ( ; exp.More(); exp.Next() )
9480 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9481 if ( data._ignoreFaceIds.count( faceID ))
9483 const bool isReversedFace = data._reversedFaceIds.count( faceID );
9484 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
9485 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
9486 while ( fIt->more() )
9488 const SMDS_MeshElement* face = fIt->next();
9489 const int nbNodes = face->NbCornerNodes();
9490 nnVec.resize( nbNodes );
9492 degenEdgeInd.clear();
9493 isRiskySWOL.resize( nbNodes );
9494 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9495 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9496 for ( int iN = 0; iN < nbNodes; ++iN )
9498 const SMDS_MeshNode* n = nIt->next();
9499 _LayerEdge* edge = data._n2eMap[ n ];
9500 const int i = isReversedFace ? nbNodes-1-iN : iN;
9501 nnVec[ i ] = & edge->_nodes;
9502 maxZ = std::max( maxZ, nnVec[ i ]->size() );
9503 minZ = std::min( minZ, nnVec[ i ]->size() );
9504 //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9506 if ( helper.HasDegeneratedEdges() )
9507 nnSet.insert( nnVec[ i ]);
9512 if ( 0 < nnSet.size() && nnSet.size() < 3 )
9520 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9521 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9522 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
9524 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9526 for ( int iN = 0; iN < nbNodes; ++iN )
9527 if ( nnVec[ iN ]->size() < iZ+1 )
9528 degenEdgeInd.insert( iN );
9530 if ( degenEdgeInd.size() == 1 ) // PYRAM
9532 int i2 = *degenEdgeInd.begin();
9533 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9534 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9535 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9536 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
9540 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9541 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9542 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9543 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9544 (*nnVec[ i3 ])[ iZ ]);
9552 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9553 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9554 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9555 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
9556 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
9558 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9560 for ( int iN = 0; iN < nbNodes; ++iN )
9561 if ( nnVec[ iN ]->size() < iZ+1 )
9562 degenEdgeInd.insert( iN );
9564 switch ( degenEdgeInd.size() )
9568 int i2 = *degenEdgeInd.begin();
9569 int i3 = *degenEdgeInd.rbegin();
9570 bool ok = ( i3 - i2 == 1 );
9571 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9572 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9573 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9575 const SMDS_MeshElement* vol =
9576 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9577 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9579 degenVols.push_back( vol );
9583 default: // degen HEX
9585 const SMDS_MeshElement* vol =
9586 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9587 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9588 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9589 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9590 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
9591 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
9592 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
9593 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
9594 degenVols.push_back( vol );
9601 return error("Not supported type of element", data._index);
9603 } // switch ( nbNodes )
9604 } // while ( fIt->more() )
9607 if ( !degenVols.empty() )
9609 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9610 if ( !err || err->IsOK() )
9612 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9613 "Degenerated volumes created" ));
9614 err->myBadElements.insert( err->myBadElements.end(),
9615 degenVols.begin(),degenVols.end() );
9622 //================================================================================
9624 * \brief Shrink 2D mesh on faces to let space for inflated layers
9626 //================================================================================
9628 bool _ViscousBuilder::shrink()
9630 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9631 // inflated along FACE or EDGE)
9632 map< TGeomID, _SolidData* > f2sdMap;
9633 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9635 _SolidData& data = _sdVec[i];
9636 TopTools_MapOfShape FFMap;
9637 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9638 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9639 if ( s2s->second.ShapeType() == TopAbs_FACE )
9641 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9643 if ( FFMap.Add( (*s2s).second ))
9644 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9645 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9646 // by StdMeshers_QuadToTriaAdaptor
9647 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9649 SMESH_ProxyMesh::SubMesh* proxySub =
9650 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9651 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9652 while ( fIt->more() )
9653 proxySub->AddElement( fIt->next() );
9654 // as a result 3D algo will use elements from proxySub and not from smDS
9659 SMESH_MesherHelper helper( *_mesh );
9660 helper.ToFixNodeParameters( true );
9663 map< TGeomID, _Shrinker1D > e2shrMap;
9664 vector< _EdgesOnShape* > subEOS;
9665 vector< _LayerEdge* > lEdges;
9667 // loop on FACES to srink mesh on
9668 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9669 for ( ; f2sd != f2sdMap.end(); ++f2sd )
9671 _SolidData& data = *f2sd->second;
9672 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9673 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
9674 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9676 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9678 helper.SetSubShape(F);
9680 // ===========================
9681 // Prepare data for shrinking
9682 // ===========================
9684 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9685 // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9686 vector < const SMDS_MeshNode* > smoothNodes;
9688 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9689 while ( nIt->more() )
9691 const SMDS_MeshNode* n = nIt->next();
9692 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9693 smoothNodes.push_back( n );
9696 // Find out face orientation
9698 const set<TGeomID> ignoreShapes;
9700 if ( !smoothNodes.empty() )
9702 vector<_Simplex> simplices;
9703 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9704 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9705 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9706 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9707 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9711 // Find _LayerEdge's inflated along F
9715 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9716 /*complexFirst=*/true); //!!!
9717 while ( subIt->more() )
9719 const TGeomID subID = subIt->next()->GetId();
9720 if ( data._noShrinkShapes.count( subID ))
9722 _EdgesOnShape* eos = data.GetShapeEdges( subID );
9723 if ( !eos || eos->_sWOL.IsNull() ) continue;
9725 subEOS.push_back( eos );
9727 for ( size_t i = 0; i < eos->_edges.size(); ++i )
9729 lEdges.push_back( eos->_edges[ i ] );
9730 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9735 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9736 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9737 while ( fIt->more() )
9738 if ( const SMDS_MeshElement* f = fIt->next() )
9739 dumpChangeNodes( f );
9742 // Replace source nodes by target nodes in mesh faces to shrink
9743 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9744 const SMDS_MeshNode* nodes[20];
9745 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9747 _EdgesOnShape& eos = * subEOS[ iS ];
9748 for ( size_t i = 0; i < eos._edges.size(); ++i )
9750 _LayerEdge& edge = *eos._edges[i];
9751 const SMDS_MeshNode* srcNode = edge._nodes[0];
9752 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9753 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9754 while ( fIt->more() )
9756 const SMDS_MeshElement* f = fIt->next();
9757 if ( !smDS->Contains( f ))
9759 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9760 for ( int iN = 0; nIt->more(); ++iN )
9762 const SMDS_MeshNode* n = nIt->next();
9763 nodes[iN] = ( n == srcNode ? tgtNode : n );
9765 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9766 dumpChangeNodes( f );
9772 // find out if a FACE is concave
9773 const bool isConcaveFace = isConcave( F, helper );
9775 // Create _SmoothNode's on face F
9776 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9778 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9779 const bool sortSimplices = isConcaveFace;
9780 for ( size_t i = 0; i < smoothNodes.size(); ++i )
9782 const SMDS_MeshNode* n = smoothNodes[i];
9783 nodesToSmooth[ i ]._node = n;
9784 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9785 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9786 // fix up incorrect uv of nodes on the FACE
9787 helper.GetNodeUV( F, n, 0, &isOkUV);
9792 //if ( nodesToSmooth.empty() ) continue;
9794 // Find EDGE's to shrink and set simpices to LayerEdge's
9795 set< _Shrinker1D* > eShri1D;
9797 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9799 _EdgesOnShape& eos = * subEOS[ iS ];
9800 if ( eos.SWOLType() == TopAbs_EDGE )
9802 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9803 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
9804 eShri1D.insert( & srinker );
9805 srinker.AddEdge( eos._edges[0], eos, helper );
9806 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9807 // restore params of nodes on EGDE if the EDGE has been already
9808 // srinked while srinking other FACE
9809 srinker.RestoreParams();
9811 for ( size_t i = 0; i < eos._edges.size(); ++i )
9813 _LayerEdge& edge = * eos._edges[i];
9814 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9819 bool toFixTria = false; // to improve quality of trias by diagonal swap
9820 if ( isConcaveFace )
9822 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9823 if ( hasTria != hasQuad ) {
9824 toFixTria = hasTria;
9827 set<int> nbNodesSet;
9828 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9829 while ( fIt->more() && nbNodesSet.size() < 2 )
9830 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9831 toFixTria = ( *nbNodesSet.begin() == 3 );
9835 // ==================
9836 // Perform shrinking
9837 // ==================
9839 bool shrinked = true;
9840 int nbBad, shriStep=0, smooStep=0;
9841 _SmoothNode::SmoothType smoothType
9842 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9843 SMESH_Comment errMsg;
9847 // Move boundary nodes (actually just set new UV)
9848 // -----------------------------------------------
9849 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9851 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9853 _EdgesOnShape& eos = * subEOS[ iS ];
9854 for ( size_t i = 0; i < eos._edges.size(); ++i )
9856 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9861 // Move nodes on EDGE's
9862 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9863 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9864 for ( ; shr != eShri1D.end(); ++shr )
9865 (*shr)->Compute( /*set3D=*/false, helper );
9868 // -----------------
9869 int nbNoImpSteps = 0;
9872 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9874 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9876 int oldBadNb = nbBad;
9879 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9880 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9881 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9883 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9884 smooTy, /*set3D=*/isConcaveFace);
9886 if ( nbBad < oldBadNb )
9896 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9897 if ( shriStep > 200 )
9898 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9899 if ( !errMsg.empty() )
9902 // Fix narrow triangles by swapping diagonals
9903 // ---------------------------------------
9906 set<const SMDS_MeshNode*> usedNodes;
9907 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9909 // update working data
9910 set<const SMDS_MeshNode*>::iterator n;
9911 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9913 n = usedNodes.find( nodesToSmooth[ i ]._node );
9914 if ( n != usedNodes.end())
9916 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9917 nodesToSmooth[ i ]._simplices,
9919 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9920 usedNodes.erase( n );
9923 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9925 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9926 if ( n != usedNodes.end())
9928 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9929 lEdges[i]->_simplices,
9931 usedNodes.erase( n );
9935 // TODO: check effect of this additional smooth
9936 // additional laplacian smooth to increase allowed shrink step
9937 // for ( int st = 1; st; --st )
9939 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9940 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9942 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9943 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
9947 } // while ( shrinked )
9949 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9952 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9954 vector< const SMDS_MeshElement* > facesToRm;
9957 facesToRm.reserve( psm->NbElements() );
9958 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9959 facesToRm.push_back( ite->next() );
9961 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9962 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9965 for ( size_t i = 0; i < facesToRm.size(); ++i )
9966 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9970 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9971 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9972 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9973 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9974 subEOS[iS]->_edges[i]->_nodes.end() );
9976 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9977 while ( itn->more() ) {
9978 const SMDS_MeshNode* n = itn->next();
9979 if ( !nodesToKeep.count( n ))
9980 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9983 // restore position and UV of target nodes
9985 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9986 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9988 _LayerEdge* edge = subEOS[iS]->_edges[i];
9989 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9990 if ( edge->_pos.empty() ) continue;
9991 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9993 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9994 pos->SetUParameter( edge->_pos[0].X() );
9995 pos->SetVParameter( edge->_pos[0].Y() );
9996 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10000 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10001 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10002 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10004 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10005 dumpMove( tgtNode );
10007 // shrink EDGE sub-meshes and set proxy sub-meshes
10008 UVPtStructVec uvPtVec;
10009 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10010 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10012 _Shrinker1D* shr = (*shrIt);
10013 shr->Compute( /*set3D=*/true, helper );
10015 // set proxy mesh of EDGEs w/o layers
10016 map< double, const SMDS_MeshNode* > nodes;
10017 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10018 // remove refinement nodes
10019 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10020 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10021 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10022 if ( u2n->second == sn0 || u2n->second == sn1 )
10024 while ( u2n->second != tn0 && u2n->second != tn1 )
10026 nodes.erase( nodes.begin(), u2n );
10028 u2n = --nodes.end();
10029 if ( u2n->second == sn0 || u2n->second == sn1 )
10031 while ( u2n->second != tn0 && u2n->second != tn1 )
10033 nodes.erase( ++u2n, nodes.end() );
10035 // set proxy sub-mesh
10036 uvPtVec.resize( nodes.size() );
10037 u2n = nodes.begin();
10038 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10039 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10041 uvPtVec[ i ].node = u2n->second;
10042 uvPtVec[ i ].param = u2n->first;
10043 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10045 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10046 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10049 // set proxy mesh of EDGEs with layers
10050 vector< _LayerEdge* > edges;
10051 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10053 _EdgesOnShape& eos = * subEOS[ iS ];
10054 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10056 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10057 data.SortOnEdge( E, eos._edges );
10060 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10061 if ( !eov->_edges.empty() )
10062 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10064 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10066 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10067 if ( !eov->_edges.empty() )
10068 edges.push_back( eov->_edges[0] ); // on last VERTEX
10070 uvPtVec.resize( edges.size() );
10071 for ( size_t i = 0; i < edges.size(); ++i )
10073 uvPtVec[ i ].node = edges[i]->_nodes.back();
10074 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10075 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10077 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10078 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10079 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10081 // temporary clear the FACE sub-mesh from faces made by refine()
10082 vector< const SMDS_MeshElement* > elems;
10083 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10084 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10085 elems.push_back( ite->next() );
10086 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10087 elems.push_back( ite->next() );
10090 // compute the mesh on the FACE
10091 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10092 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10094 // re-fill proxy sub-meshes of the FACE
10095 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10096 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10097 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10098 psm->AddElement( ite->next() );
10101 for ( size_t i = 0; i < elems.size(); ++i )
10102 smDS->AddElement( elems[i] );
10104 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10105 return error( errMsg );
10107 } // end of re-meshing in case of failed smoothing
10110 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10111 bool isStructuredFixed = false;
10112 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10113 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10114 if ( !isStructuredFixed )
10116 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10117 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10119 for ( int st = 3; st; --st )
10122 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10123 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10124 case 3: smoothType = _SmoothNode::ANGULAR; break;
10126 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10127 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10129 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10130 smoothType,/*set3D=*/st==1 );
10135 if ( !getMeshDS()->IsEmbeddedMode() )
10136 // Log node movement
10137 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10139 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10140 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10144 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10145 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10147 } // loop on FACES to srink mesh on
10150 // Replace source nodes by target nodes in shrinked mesh edges
10152 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10153 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10154 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10159 //================================================================================
10161 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10163 //================================================================================
10165 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10166 _EdgesOnShape& eos,
10167 SMESH_MesherHelper& helper,
10168 const SMESHDS_SubMesh* faceSubMesh)
10170 const SMDS_MeshNode* srcNode = edge._nodes[0];
10171 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10173 if ( eos.SWOLType() == TopAbs_FACE )
10175 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10178 return srcNode == tgtNode;
10180 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10181 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10182 gp_Vec2d uvDir( srcUV, tgtUV );
10183 double uvLen = uvDir.Magnitude();
10185 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10188 edge._pos.resize(1);
10189 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10191 // set UV of source node to target node
10192 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10193 pos->SetUParameter( srcUV.X() );
10194 pos->SetVParameter( srcUV.Y() );
10196 else // _sWOL is TopAbs_EDGE
10198 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10201 return srcNode == tgtNode;
10203 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10204 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10205 if ( !edgeSM || edgeSM->NbElements() == 0 )
10206 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10208 const SMDS_MeshNode* n2 = 0;
10209 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10210 while ( eIt->more() && !n2 )
10212 const SMDS_MeshElement* e = eIt->next();
10213 if ( !edgeSM->Contains(e)) continue;
10214 n2 = e->GetNode( 0 );
10215 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10218 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10220 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10221 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10222 double u2 = helper.GetNodeU( E, n2, srcNode );
10226 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10228 // tgtNode is located so that it does not make faces with wrong orientation
10231 edge._pos.resize(1);
10232 edge._pos[0].SetCoord( U_TGT, uTgt );
10233 edge._pos[0].SetCoord( U_SRC, uSrc );
10234 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10236 edge._simplices.resize( 1 );
10237 edge._simplices[0]._nPrev = n2;
10239 // set U of source node to the target node
10240 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10241 pos->SetUParameter( uSrc );
10246 //================================================================================
10248 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10250 //================================================================================
10252 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10254 if ( edge._nodes.size() == 1 )
10259 const SMDS_MeshNode* srcNode = edge._nodes[0];
10260 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10261 if ( S.IsNull() ) return;
10265 switch ( S.ShapeType() )
10270 TopLoc_Location loc;
10271 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10272 if ( curve.IsNull() ) return;
10273 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10274 p = curve->Value( ePos->GetUParameter() );
10277 case TopAbs_VERTEX:
10279 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10284 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10285 dumpMove( srcNode );
10289 //================================================================================
10291 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10293 //================================================================================
10295 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10296 SMESH_MesherHelper& helper,
10299 set<const SMDS_MeshNode*> * involvedNodes)
10301 SMESH::Controls::AspectRatio qualifier;
10302 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10303 const double maxAspectRatio = is2D ? 4. : 2;
10304 _NodeCoordHelper xyz( F, helper, is2D );
10306 // find bad triangles
10308 vector< const SMDS_MeshElement* > badTrias;
10309 vector< double > badAspects;
10310 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
10311 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10312 while ( fIt->more() )
10314 const SMDS_MeshElement * f = fIt->next();
10315 if ( f->NbCornerNodes() != 3 ) continue;
10316 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10317 double aspect = qualifier.GetValue( points );
10318 if ( aspect > maxAspectRatio )
10320 badTrias.push_back( f );
10321 badAspects.push_back( aspect );
10326 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10327 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10328 while ( fIt->more() )
10330 const SMDS_MeshElement * f = fIt->next();
10331 if ( f->NbCornerNodes() == 3 )
10332 dumpChangeNodes( f );
10336 if ( badTrias.empty() )
10339 // find couples of faces to swap diagonal
10341 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10342 vector< T2Trias > triaCouples;
10344 TIDSortedElemSet involvedFaces, emptySet;
10345 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10348 double aspRatio [3];
10351 if ( !involvedFaces.insert( badTrias[iTia] ).second )
10353 for ( int iP = 0; iP < 3; ++iP )
10354 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10356 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10357 int bestCouple = -1;
10358 for ( int iSide = 0; iSide < 3; ++iSide )
10360 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10361 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10362 trias [iSide].first = badTrias[iTia];
10363 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10365 if (( ! trias[iSide].second ) ||
10366 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10367 ( ! sm->Contains( trias[iSide].second )))
10370 // aspect ratio of an adjacent tria
10371 for ( int iP = 0; iP < 3; ++iP )
10372 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10373 double aspectInit = qualifier.GetValue( points2 );
10375 // arrange nodes as after diag-swaping
10376 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10377 i3 = helper.WrapIndex( i1-1, 3 );
10379 i3 = helper.WrapIndex( i1+1, 3 );
10381 points1( 1+ iSide ) = points2( 1+ i3 );
10382 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
10384 // aspect ratio after diag-swaping
10385 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10386 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10389 // prevent inversion of a triangle
10390 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10391 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10392 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10395 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10396 bestCouple = iSide;
10399 if ( bestCouple >= 0 )
10401 triaCouples.push_back( trias[bestCouple] );
10402 involvedFaces.insert ( trias[bestCouple].second );
10406 involvedFaces.erase( badTrias[iTia] );
10409 if ( triaCouples.empty() )
10414 SMESH_MeshEditor editor( helper.GetMesh() );
10415 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10416 for ( size_t i = 0; i < triaCouples.size(); ++i )
10418 dumpChangeNodes( triaCouples[i].first );
10419 dumpChangeNodes( triaCouples[i].second );
10420 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10423 if ( involvedNodes )
10424 for ( size_t i = 0; i < triaCouples.size(); ++i )
10426 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10427 triaCouples[i].first->end_nodes() );
10428 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10429 triaCouples[i].second->end_nodes() );
10432 // just for debug dump resulting triangles
10433 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10434 for ( size_t i = 0; i < triaCouples.size(); ++i )
10436 dumpChangeNodes( triaCouples[i].first );
10437 dumpChangeNodes( triaCouples[i].second );
10441 //================================================================================
10443 * \brief Move target node to it's final position on the FACE during shrinking
10445 //================================================================================
10447 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10448 const TopoDS_Face& F,
10449 _EdgesOnShape& eos,
10450 SMESH_MesherHelper& helper )
10452 if ( _pos.empty() )
10453 return false; // already at the target position
10455 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10457 if ( eos.SWOLType() == TopAbs_FACE )
10459 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
10460 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10461 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10462 const double uvLen = tgtUV.Distance( curUV );
10463 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10465 // Select shrinking step such that not to make faces with wrong orientation.
10466 double stepSize = 1e100;
10467 for ( size_t i = 0; i < _simplices.size(); ++i )
10469 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10470 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10471 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10472 gp_XY dirN = uvN2 - uvN1;
10473 double det = uvDir.Crossed( dirN );
10474 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
10475 gp_XY dirN2Cur = curUV - uvN1;
10476 double step = dirN.Crossed( dirN2Cur ) / det;
10478 stepSize = Min( step, stepSize );
10481 if ( uvLen <= stepSize )
10486 else if ( stepSize > 0 )
10488 newUV = curUV + uvDir.XY() * stepSize * kSafe;
10494 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10495 pos->SetUParameter( newUV.X() );
10496 pos->SetVParameter( newUV.Y() );
10499 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10500 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10501 dumpMove( tgtNode );
10504 else // _sWOL is TopAbs_EDGE
10506 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10507 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
10508 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10510 const double u2 = helper.GetNodeU( E, n2, tgtNode );
10511 const double uSrc = _pos[0].Coord( U_SRC );
10512 const double lenTgt = _pos[0].Coord( LEN_TGT );
10514 double newU = _pos[0].Coord( U_TGT );
10515 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10521 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10523 tgtPos->SetUParameter( newU );
10525 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10526 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10527 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10528 dumpMove( tgtNode );
10535 //================================================================================
10537 * \brief Perform smooth on the FACE
10538 * \retval bool - true if the node has been moved
10540 //================================================================================
10542 bool _SmoothNode::Smooth(int& nbBad,
10543 Handle(Geom_Surface)& surface,
10544 SMESH_MesherHelper& helper,
10545 const double refSign,
10549 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10551 // get uv of surrounding nodes
10552 vector<gp_XY> uv( _simplices.size() );
10553 for ( size_t i = 0; i < _simplices.size(); ++i )
10554 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10556 // compute new UV for the node
10557 gp_XY newPos (0,0);
10558 if ( how == TFI && _simplices.size() == 4 )
10561 for ( size_t i = 0; i < _simplices.size(); ++i )
10562 if ( _simplices[i]._nOpp )
10563 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10565 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10567 newPos = helper.calcTFI ( 0.5, 0.5,
10568 corners[0], corners[1], corners[2], corners[3],
10569 uv[1], uv[2], uv[3], uv[0] );
10571 else if ( how == ANGULAR )
10573 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10575 else if ( how == CENTROIDAL && _simplices.size() > 3 )
10577 // average centers of diagonals wieghted with their reciprocal lengths
10578 if ( _simplices.size() == 4 )
10580 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10581 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10582 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10586 double sumWeight = 0;
10587 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10588 for ( int i = 0; i < nb; ++i )
10591 int iTo = i + _simplices.size() - 1;
10592 for ( int j = iFrom; j < iTo; ++j )
10594 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10595 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10597 newPos += w * ( uv[i]+uv[i2] );
10600 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10605 // Laplacian smooth
10606 for ( size_t i = 0; i < _simplices.size(); ++i )
10608 newPos /= _simplices.size();
10611 // count quality metrics (orientation) of triangles around the node
10612 int nbOkBefore = 0;
10613 gp_XY tgtUV = helper.GetNodeUV( face, _node );
10614 for ( size_t i = 0; i < _simplices.size(); ++i )
10615 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10618 for ( size_t i = 0; i < _simplices.size(); ++i )
10619 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10621 if ( nbOkAfter < nbOkBefore )
10623 nbBad += _simplices.size() - nbOkBefore;
10627 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10628 pos->SetUParameter( newPos.X() );
10629 pos->SetVParameter( newPos.Y() );
10636 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10637 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10641 nbBad += _simplices.size() - nbOkAfter;
10642 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10645 //================================================================================
10647 * \brief Computes new UV using angle based smoothing technic
10649 //================================================================================
10651 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10652 const gp_XY& uvToFix,
10653 const double refSign)
10655 uv.push_back( uv.front() );
10657 vector< gp_XY > edgeDir ( uv.size() );
10658 vector< double > edgeSize( uv.size() );
10659 for ( size_t i = 1; i < edgeDir.size(); ++i )
10661 edgeDir [i-1] = uv[i] - uv[i-1];
10662 edgeSize[i-1] = edgeDir[i-1].Modulus();
10663 if ( edgeSize[i-1] < numeric_limits<double>::min() )
10664 edgeDir[i-1].SetX( 100 );
10666 edgeDir[i-1] /= edgeSize[i-1] * refSign;
10668 edgeDir.back() = edgeDir.front();
10669 edgeSize.back() = edgeSize.front();
10673 double sumSize = 0;
10674 for ( size_t i = 1; i < edgeDir.size(); ++i )
10676 if ( edgeDir[i-1].X() > 1. ) continue;
10678 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10679 if ( i == edgeDir.size() ) break;
10681 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10682 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
10683 gp_XY bisec = norm1 + norm2;
10684 double bisecSize = bisec.Modulus();
10685 if ( bisecSize < numeric_limits<double>::min() )
10687 bisec = -edgeDir[i1] + edgeDir[i];
10688 bisecSize = bisec.Modulus();
10690 bisec /= bisecSize;
10692 gp_XY dirToN = uvToFix - p;
10693 double distToN = dirToN.Modulus();
10694 if ( bisec * dirToN < 0 )
10695 distToN = -distToN;
10697 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10699 sumSize += edgeSize[i1] + edgeSize[i];
10701 newPos /= /*nbEdges * */sumSize;
10705 //================================================================================
10707 * \brief Delete _SolidData
10709 //================================================================================
10711 _SolidData::~_SolidData()
10713 TNode2Edge::iterator n2e = _n2eMap.begin();
10714 for ( ; n2e != _n2eMap.end(); ++n2e )
10716 _LayerEdge* & e = n2e->second;
10719 delete e->_curvature;
10720 if ( e->_2neibors )
10721 delete e->_2neibors->_plnNorm;
10722 delete e->_2neibors;
10733 //================================================================================
10735 * \brief Keep a _LayerEdge inflated along the EDGE
10737 //================================================================================
10739 void _Shrinker1D::AddEdge( const _LayerEdge* e,
10740 _EdgesOnShape& eos,
10741 SMESH_MesherHelper& helper )
10744 if ( _nodes.empty() )
10746 _edges[0] = _edges[1] = 0;
10749 // check _LayerEdge
10750 if ( e == _edges[0] || e == _edges[1] )
10752 if ( eos.SWOLType() != TopAbs_EDGE )
10753 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10754 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10755 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10757 // store _LayerEdge
10758 _geomEdge = TopoDS::Edge( eos._sWOL );
10760 BRep_Tool::Range( _geomEdge, f,l );
10761 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10762 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10766 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10767 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10769 if ( _nodes.empty() )
10771 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10772 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10774 TopLoc_Location loc;
10775 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10776 GeomAdaptor_Curve aCurve(C, f,l);
10777 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10779 int nbExpectNodes = eSubMesh->NbNodes();
10780 _initU .reserve( nbExpectNodes );
10781 _normPar.reserve( nbExpectNodes );
10782 _nodes .reserve( nbExpectNodes );
10783 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10784 while ( nIt->more() )
10786 const SMDS_MeshNode* node = nIt->next();
10787 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10788 node == tgtNode0 || node == tgtNode1 )
10789 continue; // refinement nodes
10790 _nodes.push_back( node );
10791 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10792 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10793 _normPar.push_back( len / totLen );
10798 // remove target node of the _LayerEdge from _nodes
10799 size_t nbFound = 0;
10800 for ( size_t i = 0; i < _nodes.size(); ++i )
10801 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10802 _nodes[i] = 0, nbFound++;
10803 if ( nbFound == _nodes.size() )
10808 //================================================================================
10810 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10812 //================================================================================
10814 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10816 if ( _done || _nodes.empty())
10818 const _LayerEdge* e = _edges[0];
10819 if ( !e ) e = _edges[1];
10822 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10823 ( !_edges[1] || _edges[1]->_pos.empty() ));
10826 if ( set3D || _done )
10828 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10829 GeomAdaptor_Curve aCurve(C, f,l);
10832 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10834 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10835 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10837 for ( size_t i = 0; i < _nodes.size(); ++i )
10839 if ( !_nodes[i] ) continue;
10840 double len = totLen * _normPar[i];
10841 GCPnts_AbscissaPoint discret( aCurve, len, f );
10842 if ( !discret.IsDone() )
10843 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10844 double u = discret.Parameter();
10845 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10846 pos->SetUParameter( u );
10847 gp_Pnt p = C->Value( u );
10848 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10853 BRep_Tool::Range( _geomEdge, f,l );
10855 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10857 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10859 for ( size_t i = 0; i < _nodes.size(); ++i )
10861 if ( !_nodes[i] ) continue;
10862 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10863 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10864 pos->SetUParameter( u );
10869 //================================================================================
10871 * \brief Restore initial parameters of nodes on EDGE
10873 //================================================================================
10875 void _Shrinker1D::RestoreParams()
10878 for ( size_t i = 0; i < _nodes.size(); ++i )
10880 if ( !_nodes[i] ) continue;
10881 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10882 pos->SetUParameter( _initU[i] );
10887 //================================================================================
10889 * \brief Replace source nodes by target nodes in shrinked mesh edges
10891 //================================================================================
10893 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10895 const SMDS_MeshNode* nodes[3];
10896 for ( int i = 0; i < 2; ++i )
10898 if ( !_edges[i] ) continue;
10900 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10901 if ( !eSubMesh ) return;
10902 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10903 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10904 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10905 while ( eIt->more() )
10907 const SMDS_MeshElement* e = eIt->next();
10908 if ( !eSubMesh->Contains( e ))
10910 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10911 for ( int iN = 0; iN < e->NbNodes(); ++iN )
10913 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10914 nodes[iN] = ( n == srcNode ? tgtNode : n );
10916 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10921 //================================================================================
10923 * \brief Creates 2D and 1D elements on boundaries of new prisms
10925 //================================================================================
10927 bool _ViscousBuilder::addBoundaryElements()
10929 SMESH_MesherHelper helper( *_mesh );
10931 vector< const SMDS_MeshNode* > faceNodes;
10933 for ( size_t i = 0; i < _sdVec.size(); ++i )
10935 _SolidData& data = _sdVec[i];
10936 TopTools_IndexedMapOfShape geomEdges;
10937 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10938 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10940 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10941 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10944 // Get _LayerEdge's based on E
10946 map< double, const SMDS_MeshNode* > u2nodes;
10947 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10950 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10951 TNode2Edge & n2eMap = data._n2eMap;
10952 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10954 //check if 2D elements are needed on E
10955 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10956 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10957 ledges.push_back( n2e->second );
10959 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10960 continue; // no layers on E
10961 ledges.push_back( n2eMap[ u2n->second ]);
10963 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10964 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10965 int nbSharedPyram = 0;
10966 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10967 while ( vIt->more() )
10969 const SMDS_MeshElement* v = vIt->next();
10970 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10972 if ( nbSharedPyram > 1 )
10973 continue; // not free border of the pyramid
10976 faceNodes.push_back( ledges[0]->_nodes[0] );
10977 faceNodes.push_back( ledges[1]->_nodes[0] );
10978 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10979 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10981 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10982 continue; // faces already created
10984 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10985 ledges.push_back( n2eMap[ u2n->second ]);
10987 // Find out orientation and type of face to create
10989 bool reverse = false, isOnFace;
10991 map< TGeomID, TopoDS_Shape >::iterator e2f =
10992 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10994 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10996 F = e2f->second.Oriented( TopAbs_FORWARD );
10997 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
10998 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
10999 reverse = !reverse, F.Reverse();
11000 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11001 reverse = !reverse;
11005 // find FACE with layers sharing E
11006 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
11007 while ( fIt->more() && F.IsNull() )
11009 const TopoDS_Shape* pF = fIt->next();
11010 if ( helper.IsSubShape( *pF, data._solid) &&
11011 !data._ignoreFaceIds.count( e2f->first ))
11015 // Find the sub-mesh to add new faces
11016 SMESHDS_SubMesh* sm = 0;
11018 sm = getMeshDS()->MeshElements( F );
11020 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11022 return error("error in addBoundaryElements()", data._index);
11025 const int dj1 = reverse ? 0 : 1;
11026 const int dj2 = reverse ? 1 : 0;
11027 for ( size_t j = 1; j < ledges.size(); ++j )
11029 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11030 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11031 if ( nn1.size() == nn2.size() )
11034 for ( size_t z = 1; z < nn1.size(); ++z )
11035 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11037 for ( size_t z = 1; z < nn1.size(); ++z )
11038 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11040 else if ( nn1.size() == 1 )
11043 for ( size_t z = 1; z < nn2.size(); ++z )
11044 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11046 for ( size_t z = 1; z < nn2.size(); ++z )
11047 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11052 for ( size_t z = 1; z < nn1.size(); ++z )
11053 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11055 for ( size_t z = 1; z < nn1.size(); ++z )
11056 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11061 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11063 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11064 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11065 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11067 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11068 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11070 helper.SetSubShape( eos->_sWOL );
11071 helper.SetElementsOnShape( true );
11072 for ( size_t z = 1; z < nn.size(); ++z )
11073 helper.AddEdge( nn[z-1], nn[z] );
11077 } // loop on EDGE's
11078 } // loop on _SolidData's