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 achieved with the last inflation step
413 double _maxLen; // maximal possible length
414 double _cosin; // of angle (_normal ^ surface)
415 double _minAngle; // of _simplices
416 double _lenFactor; // to compute _len taking _cosin into account
419 // simplices connected to the source node (_nodes[0]);
420 // used for smoothing and quality check of _LayerEdge's based on the FACE
421 vector<_Simplex> _simplices;
422 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423 PSmooFun _smooFunction; // smoothing function
424 _Curvature* _curvature;
425 // data for smoothing of _LayerEdge's based on the EDGE
426 _2NearEdges* _2neibors;
428 enum EFlags { TO_SMOOTH = 0x0000001,
429 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
430 SMOOTHED = 0x0000004, // set by _LayerEdge::Smooth()
431 DIFFICULT = 0x0000008, // near concave VERTEX
432 ON_CONCAVE_FACE = 0x0000010,
433 BLOCKED = 0x0000020, // not to inflate any more
434 INTERSECTED = 0x0000040, // close intersection with a face found
435 NORMAL_UPDATED = 0x0000080,
436 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
437 MARKED = 0x0000200, // local usage
438 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
439 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
440 SMOOTHED_C1 = 0x0001000, // is on _eosC1
441 DISTORTED = 0x0002000, // was bad before smoothing
442 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
443 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
444 UNUSED_FLAG = 0x0100000 // to add user flags after
446 bool Is ( int flag ) const { return _flags & flag; }
447 void Set ( int flag ) { _flags |= flag; }
448 void Unset( int flag ) { _flags &= ~flag; }
449 std::string DumpFlags() const; // debug
451 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
452 bool SetNewLength2d( Handle(Geom_Surface)& surface,
453 const TopoDS_Face& F,
455 SMESH_MesherHelper& helper );
456 void SetDataByNeighbors( const SMDS_MeshNode* n1,
457 const SMDS_MeshNode* n2,
458 const _EdgesOnShape& eos,
459 SMESH_MesherHelper& helper);
460 void Block( _SolidData& data );
461 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
462 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
463 const TNode2Edge& n2eMap);
464 void SmoothPos( const vector< double >& segLen, const double tol );
465 int GetSmoothedPos( const double tol );
466 int Smooth(const int step, const bool isConcaveFace, bool findBest);
467 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
468 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
469 void SmoothWoCheck();
470 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
471 const TopoDS_Face& F,
472 SMESH_MesherHelper& helper);
473 void MoveNearConcaVer( const _EdgesOnShape* eov,
474 const _EdgesOnShape* eos,
476 vector< _LayerEdge* > & badSmooEdges);
477 bool FindIntersection( SMESH_ElementSearcher& searcher,
479 const double& epsilon,
481 const SMDS_MeshElement** face = 0);
482 bool SegTriaInter( const gp_Ax1& lastSegment,
487 const double& epsilon) const;
488 bool SegTriaInter( const gp_Ax1& lastSegment,
489 const SMDS_MeshNode* n0,
490 const SMDS_MeshNode* n1,
491 const SMDS_MeshNode* n2,
493 const double& epsilon) const
494 { return SegTriaInter( lastSegment,
495 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
498 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
499 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
500 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
501 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
502 bool IsOnEdge() const { return _2neibors; }
503 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
504 void SetCosin( double cosin );
505 void SetNormal( const gp_XYZ& n ) { _normal = n; }
506 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
507 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
508 void SetSmooLen( double len ) { // set _len at which smoothing is needed
509 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
511 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
513 gp_XYZ smoothLaplacian();
514 gp_XYZ smoothAngular();
515 gp_XYZ smoothLengthWeighted();
516 gp_XYZ smoothCentroidal();
517 gp_XYZ smoothNefPolygon();
519 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
520 static const int theNbSmooFuns = FUN_NB;
521 static PSmooFun _funs[theNbSmooFuns];
522 static const char* _funNames[theNbSmooFuns+1];
523 int smooFunID( PSmooFun fun=0) const;
525 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
526 &_LayerEdge::smoothLengthWeighted,
527 &_LayerEdge::smoothCentroidal,
528 &_LayerEdge::smoothNefPolygon,
529 &_LayerEdge::smoothAngular };
530 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
538 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
540 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
541 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
544 //--------------------------------------------------------------------------------
546 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
550 gp_XY _pos, _dir, _inNorm;
551 bool IsOut( const gp_XY p, const double tol ) const
553 return _inNorm * ( p - _pos ) < -tol;
555 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
557 //const double eps = 1e-10;
558 double D = _dir.Crossed( hp._dir );
559 if ( fabs(D) < std::numeric_limits<double>::min())
561 gp_XY vec21 = _pos - hp._pos;
562 double u = hp._dir.Crossed( vec21 ) / D;
563 intPnt = _pos + _dir * u;
567 //--------------------------------------------------------------------------------
569 * Structure used to smooth a _LayerEdge based on an EDGE.
573 double _wgt [2]; // weights of _nodes
574 _LayerEdge* _edges[2];
576 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
579 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
580 const SMDS_MeshNode* tgtNode(bool is2nd) {
581 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
583 const SMDS_MeshNode* srcNode(bool is2nd) {
584 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
587 std::swap( _wgt [0], _wgt [1] );
588 std::swap( _edges[0], _edges[1] );
590 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
591 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
593 bool include( const _LayerEdge* e ) {
594 return ( _edges[0] == e || _edges[1] == e );
599 //--------------------------------------------------------------------------------
601 * \brief Layers parameters got by averaging several hypotheses
605 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
606 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
610 void Add( const StdMeshers_ViscousLayers* hyp )
615 _nbLayers = hyp->GetNumberLayers();
616 //_thickness += hyp->GetTotalThickness();
617 _thickness = Max( _thickness, hyp->GetTotalThickness() );
618 _stretchFactor += hyp->GetStretchFactor();
619 _method = hyp->GetMethod();
622 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
623 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
624 int GetNumberLayers() const { return _nbLayers; }
625 int GetMethod() const { return _method; }
627 bool UseSurfaceNormal() const
628 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
629 bool ToSmooth() const
630 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
631 bool IsOffsetMethod() const
632 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
635 int _nbLayers, _nbHyps, _method;
636 double _thickness, _stretchFactor;
639 //--------------------------------------------------------------------------------
641 * \brief _LayerEdge's on a shape and other shape data
645 vector< _LayerEdge* > _edges;
649 SMESH_subMesh * _subMesh;
650 // face or edge w/o layer along or near which _edges are inflated
652 bool _isRegularSWOL; // w/o singularities
653 // averaged StdMeshers_ViscousLayers parameters
656 _Smoother1D* _edgeSmoother;
657 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
658 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
660 vector< gp_XYZ > _faceNormals; // if _shape is FACE
661 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
663 Handle(ShapeAnalysis_Surface) _offsetSurf;
664 _LayerEdge* _edgeForOffset;
666 _SolidData* _data; // parent SOLID
668 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
669 size_t size() const { return _edges.size(); }
670 TopAbs_ShapeEnum ShapeType() const
671 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
672 TopAbs_ShapeEnum SWOLType() const
673 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
674 bool HasC1( const _EdgesOnShape* other ) const
675 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
676 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
677 _SolidData& GetData() const { return *_data; }
679 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
682 //--------------------------------------------------------------------------------
684 * \brief Convex FACE whose radius of curvature is less than the thickness of
685 * layers. It is used to detect distortion of prisms based on a convex
686 * FACE and to update normals to enable further increasing the thickness
692 // edges whose _simplices are used to detect prism distortion
693 vector< _LayerEdge* > _simplexTestEdges;
695 // map a sub-shape to _SolidData::_edgesOnShape
696 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
700 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
702 double GetMaxCurvature( _SolidData& data,
704 BRepLProp_SLProps& surfProp,
705 SMESH_MesherHelper& helper);
707 bool GetCenterOfCurvature( _LayerEdge* ledge,
708 BRepLProp_SLProps& surfProp,
709 SMESH_MesherHelper& helper,
710 gp_Pnt & center ) const;
711 bool CheckPrisms() const;
714 //--------------------------------------------------------------------------------
716 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
717 * at inflation up to the full thickness. A detected collision
718 * is fixed in updateNormals()
720 struct _CollisionEdges
723 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
724 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
725 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
728 //--------------------------------------------------------------------------------
730 * \brief Data of a SOLID
734 typedef const StdMeshers_ViscousLayers* THyp;
736 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
737 TGeomID _index; // SOLID id
738 _MeshOfSolid* _proxyMesh;
740 list< TopoDS_Shape > _hypShapes;
741 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
742 set< TGeomID > _reversedFaceIds;
743 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
745 double _stepSize, _stepSizeCoeff, _geomSize;
746 const SMDS_MeshNode* _stepSizeNodes[2];
748 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
750 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
751 map< TGeomID, TNode2Edge* > _s2neMap;
752 // _LayerEdge's with underlying shapes
753 vector< _EdgesOnShape > _edgesOnShape;
755 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
756 // layers and a FACE w/o layers
757 // value: the shape (FACE or EDGE) to shrink mesh on.
758 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
759 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
761 // Convex FACEs whose radius of curvature is less than the thickness of layers
762 map< TGeomID, _ConvexFace > _convexFaces;
764 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
765 // the adjacent SOLID
766 set< TGeomID > _noShrinkShapes;
768 int _nbShapesToSmooth;
770 vector< _CollisionEdges > _collisionEdges;
771 set< TGeomID > _concaveFaces;
773 double _maxThickness; // of all _hyps
774 double _minThickness; // of all _hyps
776 double _epsilon; // precision for SegTriaInter()
778 SMESH_MesherHelper* _helper;
780 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
782 :_solid(s), _proxyMesh(m), _helper(0) {}
785 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
786 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
788 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
789 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
790 return id2face == _convexFaces.end() ? 0 : & id2face->second;
792 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
793 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
794 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
795 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
797 SMESH_MesherHelper& GetHelper() const { return *_helper; }
799 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
800 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
801 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
802 _edgesOnShape[i]._edges[j]->Unset( flag );
804 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
805 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
807 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
809 //--------------------------------------------------------------------------------
811 * \brief Offset plane used in getNormalByOffset()
817 int _faceIndexNext[2];
818 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
821 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
823 void ComputeIntersectionLine( _OffsetPlane& pln,
824 const TopoDS_Edge& E,
825 const TopoDS_Vertex& V );
826 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
827 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
829 //--------------------------------------------------------------------------------
831 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
833 struct _CentralCurveOnEdge
836 vector< gp_Pnt > _curvaCenters;
837 vector< _LayerEdge* > _ledges;
838 vector< gp_XYZ > _normals; // new normal for each of _ledges
839 vector< double > _segLength2;
842 TopoDS_Face _adjFace;
843 bool _adjFaceToSmooth;
845 void Append( const gp_Pnt& center, _LayerEdge* ledge )
847 if ( _curvaCenters.size() > 0 )
848 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
849 _curvaCenters.push_back( center );
850 _ledges.push_back( ledge );
851 _normals.push_back( ledge->_normal );
853 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
854 void SetShapes( const TopoDS_Edge& edge,
855 const _ConvexFace& convFace,
857 SMESH_MesherHelper& helper);
859 //--------------------------------------------------------------------------------
861 * \brief Data of node on a shrinked FACE
865 const SMDS_MeshNode* _node;
866 vector<_Simplex> _simplices; // for quality check
868 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
870 bool Smooth(int& badNb,
871 Handle(Geom_Surface)& surface,
872 SMESH_MesherHelper& helper,
873 const double refSign,
877 gp_XY computeAngularPos(vector<gp_XY>& uv,
878 const gp_XY& uvToFix,
879 const double refSign );
882 //--------------------------------------------------------------------------------
884 * \brief Builder of viscous layers
886 class _ViscousBuilder
891 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
892 const TopoDS_Shape& shape);
893 // check validity of hypotheses
894 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
895 const TopoDS_Shape& shape );
897 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
898 void RestoreListeners();
900 // computes SMESH_ProxyMesh::SubMesh::_n2n;
901 bool MakeN2NMap( _MeshOfSolid* pm );
905 bool findSolidsWithLayers();
906 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
907 bool findFacesWithLayers(const bool onlyWith=false);
908 void getIgnoreFaces(const TopoDS_Shape& solid,
909 const StdMeshers_ViscousLayers* hyp,
910 const TopoDS_Shape& hypShape,
911 set<TGeomID>& ignoreFaces);
912 bool makeLayer(_SolidData& data);
913 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
914 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
915 SMESH_MesherHelper& helper, _SolidData& data);
916 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
917 const TopoDS_Face& face,
918 SMESH_MesherHelper& helper,
920 bool shiftInside=false);
921 bool getFaceNormalAtSingularity(const gp_XY& uv,
922 const TopoDS_Face& face,
923 SMESH_MesherHelper& helper,
925 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
926 gp_XYZ getNormalByOffset( _LayerEdge* edge,
927 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
929 bool lastNoOffset = false);
930 bool findNeiborsOnEdge(const _LayerEdge* edge,
931 const SMDS_MeshNode*& n1,
932 const SMDS_MeshNode*& n2,
935 void findSimplexTestEdges( _SolidData& data,
936 vector< vector<_LayerEdge*> >& edgesByGeom);
937 void computeGeomSize( _SolidData& data );
938 bool findShapesToSmooth( _SolidData& data);
939 void limitStepSizeByCurvature( _SolidData& data );
940 void limitStepSize( _SolidData& data,
941 const SMDS_MeshElement* face,
942 const _LayerEdge* maxCosinEdge );
943 void limitStepSize( _SolidData& data, const double minSize);
944 bool inflate(_SolidData& data);
945 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
946 int invalidateBadSmooth( _SolidData& data,
947 SMESH_MesherHelper& helper,
948 vector< _LayerEdge* >& badSmooEdges,
949 vector< _EdgesOnShape* >& eosC1,
951 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
952 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
953 vector< _EdgesOnShape* >& eosC1,
954 int smooStep=0, int moveAll=false );
955 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
956 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
958 SMESH_MesherHelper& helper );
959 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
960 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
961 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
962 SMESH_MesherHelper& helper );
963 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
964 bool updateNormalsOfConvexFaces( _SolidData& data,
965 SMESH_MesherHelper& helper,
967 void updateNormalsOfC1Vertices( _SolidData& data );
968 bool updateNormalsOfSmoothed( _SolidData& data,
969 SMESH_MesherHelper& helper,
971 const double stepSize );
972 bool isNewNormalOk( _SolidData& data,
974 const gp_XYZ& newNormal);
975 bool refine(_SolidData& data);
976 bool shrink(_SolidData& data);
977 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
978 SMESH_MesherHelper& helper,
979 const SMESHDS_SubMesh* faceSubMesh );
980 void restoreNoShrink( _LayerEdge& edge ) const;
981 void fixBadFaces(const TopoDS_Face& F,
982 SMESH_MesherHelper& helper,
985 set<const SMDS_MeshNode*> * involvedNodes=NULL);
986 bool addBoundaryElements(_SolidData& data);
988 bool error( const string& text, int solidID=-1 );
989 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
992 void makeGroupOfLE();
995 SMESH_ComputeErrorPtr _error;
997 vector< _SolidData > _sdVec;
998 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
999 TopTools_MapOfShape _shrinkedFaces;
1004 //--------------------------------------------------------------------------------
1006 * \brief Shrinker of nodes on the EDGE
1010 TopoDS_Edge _geomEdge;
1011 vector<double> _initU;
1012 vector<double> _normPar;
1013 vector<const SMDS_MeshNode*> _nodes;
1014 const _LayerEdge* _edges[2];
1017 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1018 void Compute(bool set3D, SMESH_MesherHelper& helper);
1019 void RestoreParams();
1020 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1021 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1022 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1023 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1024 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1025 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1027 //--------------------------------------------------------------------------------
1029 * \brief Smoother of _LayerEdge's on EDGE.
1033 struct OffPnt // point of the offsetted EDGE
1035 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1036 double _len; // length reached at previous inflation step
1037 double _param; // on EDGE
1038 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1039 gp_XYZ _edgeDir;// EDGE tangent at _param
1040 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1042 vector< OffPnt > _offPoints;
1043 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1044 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1045 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1046 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1047 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1048 _EdgesOnShape& _eos;
1049 double _curveLen; // length of the EDGE
1050 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1052 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1054 SMESH_MesherHelper& helper);
1056 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1057 _EdgesOnShape& eos )
1058 : _anaCurve( curveForSmooth ), _eos( eos )
1061 bool Perform(_SolidData& data,
1062 Handle(ShapeAnalysis_Surface)& surface,
1063 const TopoDS_Face& F,
1064 SMESH_MesherHelper& helper );
1066 void prepare(_SolidData& data );
1068 void findEdgesToSmooth();
1070 bool isToSmooth( int iE );
1072 bool smoothAnalyticEdge( _SolidData& data,
1073 Handle(ShapeAnalysis_Surface)& surface,
1074 const TopoDS_Face& F,
1075 SMESH_MesherHelper& helper);
1076 bool smoothComplexEdge( _SolidData& data,
1077 Handle(ShapeAnalysis_Surface)& surface,
1078 const TopoDS_Face& F,
1079 SMESH_MesherHelper& helper);
1080 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1081 const gp_XYZ& edgeDir);
1082 _LayerEdge* getLEdgeOnV( bool is2nd )
1084 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1086 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1088 //--------------------------------------------------------------------------------
1090 * \brief Class of temporary mesh face.
1091 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1092 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1094 struct _TmpMeshFace : public SMDS_MeshElement
1096 vector<const SMDS_MeshNode* > _nn;
1097 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1098 int id, int faceID=-1, int idInFace=-1):
1099 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1100 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1101 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1102 virtual vtkIdType GetVtkType() const { return -1; }
1103 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1104 virtual SMDSAbs_GeometryType GetGeomType() const
1105 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1106 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1107 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1109 //--------------------------------------------------------------------------------
1111 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1113 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1115 _LayerEdge *_le1, *_le2;
1116 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1117 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1119 _nn[0]=_le1->_nodes[0];
1120 _nn[1]=_le1->_nodes.back();
1121 _nn[2]=_le2->_nodes.back();
1122 _nn[3]=_le2->_nodes[0];
1124 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1126 SMESH_TNodeXYZ p0s( _nn[0] );
1127 SMESH_TNodeXYZ p0t( _nn[1] );
1128 SMESH_TNodeXYZ p1t( _nn[2] );
1129 SMESH_TNodeXYZ p1s( _nn[3] );
1130 gp_XYZ v0 = p0t - p0s;
1131 gp_XYZ v1 = p1t - p1s;
1132 gp_XYZ v01 = p1s - p0s;
1133 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1138 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1140 _nn[0]=le1->_nodes[0];
1141 _nn[1]=le1->_nodes.back();
1142 _nn[2]=le2->_nodes.back();
1143 _nn[3]=le2->_nodes[0];
1147 //--------------------------------------------------------------------------------
1149 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1150 * \warning Location of a surface is ignored
1152 struct _NodeCoordHelper
1154 SMESH_MesherHelper& _helper;
1155 const TopoDS_Face& _face;
1156 Handle(Geom_Surface) _surface;
1157 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1159 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1160 : _helper( helper ), _face( F )
1164 TopLoc_Location loc;
1165 _surface = BRep_Tool::Surface( _face, loc );
1167 if ( _surface.IsNull() )
1168 _fun = & _NodeCoordHelper::direct;
1170 _fun = & _NodeCoordHelper::byUV;
1172 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1175 gp_XYZ direct(const SMDS_MeshNode* n) const
1177 return SMESH_TNodeXYZ( n );
1179 gp_XYZ byUV (const SMDS_MeshNode* n) const
1181 gp_XY uv = _helper.GetNodeUV( _face, n );
1182 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1186 //================================================================================
1188 * \brief Check angle between vectors
1190 //================================================================================
1192 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1194 double dot = v1 * v2; // cos * |v1| * |v2|
1195 double l1 = v1.SquareMagnitude();
1196 double l2 = v2.SquareMagnitude();
1197 return (( dot * cos >= 0 ) &&
1198 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1201 } // namespace VISCOUS_3D
1205 //================================================================================
1206 // StdMeshers_ViscousLayers hypothesis
1208 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1209 :SMESH_Hypothesis(hypId, studyId, gen),
1210 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1211 _method( SURF_OFFSET_SMOOTH )
1213 _name = StdMeshers_ViscousLayers::GetHypType();
1214 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1215 } // --------------------------------------------------------------------------------
1216 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1218 if ( faceIds != _shapeIds )
1219 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1220 if ( _isToIgnoreShapes != toIgnore )
1221 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1222 } // --------------------------------------------------------------------------------
1223 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1225 if ( thickness != _thickness )
1226 _thickness = thickness, NotifySubMeshesHypothesisModification();
1227 } // --------------------------------------------------------------------------------
1228 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1230 if ( _nbLayers != nb )
1231 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1232 } // --------------------------------------------------------------------------------
1233 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1235 if ( _stretchFactor != factor )
1236 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1237 } // --------------------------------------------------------------------------------
1238 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1240 if ( _method != method )
1241 _method = method, NotifySubMeshesHypothesisModification();
1242 } // --------------------------------------------------------------------------------
1243 SMESH_ProxyMesh::Ptr
1244 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1245 const TopoDS_Shape& theShape,
1246 const bool toMakeN2NMap) const
1248 using namespace VISCOUS_3D;
1249 _ViscousBuilder builder;
1250 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1251 if ( err && !err->IsOK() )
1252 return SMESH_ProxyMesh::Ptr();
1254 vector<SMESH_ProxyMesh::Ptr> components;
1255 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1256 for ( ; exp.More(); exp.Next() )
1258 if ( _MeshOfSolid* pm =
1259 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1261 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1262 if ( !builder.MakeN2NMap( pm ))
1263 return SMESH_ProxyMesh::Ptr();
1264 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1265 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1267 if ( pm->_warning && !pm->_warning->IsOK() )
1269 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1270 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1271 if ( !smError || smError->IsOK() )
1272 smError = pm->_warning;
1275 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1277 switch ( components.size() )
1281 case 1: return components[0];
1283 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1285 return SMESH_ProxyMesh::Ptr();
1286 } // --------------------------------------------------------------------------------
1287 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1289 save << " " << _nbLayers
1290 << " " << _thickness
1291 << " " << _stretchFactor
1292 << " " << _shapeIds.size();
1293 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1294 save << " " << _shapeIds[i];
1295 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1296 save << " " << _method;
1298 } // --------------------------------------------------------------------------------
1299 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1301 int nbFaces, faceID, shapeToTreat, method;
1302 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1303 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1304 _shapeIds.push_back( faceID );
1305 if ( load >> shapeToTreat ) {
1306 _isToIgnoreShapes = !shapeToTreat;
1307 if ( load >> method )
1308 _method = (ExtrusionMethod) method;
1311 _isToIgnoreShapes = true; // old behavior
1314 } // --------------------------------------------------------------------------------
1315 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1316 const TopoDS_Shape& theShape)
1320 } // --------------------------------------------------------------------------------
1321 SMESH_ComputeErrorPtr
1322 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1323 const TopoDS_Shape& theShape,
1324 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1326 VISCOUS_3D::_ViscousBuilder builder;
1327 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1328 if ( err && !err->IsOK() )
1329 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1331 theStatus = SMESH_Hypothesis::HYP_OK;
1335 // --------------------------------------------------------------------------------
1336 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1339 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1340 return IsToIgnoreShapes() ? !isIn : isIn;
1342 // END StdMeshers_ViscousLayers hypothesis
1343 //================================================================================
1345 namespace VISCOUS_3D
1347 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1351 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1352 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1353 gp_Pnt p = BRep_Tool::Pnt( fromV );
1354 double distF = p.SquareDistance( c->Value( f ));
1355 double distL = p.SquareDistance( c->Value( l ));
1356 c->D1(( distF < distL ? f : l), p, dir );
1357 if ( distL < distF ) dir.Reverse();
1360 //--------------------------------------------------------------------------------
1361 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1362 SMESH_MesherHelper& helper)
1365 double f,l; gp_Pnt p;
1366 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1367 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1368 double u = helper.GetNodeU( E, atNode );
1372 //--------------------------------------------------------------------------------
1373 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1374 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1376 //--------------------------------------------------------------------------------
1377 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1378 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1381 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1384 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1385 return getFaceDir( F, v, node, helper, ok );
1387 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1388 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1389 gp_Pnt p; gp_Vec du, dv, norm;
1390 surface->D1( uv.X(),uv.Y(), p, du,dv );
1393 double u = helper.GetNodeU( fromE, node, 0, &ok );
1395 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1396 if ( o == TopAbs_REVERSED )
1399 gp_Vec dir = norm ^ du;
1401 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1402 helper.IsClosedEdge( fromE ))
1404 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1405 else c->D1( f, p, dv );
1406 if ( o == TopAbs_REVERSED )
1408 gp_Vec dir2 = norm ^ dv;
1409 dir = dir.Normalized() + dir2.Normalized();
1413 //--------------------------------------------------------------------------------
1414 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1415 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1416 bool& ok, double* cosin)
1418 TopoDS_Face faceFrw = F;
1419 faceFrw.Orientation( TopAbs_FORWARD );
1420 //double f,l; TopLoc_Location loc;
1421 TopoDS_Edge edges[2]; // sharing a vertex
1424 TopoDS_Vertex VV[2];
1425 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1426 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1428 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1429 if ( SMESH_Algo::isDegenerated( e )) continue;
1430 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1431 if ( VV[1].IsSame( fromV )) {
1432 nbEdges += edges[ 0 ].IsNull();
1435 else if ( VV[0].IsSame( fromV )) {
1436 nbEdges += edges[ 1 ].IsNull();
1441 gp_XYZ dir(0,0,0), edgeDir[2];
1444 // get dirs of edges going fromV
1446 for ( size_t i = 0; i < nbEdges && ok; ++i )
1448 edgeDir[i] = getEdgeDir( edges[i], fromV );
1449 double size2 = edgeDir[i].SquareModulus();
1450 if (( ok = size2 > numeric_limits<double>::min() ))
1451 edgeDir[i] /= sqrt( size2 );
1453 if ( !ok ) return dir;
1455 // get angle between the 2 edges
1457 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1458 if ( Abs( angle ) < 5 * M_PI/180 )
1460 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1464 dir = edgeDir[0] + edgeDir[1];
1469 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1470 *cosin = Cos( angle );
1473 else if ( nbEdges == 1 )
1475 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1476 if ( cosin ) *cosin = 1.;
1486 //================================================================================
1488 * \brief Finds concave VERTEXes of a FACE
1490 //================================================================================
1492 bool getConcaveVertices( const TopoDS_Face& F,
1493 SMESH_MesherHelper& helper,
1494 set< TGeomID >* vertices = 0)
1496 // check angles at VERTEXes
1498 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1499 for ( size_t iW = 0; iW < wires.size(); ++iW )
1501 const int nbEdges = wires[iW]->NbEdges();
1502 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1504 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1506 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1507 int iE2 = ( iE1 + 1 ) % nbEdges;
1508 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1509 iE2 = ( iE2 + 1 ) % nbEdges;
1510 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1511 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1512 wires[iW]->Edge( iE2 ), F, V );
1513 if ( angle < -5. * M_PI / 180. )
1517 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1521 return vertices ? !vertices->empty() : false;
1524 //================================================================================
1526 * \brief Returns true if a FACE is bound by a concave EDGE
1528 //================================================================================
1530 bool isConcave( const TopoDS_Face& F,
1531 SMESH_MesherHelper& helper,
1532 set< TGeomID >* vertices = 0 )
1534 bool isConcv = false;
1535 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1537 gp_Vec2d drv1, drv2;
1539 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1540 for ( ; eExp.More(); eExp.Next() )
1542 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1543 if ( SMESH_Algo::isDegenerated( E )) continue;
1544 // check if 2D curve is concave
1545 BRepAdaptor_Curve2d curve( E, F );
1546 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1547 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1548 curve.Intervals( intervals, GeomAbs_C2 );
1549 bool isConvex = true;
1550 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1552 double u1 = intervals( i );
1553 double u2 = intervals( i+1 );
1554 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1555 double cross = drv1 ^ drv2;
1556 if ( E.Orientation() == TopAbs_REVERSED )
1558 isConvex = ( cross > -1e-9 ); // 0.1 );
1562 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1571 // check angles at VERTEXes
1572 if ( getConcaveVertices( F, helper, vertices ))
1578 //================================================================================
1580 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1581 * \param [in] face - the mesh face to treat
1582 * \param [in] nodeOnEdge - a node on the EDGE
1583 * \param [out] faceSize - the computed distance
1584 * \return bool - true if faceSize computed
1586 //================================================================================
1588 bool getDistFromEdge( const SMDS_MeshElement* face,
1589 const SMDS_MeshNode* nodeOnEdge,
1592 faceSize = Precision::Infinite();
1595 int nbN = face->NbCornerNodes();
1596 int iOnE = face->GetNodeIndex( nodeOnEdge );
1597 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1598 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1599 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1600 face->GetNode( iNext[1] ) };
1601 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1602 double segLen = -1.;
1603 // look for two neighbor not in-FACE nodes of face
1604 for ( int i = 0; i < 2; ++i )
1606 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1607 nNext[i]->GetID() < nodeOnEdge->GetID() )
1609 // look for an in-FACE node
1610 for ( int iN = 0; iN < nbN; ++iN )
1612 if ( iN == iOnE || iN == iNext[i] )
1614 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1615 gp_XYZ v = pInFace - segEnd;
1618 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1619 segLen = segVec.Modulus();
1621 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1622 faceSize = Min( faceSize, distToSeg );
1630 //================================================================================
1632 * \brief Return direction of axis or revolution of a surface
1634 //================================================================================
1636 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1639 switch ( surface.GetType() ) {
1642 gp_Cone cone = surface.Cone();
1643 axis = cone.Axis().Direction();
1646 case GeomAbs_Sphere:
1648 gp_Sphere sphere = surface.Sphere();
1649 axis = sphere.Position().Direction();
1652 case GeomAbs_SurfaceOfRevolution:
1654 axis = surface.AxeOfRevolution().Direction();
1657 //case GeomAbs_SurfaceOfExtrusion:
1658 case GeomAbs_OffsetSurface:
1660 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1661 return getRovolutionAxis( base->Surface(), axis );
1663 default: return false;
1668 //--------------------------------------------------------------------------------
1669 // DEBUG. Dump intermediate node positions into a python script
1670 // HOWTO use: run python commands written in a console to see
1671 // construction steps of viscous layers
1677 PyDump(SMESH_Mesh& m) {
1678 int tag = 3 + m.GetId();
1679 const char* fname = "/tmp/viscous.py";
1680 cout << "execfile('"<<fname<<"')"<<endl;
1681 py = _pyStream = new ofstream(fname);
1682 *py << "import SMESH" << endl
1683 << "from salome.smesh import smeshBuilder" << endl
1684 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1685 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1686 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1691 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1692 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1693 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1694 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1698 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1699 struct MyStream : public ostream
1701 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1703 void Pause() { py = &_mystream; }
1704 void Resume() { py = _pyStream; }
1708 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1709 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1710 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1711 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1712 void _dumpFunction(const string& fun, int ln)
1713 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1714 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1715 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1716 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1717 void _dumpCmd(const string& txt, int ln)
1718 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1719 void dumpFunctionEnd()
1720 { if (py) *py<< " return"<< endl; }
1721 void dumpChangeNodes( const SMDS_MeshElement* f )
1722 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1723 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1724 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1725 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1729 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1730 #define dumpFunction(f) f
1732 #define dumpMoveComm(n,txt)
1733 #define dumpCmd(txt)
1734 #define dumpFunctionEnd()
1735 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1736 #define debugMsg( txt ) {}
1741 using namespace VISCOUS_3D;
1743 //================================================================================
1745 * \brief Constructor of _ViscousBuilder
1747 //================================================================================
1749 _ViscousBuilder::_ViscousBuilder()
1751 _error = SMESH_ComputeError::New(COMPERR_OK);
1755 //================================================================================
1757 * \brief Stores error description and returns false
1759 //================================================================================
1761 bool _ViscousBuilder::error(const string& text, int solidId )
1763 const string prefix = string("Viscous layers builder: ");
1764 _error->myName = COMPERR_ALGO_FAILED;
1765 _error->myComment = prefix + text;
1768 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1769 if ( !sm && !_sdVec.empty() )
1770 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1771 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1773 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1774 if ( smError && smError->myAlgo )
1775 _error->myAlgo = smError->myAlgo;
1777 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1779 // set KO to all solids
1780 for ( size_t i = 0; i < _sdVec.size(); ++i )
1782 if ( _sdVec[i]._index == solidId )
1784 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1785 if ( !sm->IsEmpty() )
1787 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1788 if ( !smError || smError->IsOK() )
1790 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1791 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1795 makeGroupOfLE(); // debug
1800 //================================================================================
1802 * \brief At study restoration, restore event listeners used to clear an inferior
1803 * dim sub-mesh modified by viscous layers
1805 //================================================================================
1807 void _ViscousBuilder::RestoreListeners()
1812 //================================================================================
1814 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1816 //================================================================================
1818 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1820 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1821 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1822 for ( ; fExp.More(); fExp.Next() )
1824 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1825 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1827 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1829 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1832 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1833 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1835 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1836 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1837 while( prxIt->more() )
1839 const SMDS_MeshElement* fSrc = srcIt->next();
1840 const SMDS_MeshElement* fPrx = prxIt->next();
1841 if ( fSrc->NbNodes() != fPrx->NbNodes())
1842 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1843 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1844 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1847 pm->_n2nMapComputed = true;
1851 //================================================================================
1853 * \brief Does its job
1855 //================================================================================
1857 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1858 const TopoDS_Shape& theShape)
1862 // check if proxy mesh already computed
1863 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1865 return error("No SOLID's in theShape"), _error;
1867 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1868 return SMESH_ComputeErrorPtr(); // everything already computed
1870 PyDump debugDump( theMesh );
1871 _pyDump = &debugDump;
1873 // TODO: ignore already computed SOLIDs
1874 if ( !findSolidsWithLayers())
1877 if ( !findFacesWithLayers() )
1880 for ( size_t i = 0; i < _sdVec.size(); ++i )
1883 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1884 if ( _sdVec[iSD]._before.IsEmpty() &&
1885 !_sdVec[iSD]._solid.IsNull() &&
1886 _sdVec[iSD]._n2eMap.empty() )
1889 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1892 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1894 _sdVec[iSD]._solid.Nullify();
1898 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
1901 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
1904 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
1907 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1909 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1910 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1911 _sdVec[iSD]._before.Remove( solid );
1914 makeGroupOfLE(); // debug
1920 //================================================================================
1922 * \brief Check validity of hypotheses
1924 //================================================================================
1926 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1927 const TopoDS_Shape& shape )
1931 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1932 return SMESH_ComputeErrorPtr(); // everything already computed
1935 findSolidsWithLayers();
1936 bool ok = findFacesWithLayers( true );
1938 // remove _MeshOfSolid's of _SolidData's
1939 for ( size_t i = 0; i < _sdVec.size(); ++i )
1940 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1945 return SMESH_ComputeErrorPtr();
1948 //================================================================================
1950 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1952 //================================================================================
1954 bool _ViscousBuilder::findSolidsWithLayers()
1957 TopTools_IndexedMapOfShape allSolids;
1958 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1959 _sdVec.reserve( allSolids.Extent());
1961 SMESH_HypoFilter filter;
1962 for ( int i = 1; i <= allSolids.Extent(); ++i )
1964 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1965 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1966 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1967 continue; // solid is already meshed
1968 SMESH_Algo* algo = sm->GetAlgo();
1969 if ( !algo ) continue;
1970 // TODO: check if algo is hidden
1971 const list <const SMESHDS_Hypothesis *> & allHyps =
1972 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1973 _SolidData* soData = 0;
1974 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1975 const StdMeshers_ViscousLayers* viscHyp = 0;
1976 for ( ; hyp != allHyps.end(); ++hyp )
1977 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1979 TopoDS_Shape hypShape;
1980 filter.Init( filter.Is( viscHyp ));
1981 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1985 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1988 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1989 soData = & _sdVec.back();
1990 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1991 soData->_helper = new SMESH_MesherHelper( *_mesh );
1992 soData->_helper->SetSubShape( allSolids(i) );
1993 _solids.Add( allSolids(i) );
1995 soData->_hyps.push_back( viscHyp );
1996 soData->_hypShapes.push_back( hypShape );
1999 if ( _sdVec.empty() )
2001 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2006 //================================================================================
2008 * \brief Set a _SolidData to be computed before another
2010 //================================================================================
2012 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2014 // check possibility to set this order; get all solids before solidBefore
2015 TopTools_IndexedMapOfShape allSolidsBefore;
2016 allSolidsBefore.Add( solidBefore._solid );
2017 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2019 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2022 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2023 for ( ; soIt.More(); soIt.Next() )
2024 allSolidsBefore.Add( soIt.Value() );
2027 if ( allSolidsBefore.Contains( solidAfter._solid ))
2030 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2031 solidAfter._before.Add( allSolidsBefore(i) );
2036 //================================================================================
2040 //================================================================================
2042 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2044 SMESH_MesherHelper helper( *_mesh );
2045 TopExp_Explorer exp;
2047 // collect all faces-to-ignore defined by hyp
2048 for ( size_t i = 0; i < _sdVec.size(); ++i )
2050 // get faces-to-ignore defined by each hyp
2051 typedef const StdMeshers_ViscousLayers* THyp;
2052 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2053 list< TFacesOfHyp > ignoreFacesOfHyps;
2054 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2055 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2056 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2058 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2059 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2062 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2063 const int nbHyps = _sdVec[i]._hyps.size();
2066 // check if two hypotheses define different parameters for the same FACE
2067 list< TFacesOfHyp >::iterator igFacesOfHyp;
2068 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2070 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2072 igFacesOfHyp = ignoreFacesOfHyps.begin();
2073 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2074 if ( ! igFacesOfHyp->first.count( faceID ))
2077 return error(SMESH_Comment("Several hypotheses define "
2078 "Viscous Layers on the face #") << faceID );
2079 hyp = igFacesOfHyp->second;
2082 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2084 _sdVec[i]._ignoreFaceIds.insert( faceID );
2087 // check if two hypotheses define different number of viscous layers for
2088 // adjacent faces of a solid
2089 set< int > nbLayersSet;
2090 igFacesOfHyp = ignoreFacesOfHyps.begin();
2091 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2093 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2095 if ( nbLayersSet.size() > 1 )
2097 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2099 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2100 THyp hyp1 = 0, hyp2 = 0;
2101 while( const TopoDS_Shape* face = fIt->next() )
2103 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2104 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2105 if ( f2h != _sdVec[i]._face2hyp.end() )
2107 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2110 if ( hyp1 && hyp2 &&
2111 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2113 return error("Two hypotheses define different number of "
2114 "viscous layers on adjacent faces");
2118 } // if ( nbHyps > 1 )
2121 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2125 if ( onlyWith ) // is called to check hypotheses compatibility only
2128 // fill _SolidData::_reversedFaceIds
2129 for ( size_t i = 0; i < _sdVec.size(); ++i )
2131 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2132 for ( ; exp.More(); exp.Next() )
2134 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2135 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2136 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2137 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2138 helper.IsReversedSubMesh( face ))
2140 _sdVec[i]._reversedFaceIds.insert( faceID );
2145 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2146 TopTools_IndexedMapOfShape shapes;
2147 std::string structAlgoName = "Hexa_3D";
2148 for ( size_t i = 0; i < _sdVec.size(); ++i )
2151 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2152 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2154 const TopoDS_Shape& edge = shapes(iE);
2155 // find 2 FACEs sharing an EDGE
2157 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2158 while ( fIt->more())
2160 const TopoDS_Shape* f = fIt->next();
2161 FF[ int( !FF[0].IsNull()) ] = *f;
2163 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2165 // check presence of layers on them
2167 for ( int j = 0; j < 2; ++j )
2168 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2169 if ( ignore[0] == ignore[1] )
2170 continue; // nothing interesting
2171 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2174 if ( !fWOL.IsNull())
2176 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2177 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2182 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2184 for ( size_t i = 0; i < _sdVec.size(); ++i )
2187 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2188 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2190 const TopoDS_Shape& vertex = shapes(iV);
2191 // find faces WOL sharing the vertex
2192 vector< TopoDS_Shape > facesWOL;
2193 size_t totalNbFaces = 0;
2194 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2195 while ( fIt->more())
2197 const TopoDS_Shape* f = fIt->next();
2199 const int fID = getMeshDS()->ShapeToIndex( *f );
2200 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2201 facesWOL.push_back( *f );
2203 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2204 continue; // no layers at this vertex or no WOL
2205 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2206 switch ( facesWOL.size() )
2210 helper.SetSubShape( facesWOL[0] );
2211 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2213 TopoDS_Shape seamEdge;
2214 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2215 while ( eIt->more() && seamEdge.IsNull() )
2217 const TopoDS_Shape* e = eIt->next();
2218 if ( helper.IsRealSeam( *e ) )
2221 if ( !seamEdge.IsNull() )
2223 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2227 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2232 // find an edge shared by 2 faces
2233 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2234 while ( eIt->more())
2236 const TopoDS_Shape* e = eIt->next();
2237 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2238 helper.IsSubShape( *e, facesWOL[1]))
2240 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2246 return error("Not yet supported case", _sdVec[i]._index);
2251 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2252 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2253 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2254 for ( size_t i = 0; i < _sdVec.size(); ++i )
2256 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2257 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2259 const TopoDS_Shape& fWOL = e2f->second;
2260 const TGeomID edgeID = e2f->first;
2261 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2262 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2263 if ( edge.ShapeType() != TopAbs_EDGE )
2264 continue; // shrink shape is VERTEX
2267 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2268 while ( soIt->more() && solid.IsNull() )
2270 const TopoDS_Shape* so = soIt->next();
2271 if ( !so->IsSame( _sdVec[i]._solid ))
2274 if ( solid.IsNull() )
2277 bool noShrinkE = false;
2278 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2279 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2280 size_t iSolid = _solids.FindIndex( solid ) - 1;
2281 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2283 // the adjacent SOLID has NO layers on fWOL;
2284 // shrink allowed if
2285 // - there are layers on the EDGE in the adjacent SOLID
2286 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2287 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2288 bool shrinkAllowed = (( hasWLAdj ) ||
2289 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2290 noShrinkE = !shrinkAllowed;
2292 else if ( iSolid < _sdVec.size() )
2294 // the adjacent SOLID has layers on fWOL;
2295 // check if SOLID's mesh is unstructured and then try to set it
2296 // to be computed after the i-th solid
2297 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2298 noShrinkE = true; // don't shrink fWOL
2302 // the adjacent SOLID has NO layers at all
2303 noShrinkE = isStructured;
2308 _sdVec[i]._noShrinkShapes.insert( edgeID );
2310 // check if there is a collision with to-shrink-from EDGEs in iSolid
2311 // if ( iSolid < _sdVec.size() )
2314 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2315 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2317 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2318 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2319 // if ( eID == edgeID ||
2320 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2321 // _sdVec[i]._noShrinkShapes.count( eID ))
2323 // for ( int is1st = 0; is1st < 2; ++is1st )
2325 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2326 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2328 // return error("No way to make a conformal mesh with "
2329 // "the given set of faces with layers", _sdVec[i]._index);
2336 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2337 // _shrinkShape2Shape is different in the adjacent SOLID
2338 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2340 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2341 bool noShrinkV = false;
2343 if ( iSolid < _sdVec.size() )
2345 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2347 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2348 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2349 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2350 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2351 noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2353 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2357 noShrinkV = noShrinkE;
2362 // the adjacent SOLID has NO layers at all
2363 noShrinkV = ( isStructured ||
2364 _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2367 _sdVec[i]._noShrinkShapes.insert( vID );
2370 } // loop on _sdVec[i]._shrinkShape2Shape
2371 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2374 // add FACEs of other SOLIDs to _ignoreFaceIds
2375 for ( size_t i = 0; i < _sdVec.size(); ++i )
2378 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2380 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2382 if ( !shapes.Contains( exp.Current() ))
2383 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2390 //================================================================================
2392 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2394 //================================================================================
2396 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2397 const StdMeshers_ViscousLayers* hyp,
2398 const TopoDS_Shape& hypShape,
2399 set<TGeomID>& ignoreFaceIds)
2401 TopExp_Explorer exp;
2403 vector<TGeomID> ids = hyp->GetBndShapes();
2404 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2406 for ( size_t ii = 0; ii < ids.size(); ++ii )
2408 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2409 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2410 ignoreFaceIds.insert( ids[ii] );
2413 else // FACEs with layers are given
2415 exp.Init( solid, TopAbs_FACE );
2416 for ( ; exp.More(); exp.Next() )
2418 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2419 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2420 ignoreFaceIds.insert( faceInd );
2424 // ignore internal FACEs if inlets and outlets are specified
2425 if ( hyp->IsToIgnoreShapes() )
2427 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2428 TopExp::MapShapesAndAncestors( hypShape,
2429 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2431 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2433 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2434 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2437 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2439 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2444 //================================================================================
2446 * \brief Create the inner surface of the viscous layer and prepare data for infation
2448 //================================================================================
2450 bool _ViscousBuilder::makeLayer(_SolidData& data)
2452 // get all sub-shapes to make layers on
2453 set<TGeomID> subIds, faceIds;
2454 subIds = data._noShrinkShapes;
2455 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2456 for ( ; exp.More(); exp.Next() )
2458 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2459 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2460 faceIds.insert( fSubM->GetId() );
2463 // make a map to find new nodes on sub-shapes shared with other SOLID
2464 map< TGeomID, TNode2Edge* >::iterator s2ne;
2465 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2466 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2468 TGeomID shapeInd = s2s->first;
2469 for ( size_t i = 0; i < _sdVec.size(); ++i )
2471 if ( _sdVec[i]._index == data._index ) continue;
2472 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2473 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2474 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2476 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2482 // Create temporary faces and _LayerEdge's
2484 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2486 data._stepSize = Precision::Infinite();
2487 data._stepSizeNodes[0] = 0;
2489 SMESH_MesherHelper helper( *_mesh );
2490 helper.SetSubShape( data._solid );
2491 helper.SetElementsOnShape( true );
2493 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2494 TNode2Edge::iterator n2e2;
2496 // collect _LayerEdge's of shapes they are based on
2497 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2498 const int nbShapes = getMeshDS()->MaxShapeIndex();
2499 edgesByGeom.resize( nbShapes+1 );
2501 // set data of _EdgesOnShape's
2502 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2504 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2505 while ( smIt->more() )
2508 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2509 !faceIds.count( sm->GetId() ))
2511 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2514 // make _LayerEdge's
2515 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2517 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2518 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2519 SMESH_ProxyMesh::SubMesh* proxySub =
2520 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2522 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2523 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2525 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2526 while ( eIt->more() )
2528 const SMDS_MeshElement* face = eIt->next();
2529 double faceMaxCosin = -1;
2530 _LayerEdge* maxCosinEdge = 0;
2531 int nbDegenNodes = 0;
2533 newNodes.resize( face->NbCornerNodes() );
2534 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2536 const SMDS_MeshNode* n = face->GetNode( i );
2537 const int shapeID = n->getshapeId();
2538 const bool onDegenShap = helper.IsDegenShape( shapeID );
2539 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2544 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2545 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2546 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2547 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2557 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2558 if ( !(*n2e).second )
2561 _LayerEdge* edge = new _LayerEdge();
2562 edge->_nodes.push_back( n );
2564 edgesByGeom[ shapeID ]._edges.push_back( edge );
2565 const bool noShrink = data._noShrinkShapes.count( shapeID );
2567 SMESH_TNodeXYZ xyz( n );
2569 // set edge data or find already refined _LayerEdge and get data from it
2570 if (( !noShrink ) &&
2571 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2572 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2573 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2575 _LayerEdge* foundEdge = (*n2e2).second;
2576 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2577 foundEdge->_pos.push_back( lastPos );
2578 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2579 const_cast< SMDS_MeshNode* >
2580 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2586 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2588 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2591 if ( edge->_nodes.size() < 2 )
2592 edge->Block( data );
2593 //data._noShrinkShapes.insert( shapeID );
2595 dumpMove(edge->_nodes.back());
2597 if ( edge->_cosin > faceMaxCosin )
2599 faceMaxCosin = edge->_cosin;
2600 maxCosinEdge = edge;
2603 newNodes[ i ] = n2e->second->_nodes.back();
2606 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2608 if ( newNodes.size() - nbDegenNodes < 2 )
2611 // create a temporary face
2612 const SMDS_MeshElement* newFace =
2613 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2614 proxySub->AddElement( newFace );
2616 // compute inflation step size by min size of element on a convex surface
2617 if ( faceMaxCosin > theMinSmoothCosin )
2618 limitStepSize( data, face, maxCosinEdge );
2620 } // loop on 2D elements on a FACE
2621 } // loop on FACEs of a SOLID to create _LayerEdge's
2624 // Set _LayerEdge::_neibors
2625 TNode2Edge::iterator n2e;
2626 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2628 _EdgesOnShape& eos = data._edgesOnShape[iS];
2629 for ( size_t i = 0; i < eos._edges.size(); ++i )
2631 _LayerEdge* edge = eos._edges[i];
2632 TIDSortedNodeSet nearNodes;
2633 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2634 while ( fIt->more() )
2636 const SMDS_MeshElement* f = fIt->next();
2637 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2638 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2640 nearNodes.erase( edge->_nodes[0] );
2641 edge->_neibors.reserve( nearNodes.size() );
2642 TIDSortedNodeSet::iterator node = nearNodes.begin();
2643 for ( ; node != nearNodes.end(); ++node )
2644 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2645 edge->_neibors.push_back( n2e->second );
2649 data._epsilon = 1e-7;
2650 if ( data._stepSize < 1. )
2651 data._epsilon *= data._stepSize;
2653 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2656 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2657 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2659 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2660 const SMDS_MeshNode* nn[2];
2661 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2663 _EdgesOnShape& eos = data._edgesOnShape[iS];
2664 for ( size_t i = 0; i < eos._edges.size(); ++i )
2666 _LayerEdge* edge = eos._edges[i];
2667 if ( edge->IsOnEdge() )
2669 // get neighbor nodes
2670 bool hasData = ( edge->_2neibors->_edges[0] );
2671 if ( hasData ) // _LayerEdge is a copy of another one
2673 nn[0] = edge->_2neibors->srcNode(0);
2674 nn[1] = edge->_2neibors->srcNode(1);
2676 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2680 // set neighbor _LayerEdge's
2681 for ( int j = 0; j < 2; ++j )
2683 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2684 return error("_LayerEdge not found by src node", data._index);
2685 edge->_2neibors->_edges[j] = n2e->second;
2688 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2691 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2693 _Simplex& s = edge->_simplices[j];
2694 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2695 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2698 // For an _LayerEdge on a degenerated EDGE, copy some data from
2699 // a corresponding _LayerEdge on a VERTEX
2700 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2701 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2703 // Generally we should not get here
2704 if ( eos.ShapeType() != TopAbs_EDGE )
2706 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2707 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2708 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2710 const _LayerEdge* vEdge = n2e->second;
2711 edge->_normal = vEdge->_normal;
2712 edge->_lenFactor = vEdge->_lenFactor;
2713 edge->_cosin = vEdge->_cosin;
2716 } // loop on data._edgesOnShape._edges
2717 } // loop on data._edgesOnShape
2719 // fix _LayerEdge::_2neibors on EDGEs to smooth
2720 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2721 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2722 // if ( !e2c->second.IsNull() )
2724 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2725 // data.Sort2NeiborsOnEdge( eos->_edges );
2732 //================================================================================
2734 * \brief Compute inflation step size by min size of element on a convex surface
2736 //================================================================================
2738 void _ViscousBuilder::limitStepSize( _SolidData& data,
2739 const SMDS_MeshElement* face,
2740 const _LayerEdge* maxCosinEdge )
2743 double minSize = 10 * data._stepSize;
2744 const int nbNodes = face->NbCornerNodes();
2745 for ( int i = 0; i < nbNodes; ++i )
2747 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2748 const SMDS_MeshNode* curN = face->GetNode( i );
2749 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2750 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2752 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2753 if ( dist < minSize )
2754 minSize = dist, iN = i;
2757 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2758 if ( newStep < data._stepSize )
2760 data._stepSize = newStep;
2761 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2762 data._stepSizeNodes[0] = face->GetNode( iN );
2763 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2767 //================================================================================
2769 * \brief Compute inflation step size by min size of element on a convex surface
2771 //================================================================================
2773 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2775 if ( minSize < data._stepSize )
2777 data._stepSize = minSize;
2778 if ( data._stepSizeNodes[0] )
2781 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2782 data._stepSizeCoeff = data._stepSize / dist;
2787 //================================================================================
2789 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2791 //================================================================================
2793 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2795 SMESH_MesherHelper helper( *_mesh );
2797 BRepLProp_SLProps surfProp( 2, 1e-6 );
2798 data._convexFaces.clear();
2800 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2802 _EdgesOnShape& eof = data._edgesOnShape[iS];
2803 if ( eof.ShapeType() != TopAbs_FACE ||
2804 data._ignoreFaceIds.count( eof._shapeID ))
2807 TopoDS_Face F = TopoDS::Face( eof._shape );
2808 const TGeomID faceID = eof._shapeID;
2810 BRepAdaptor_Surface surface( F, false );
2811 surfProp.SetSurface( surface );
2813 _ConvexFace cnvFace;
2815 cnvFace._normalsFixed = false;
2816 cnvFace._isTooCurved = false;
2818 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2819 if ( maxCurvature > 0 )
2821 limitStepSize( data, 0.9 / maxCurvature );
2822 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2824 if ( !cnvFace._isTooCurved ) continue;
2826 _ConvexFace & convFace =
2827 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2829 // skip a closed surface (data._convexFaces is useful anyway)
2830 bool isClosedF = false;
2831 helper.SetSubShape( F );
2832 if ( helper.HasRealSeam() )
2834 // in the closed surface there must be a closed EDGE
2835 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2836 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2840 // limit _LayerEdge::_maxLen on the FACE
2841 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2842 const double minCurvature =
2843 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2844 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2845 if ( id2eos != cnvFace._subIdToEOS.end() )
2847 _EdgesOnShape& eos = * id2eos->second;
2848 for ( size_t i = 0; i < eos._edges.size(); ++i )
2850 _LayerEdge* ledge = eos._edges[ i ];
2851 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2852 surfProp.SetParameters( uv.X(), uv.Y() );
2853 if ( surfProp.IsCurvatureDefined() )
2855 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2856 surfProp.MinCurvature() * oriFactor );
2857 if ( curvature > minCurvature )
2858 ledge->_maxLen = Min( ledge->_maxLen, 1. / curvature );
2865 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2866 // prism distortion.
2867 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2868 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2870 // there are _LayerEdge's on the FACE it-self;
2871 // select _LayerEdge's near EDGEs
2872 _EdgesOnShape& eos = * id2eos->second;
2873 for ( size_t i = 0; i < eos._edges.size(); ++i )
2875 _LayerEdge* ledge = eos._edges[ i ];
2876 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2877 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2879 convFace._simplexTestEdges.push_back( ledge );
2886 // where there are no _LayerEdge's on a _ConvexFace,
2887 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2888 // so that collision of viscous internal faces is not detected by check of
2889 // intersection of _LayerEdge's with the viscous internal faces.
2891 set< const SMDS_MeshNode* > usedNodes;
2893 // look for _LayerEdge's with null _sWOL
2894 id2eos = convFace._subIdToEOS.begin();
2895 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2897 _EdgesOnShape& eos = * id2eos->second;
2898 if ( !eos._sWOL.IsNull() )
2900 for ( size_t i = 0; i < eos._edges.size(); ++i )
2902 _LayerEdge* ledge = eos._edges[ i ];
2903 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2904 if ( !usedNodes.insert( srcNode ).second ) continue;
2906 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2908 usedNodes.insert( ledge->_simplices[i]._nPrev );
2909 usedNodes.insert( ledge->_simplices[i]._nNext );
2911 convFace._simplexTestEdges.push_back( ledge );
2915 } // loop on FACEs of data._solid
2918 //================================================================================
2920 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2922 //================================================================================
2924 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2926 // define allowed thickness
2927 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2930 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2931 // boundary inclined to the shape at a sharp angle
2933 //list< TGeomID > shapesToSmooth;
2934 TopTools_MapOfShape edgesOfSmooFaces;
2936 SMESH_MesherHelper helper( *_mesh );
2939 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2940 data._nbShapesToSmooth = 0;
2942 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2944 _EdgesOnShape& eos = edgesByGeom[iS];
2945 eos._toSmooth = false;
2946 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2949 double tgtThick = eos._hyp.GetTotalThickness();
2950 TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2951 for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2953 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2954 vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2955 if ( eE.empty() ) continue;
2958 for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2959 if ( eE[i]->_cosin > theMinSmoothCosin )
2961 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2962 while ( fIt->more() && !eos._toSmooth )
2964 const SMDS_MeshElement* face = fIt->next();
2965 if ( face->getshapeId() == eos._shapeID &&
2966 getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2968 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2973 if ( eos._toSmooth )
2975 for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2976 edgesOfSmooFaces.Add( eExp.Current() );
2978 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2980 data._nbShapesToSmooth += eos._toSmooth;
2984 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2986 _EdgesOnShape& eos = edgesByGeom[iS];
2987 eos._edgeSmoother = NULL;
2988 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2989 if ( !eos._hyp.ToSmooth() ) continue;
2991 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2992 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2995 double tgtThick = eos._hyp.GetTotalThickness();
2996 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2998 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2999 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3000 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3001 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3002 double angle = eDir.Angle( eV[0]->_normal );
3003 double cosin = Cos( angle );
3004 double cosinAbs = Abs( cosin );
3005 if ( cosinAbs > theMinSmoothCosin )
3007 // always smooth analytic EDGEs
3008 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3009 eos._toSmooth = ! curve.IsNull();
3011 // compare tgtThick with the length of an end segment
3012 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3013 while ( eIt->more() && !eos._toSmooth )
3015 const SMDS_MeshElement* endSeg = eIt->next();
3016 if ( endSeg->getshapeId() == (int) iS )
3019 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3020 eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3023 if ( eos._toSmooth )
3025 eos._edgeSmoother = new _Smoother1D( curve, eos );
3027 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3028 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3032 data._nbShapesToSmooth += eos._toSmooth;
3036 // Reset _cosin if no smooth is allowed by the user
3037 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3039 _EdgesOnShape& eos = edgesByGeom[iS];
3040 if ( eos._edges.empty() ) continue;
3042 if ( !eos._hyp.ToSmooth() )
3043 for ( size_t i = 0; i < eos._edges.size(); ++i )
3044 eos._edges[i]->SetCosin( 0 );
3048 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3050 TopTools_MapOfShape c1VV;
3052 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3054 _EdgesOnShape& eos = edgesByGeom[iS];
3055 if ( eos._edges.empty() ||
3056 eos.ShapeType() != TopAbs_FACE ||
3060 // check EDGEs of a FACE
3061 TopTools_MapOfShape checkedEE, allVV;
3062 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3063 while ( !smQueue.empty() )
3065 SMESH_subMesh* sm = smQueue.front();
3066 smQueue.pop_front();
3067 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3068 while ( smIt->more() )
3071 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3072 allVV.Add( sm->GetSubShape() );
3073 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3074 !checkedEE.Add( sm->GetSubShape() ))
3077 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3078 vector<_LayerEdge*>& eE = eoe->_edges;
3079 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3082 bool isC1 = true; // check continuity along an EDGE
3083 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3084 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3088 // check that mesh faces are C1 as well
3090 gp_XYZ norm1, norm2;
3091 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3092 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3093 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3095 while ( fIt->more() && isC1 )
3096 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3097 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3102 // add the EDGE and an adjacent FACE to _eosC1
3103 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3104 while ( const TopoDS_Shape* face = fIt->next() )
3106 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3107 if ( !eof ) continue; // other solid
3108 if ( !eos.HasC1( eoe ))
3110 eos._eosC1.push_back( eoe );
3111 eoe->_toSmooth = false;
3112 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3114 if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof ))
3116 eos._eosC1.push_back( eof );
3117 eof->_toSmooth = false;
3118 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3119 smQueue.push_back( eof->_subMesh );
3124 if ( eos._eosC1.empty() )
3127 // check VERTEXes of C1 FACEs
3128 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3129 for ( ; vIt.More(); vIt.Next() )
3131 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3132 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3135 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3136 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3137 while ( const TopoDS_Shape* face = fIt->next() )
3139 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3140 if ( !eof ) continue; // other solid
3141 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3147 eos._eosC1.push_back( eov );
3148 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3149 c1VV.Add( eov->_shape );
3153 } // fill _eosC1 of FACEs
3158 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3160 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3162 _EdgesOnShape& eov = edgesByGeom[iS];
3163 if ( eov._edges.empty() ||
3164 eov.ShapeType() != TopAbs_VERTEX ||
3165 c1VV.Contains( eov._shape ))
3167 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3169 // get directions of surrounding EDGEs
3171 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3172 while ( const TopoDS_Shape* e = fIt->next() )
3174 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3175 if ( !eoe ) continue; // other solid
3176 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3177 if ( !Precision::IsInfinite( eDir.X() ))
3178 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3181 // find EDGEs with C1 directions
3182 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3183 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3184 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3186 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3187 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3190 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3191 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3192 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3193 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3194 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3195 dirOfEdges[i].first = 0;
3196 dirOfEdges[j].first = 0;
3199 } // fill _eosC1 of VERTEXes
3206 //================================================================================
3208 * \brief initialize data of _EdgesOnShape
3210 //================================================================================
3212 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3216 if ( !eos._shape.IsNull() ||
3217 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3220 SMESH_MesherHelper helper( *_mesh );
3223 eos._shapeID = sm->GetId();
3224 eos._shape = sm->GetSubShape();
3225 if ( eos.ShapeType() == TopAbs_FACE )
3226 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3227 eos._toSmooth = false;
3231 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3232 data._shrinkShape2Shape.find( eos._shapeID );
3233 if ( s2s != data._shrinkShape2Shape.end() )
3234 eos._sWOL = s2s->second;
3236 eos._isRegularSWOL = true;
3237 if ( eos.SWOLType() == TopAbs_FACE )
3239 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3240 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3241 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3245 if ( data._hyps.size() == 1 )
3247 eos._hyp = data._hyps.back();
3251 // compute average StdMeshers_ViscousLayers parameters
3252 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3253 if ( eos.ShapeType() == TopAbs_FACE )
3255 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3256 eos._hyp = f2hyp->second;
3260 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3261 while ( const TopoDS_Shape* face = fIt->next() )
3263 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3264 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3265 eos._hyp.Add( f2hyp->second );
3271 if ( ! eos._hyp.UseSurfaceNormal() )
3273 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3275 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3276 eos._faceNormals.resize( smDS->NbElements() );
3278 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3279 for ( int iF = 0; eIt->more(); ++iF )
3281 const SMDS_MeshElement* face = eIt->next();
3282 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3283 eos._faceNormals[iF].SetCoord( 0,0,0 );
3286 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3287 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3288 eos._faceNormals[iF].Reverse();
3290 else // find EOS of adjacent FACEs
3292 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3293 while ( const TopoDS_Shape* face = fIt->next() )
3295 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3296 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3297 if ( eos._faceEOS.back()->_shape.IsNull() )
3298 // avoid using uninitialised _shapeID in GetNormal()
3299 eos._faceEOS.back()->_shapeID = faceID;
3305 //================================================================================
3307 * \brief Returns normal of a face
3309 //================================================================================
3311 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3314 const _EdgesOnShape* eos = 0;
3316 if ( face->getshapeId() == _shapeID )
3322 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3323 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3324 eos = _faceEOS[ iF ];
3328 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3330 norm = eos->_faceNormals[ face->getIdInShape() ];
3334 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3335 << " on _shape #" << _shapeID );
3341 //================================================================================
3343 * \brief Set data of _LayerEdge needed for smoothing
3345 //================================================================================
3347 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3349 SMESH_MesherHelper& helper,
3352 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3355 edge._maxLen = Precision::Infinite();
3358 edge._curvature = 0;
3361 // --------------------------
3362 // Compute _normal and _cosin
3363 // --------------------------
3366 edge._lenFactor = 1.;
3367 edge._normal.SetCoord(0,0,0);
3368 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3370 int totalNbFaces = 0;
3372 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3376 const bool onShrinkShape = !eos._sWOL.IsNull();
3377 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3378 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3380 // get geom FACEs the node lies on
3381 //if ( useGeometry )
3383 set<TGeomID> faceIds;
3384 if ( eos.ShapeType() == TopAbs_FACE )
3386 faceIds.insert( eos._shapeID );
3390 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3391 while ( fIt->more() )
3392 faceIds.insert( fIt->next()->getshapeId() );
3394 set<TGeomID>::iterator id = faceIds.begin();
3395 for ( ; id != faceIds.end(); ++id )
3397 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3398 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3400 F = TopoDS::Face( s );
3401 face2Norm[ totalNbFaces ].first = F;
3407 bool fromVonF = false;
3410 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3411 eos.SWOLType() == TopAbs_FACE &&
3414 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3416 if ( eos.SWOLType() == TopAbs_EDGE )
3418 // inflate from VERTEX along EDGE
3419 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3421 else if ( eos.ShapeType() == TopAbs_VERTEX )
3423 // inflate from VERTEX along FACE
3424 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3425 node, helper, normOK, &edge._cosin);
3429 // inflate from EDGE along FACE
3430 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3431 node, helper, normOK);
3434 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3437 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3440 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3442 F = face2Norm[ iF ].first;
3443 geomNorm = getFaceNormal( node, F, helper, normOK );
3444 if ( !normOK ) continue;
3447 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3449 face2Norm[ iF ].second = geomNorm.XYZ();
3450 edge._normal += geomNorm.XYZ();
3452 if ( nbOkNorms == 0 )
3453 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3455 if ( totalNbFaces >= 3 )
3457 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3460 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3462 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3463 edge._normal.SetCoord( 0,0,0 );
3464 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3466 const TopoDS_Face& F = face2Norm[iF].first;
3467 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3468 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3471 face2Norm[ iF ].second = geomNorm.XYZ();
3472 edge._normal += face2Norm[ iF ].second;
3477 else // !useGeometry - get _normal using surrounding mesh faces
3479 edge._normal = getWeigthedNormal( &edge );
3481 // set<TGeomID> faceIds;
3483 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3484 // while ( fIt->more() )
3486 // const SMDS_MeshElement* face = fIt->next();
3487 // if ( eos.GetNormal( face, geomNorm ))
3489 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3490 // continue; // use only one mesh face on FACE
3491 // edge._normal += geomNorm.XYZ();
3498 //if ( eos._hyp.UseSurfaceNormal() )
3500 switch ( eos.ShapeType() )
3507 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3508 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3509 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3510 edge._cosin = Cos( angle );
3513 case TopAbs_VERTEX: {
3516 getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3517 node, helper, normOK, &edge._cosin );
3519 else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3521 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3522 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3523 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3524 edge._cosin = Cos( angle );
3525 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3526 for ( int iF = 1; iF < totalNbFaces; ++iF )
3528 F = face2Norm[ iF ].first;
3529 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3531 double angle = inFaceDir.Angle( edge._normal );
3532 double cosin = Cos( angle );
3533 if ( Abs( cosin ) > Abs( edge._cosin ))
3534 edge._cosin = cosin;
3541 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3545 double normSize = edge._normal.SquareModulus();
3546 if ( normSize < numeric_limits<double>::min() )
3547 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3549 edge._normal /= sqrt( normSize );
3551 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3553 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3554 edge._nodes.resize( 1 );
3555 edge._normal.SetCoord( 0,0,0 );
3559 // Set the rest data
3560 // --------------------
3562 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3564 if ( onShrinkShape )
3566 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3567 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3568 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3570 // set initial position which is parameters on _sWOL in this case
3571 if ( eos.SWOLType() == TopAbs_EDGE )
3573 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3574 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3575 if ( edge._nodes.size() > 1 )
3576 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3578 else // eos.SWOLType() == TopAbs_FACE
3580 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3581 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3582 if ( edge._nodes.size() > 1 )
3583 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3586 if ( edge._nodes.size() > 1 )
3588 // check if an angle between a FACE with layers and SWOL is sharp,
3589 // else the edge should not inflate
3591 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3592 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3593 F = face2Norm[iF].first;
3596 geomNorm = getFaceNormal( node, F, helper, normOK );
3597 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3598 geomNorm.Reverse(); // inside the SOLID
3599 if ( geomNorm * edge._normal < -0.001 )
3601 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3602 edge._nodes.resize( 1 );
3604 else if ( edge._lenFactor > 3 )
3606 edge._lenFactor = 2;
3607 edge.Set( _LayerEdge::RISKY_SWOL );
3614 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3616 if ( eos.ShapeType() == TopAbs_FACE )
3619 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3621 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3622 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3627 // Set neighbor nodes for a _LayerEdge based on EDGE
3629 if ( eos.ShapeType() == TopAbs_EDGE /*||
3630 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3632 edge._2neibors = new _2NearEdges;
3633 // target nodes instead of source ones will be set later
3639 //================================================================================
3641 * \brief Return normal to a FACE at a node
3642 * \param [in] n - node
3643 * \param [in] face - FACE
3644 * \param [in] helper - helper
3645 * \param [out] isOK - true or false
3646 * \param [in] shiftInside - to find normal at a position shifted inside the face
3647 * \return gp_XYZ - normal
3649 //================================================================================
3651 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3652 const TopoDS_Face& face,
3653 SMESH_MesherHelper& helper,
3660 // get a shifted position
3661 gp_Pnt p = SMESH_TNodeXYZ( node );
3662 gp_XYZ shift( 0,0,0 );
3663 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3664 switch ( S.ShapeType() ) {
3667 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3672 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3680 p.Translate( shift * 1e-5 );
3682 TopLoc_Location loc;
3683 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3685 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3687 projector.Perform( p );
3688 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3693 Quantity_Parameter U,V;
3694 projector.LowerDistanceParameters(U,V);
3699 uv = helper.GetNodeUV( face, node, 0, &isOK );
3705 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3707 if ( !shiftInside &&
3708 helper.IsDegenShape( node->getshapeId() ) &&
3709 getFaceNormalAtSingularity( uv, face, helper, normal ))
3712 return normal.XYZ();
3715 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3716 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3718 if ( pointKind == IMPOSSIBLE &&
3719 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3721 // probably NormEstim() failed due to a too high tolerance
3722 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3723 isOK = ( pointKind < IMPOSSIBLE );
3725 if ( pointKind < IMPOSSIBLE )
3727 if ( pointKind != REGULAR &&
3729 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3731 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3732 if ( normShift * normal.XYZ() < 0. )
3738 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3740 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3742 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3743 while ( fIt->more() )
3745 const SMDS_MeshElement* f = fIt->next();
3746 if ( f->getshapeId() == faceID )
3748 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3751 TopoDS_Face ff = face;
3752 ff.Orientation( TopAbs_FORWARD );
3753 if ( helper.IsReversedSubMesh( ff ))
3760 return normal.XYZ();
3763 //================================================================================
3765 * \brief Try to get normal at a singularity of a surface basing on it's nature
3767 //================================================================================
3769 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3770 const TopoDS_Face& face,
3771 SMESH_MesherHelper& helper,
3774 BRepAdaptor_Surface surface( face );
3776 if ( !getRovolutionAxis( surface, axis ))
3779 double f,l, d, du, dv;
3780 f = surface.FirstUParameter();
3781 l = surface.LastUParameter();
3782 d = ( uv.X() - f ) / ( l - f );
3783 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3784 f = surface.FirstVParameter();
3785 l = surface.LastVParameter();
3786 d = ( uv.Y() - f ) / ( l - f );
3787 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3790 gp_Pnt2d testUV = uv;
3791 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3793 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3794 for ( int iLoop = 0; true ; ++iLoop )
3796 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3797 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3804 if ( axis * refDir < 0. )
3812 //================================================================================
3814 * \brief Return a normal at a node weighted with angles taken by faces
3816 //================================================================================
3818 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3820 const SMDS_MeshNode* n = edge->_nodes[0];
3822 gp_XYZ resNorm(0,0,0);
3823 SMESH_TNodeXYZ p0( n ), pP, pN;
3824 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3826 pP.Set( edge->_simplices[i]._nPrev );
3827 pN.Set( edge->_simplices[i]._nNext );
3828 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3829 double l0P = v0P.SquareMagnitude();
3830 double l0N = v0N.SquareMagnitude();
3831 double lPN = vPN.SquareMagnitude();
3832 if ( l0P < std::numeric_limits<double>::min() ||
3833 l0N < std::numeric_limits<double>::min() ||
3834 lPN < std::numeric_limits<double>::min() )
3836 double lNorm = norm.SquareMagnitude();
3837 double sin2 = lNorm / l0P / l0N;
3838 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3840 double weight = sin2 * angle / lPN;
3841 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3847 //================================================================================
3849 * \brief Return a normal at a node by getting a common point of offset planes
3850 * defined by the FACE normals
3852 //================================================================================
3854 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3855 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3859 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3861 gp_XYZ resNorm(0,0,0);
3862 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3863 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3865 for ( int i = 0; i < nbFaces; ++i )
3866 resNorm += f2Normal[i].second;
3870 // prepare _OffsetPlane's
3871 vector< _OffsetPlane > pln( nbFaces );
3872 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3874 pln[i]._faceIndex = i;
3875 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3879 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3880 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3883 // intersect neighboring OffsetPlane's
3884 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3885 while ( const TopoDS_Shape* edge = edgeIt->next() )
3887 int f1 = -1, f2 = -1;
3888 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3889 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3890 (( f1 < 0 ) ? f1 : f2 ) = i;
3893 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3896 // get a common point
3897 gp_XYZ commonPnt( 0, 0, 0 );
3900 for ( int i = 0; i < nbFaces; ++i )
3902 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3903 nbPoints += isPointFound;
3905 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3906 if ( nbPoints == 0 )
3909 commonPnt /= nbPoints;
3910 resNorm = commonPnt - p0;
3914 // choose the best among resNorm and wgtNorm
3915 resNorm.Normalize();
3916 wgtNorm.Normalize();
3917 double resMinDot = std::numeric_limits<double>::max();
3918 double wgtMinDot = std::numeric_limits<double>::max();
3919 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3921 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3922 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3925 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3927 edge->Set( _LayerEdge::MULTI_NORMAL );
3930 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3933 //================================================================================
3935 * \brief Compute line of intersection of 2 planes
3937 //================================================================================
3939 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3940 const TopoDS_Edge& E,
3941 const TopoDS_Vertex& V )
3943 int iNext = bool( _faceIndexNext[0] >= 0 );
3944 _faceIndexNext[ iNext ] = pln._faceIndex;
3946 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3947 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3949 gp_XYZ lineDir = n1 ^ n2;
3951 double x = Abs( lineDir.X() );
3952 double y = Abs( lineDir.Y() );
3953 double z = Abs( lineDir.Z() );
3955 int cooMax; // max coordinate
3957 if (x > z) cooMax = 1;
3961 if (y > z) cooMax = 2;
3966 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3968 // parallel planes - intersection is an offset of the common EDGE
3969 gp_Pnt p = BRep_Tool::Pnt( V );
3970 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3971 lineDir = getEdgeDir( E, V );
3975 // the constants in the 2 plane equations
3976 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
3977 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3982 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3983 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3986 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3988 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3991 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3992 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3996 gp_Lin& line = _lines[ iNext ];
3997 line.SetDirection( lineDir );
3998 line.SetLocation ( linePos );
4000 _isLineOK[ iNext ] = true;
4003 iNext = bool( pln._faceIndexNext[0] >= 0 );
4004 pln._lines [ iNext ] = line;
4005 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4006 pln._isLineOK [ iNext ] = true;
4009 //================================================================================
4011 * \brief Computes intersection point of two _lines
4013 //================================================================================
4015 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4016 const TopoDS_Vertex & V) const
4021 if ( NbLines() == 2 )
4023 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4024 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4025 if ( Abs( dot01 ) > 0.05 )
4027 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4028 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4029 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4034 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4035 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4036 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4037 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4038 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4046 //================================================================================
4048 * \brief Find 2 neigbor nodes of a node on EDGE
4050 //================================================================================
4052 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4053 const SMDS_MeshNode*& n1,
4054 const SMDS_MeshNode*& n2,
4058 const SMDS_MeshNode* node = edge->_nodes[0];
4059 const int shapeInd = eos._shapeID;
4060 SMESHDS_SubMesh* edgeSM = 0;
4061 if ( eos.ShapeType() == TopAbs_EDGE )
4063 edgeSM = eos._subMesh->GetSubMeshDS();
4064 if ( !edgeSM || edgeSM->NbElements() == 0 )
4065 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4069 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4070 while ( eIt->more() && !n2 )
4072 const SMDS_MeshElement* e = eIt->next();
4073 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4074 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4077 if (!edgeSM->Contains(e)) continue;
4081 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4082 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4084 ( iN++ ? n2 : n1 ) = nNeibor;
4087 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4091 //================================================================================
4093 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4095 //================================================================================
4097 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4098 const SMDS_MeshNode* n2,
4099 const _EdgesOnShape& eos,
4100 SMESH_MesherHelper& helper)
4102 if ( eos.ShapeType() != TopAbs_EDGE )
4105 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4106 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4107 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4111 double sumLen = vec1.Modulus() + vec2.Modulus();
4112 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4113 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4114 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4115 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4116 if ( _curvature ) delete _curvature;
4117 _curvature = _Curvature::New( avgNormProj, avgLen );
4118 // if ( _curvature )
4119 // debugMsg( _nodes[0]->GetID()
4120 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4121 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4122 // << _curvature->lenDelta(0) );
4126 if ( eos._sWOL.IsNull() )
4128 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4129 // if ( SMESH_Algo::isDegenerated( E ))
4131 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4132 gp_XYZ plnNorm = dirE ^ _normal;
4133 double proj0 = plnNorm * vec1;
4134 double proj1 = plnNorm * vec2;
4135 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4137 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4138 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4143 //================================================================================
4145 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4146 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4148 //================================================================================
4150 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4152 SMESH_MesherHelper& helper )
4154 _nodes = other._nodes;
4155 _normal = other._normal;
4157 _lenFactor = other._lenFactor;
4158 _cosin = other._cosin;
4159 _2neibors = other._2neibors;
4160 _curvature = 0; std::swap( _curvature, other._curvature );
4161 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4163 gp_XYZ lastPos( 0,0,0 );
4164 if ( eos.SWOLType() == TopAbs_EDGE )
4166 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4167 _pos.push_back( gp_XYZ( u, 0, 0));
4169 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4174 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4175 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4177 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4178 lastPos.SetX( uv.X() );
4179 lastPos.SetY( uv.Y() );
4184 //================================================================================
4186 * \brief Set _cosin and _lenFactor
4188 //================================================================================
4190 void _LayerEdge::SetCosin( double cosin )
4193 cosin = Abs( _cosin );
4194 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4195 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4198 //================================================================================
4200 * \brief Check if another _LayerEdge is a neighbor on EDGE
4202 //================================================================================
4204 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4206 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4207 ( edge->_2neibors && edge->_2neibors->include( this )));
4210 //================================================================================
4212 * \brief Fills a vector<_Simplex >
4214 //================================================================================
4216 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4217 vector<_Simplex>& simplices,
4218 const set<TGeomID>& ingnoreShapes,
4219 const _SolidData* dataToCheckOri,
4223 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4224 while ( fIt->more() )
4226 const SMDS_MeshElement* f = fIt->next();
4227 const TGeomID shapeInd = f->getshapeId();
4228 if ( ingnoreShapes.count( shapeInd )) continue;
4229 const int nbNodes = f->NbCornerNodes();
4230 const int srcInd = f->GetNodeIndex( node );
4231 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4232 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4233 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4234 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4235 std::swap( nPrev, nNext );
4236 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4240 SortSimplices( simplices );
4243 //================================================================================
4245 * \brief Set neighbor simplices side by side
4247 //================================================================================
4249 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4251 vector<_Simplex> sortedSimplices( simplices.size() );
4252 sortedSimplices[0] = simplices[0];
4254 for ( size_t i = 1; i < simplices.size(); ++i )
4256 for ( size_t j = 1; j < simplices.size(); ++j )
4257 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4259 sortedSimplices[i] = simplices[j];
4264 if ( nbFound == simplices.size() - 1 )
4265 simplices.swap( sortedSimplices );
4268 //================================================================================
4270 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4272 //================================================================================
4274 void _ViscousBuilder::makeGroupOfLE()
4277 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4279 if ( _sdVec[i]._n2eMap.empty() ) continue;
4281 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4282 TNode2Edge::iterator n2e;
4283 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4285 _LayerEdge* le = n2e->second;
4286 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4287 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4288 // << ", " << le->_nodes[iN]->GetID() <<"])");
4290 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4291 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4296 dumpFunction( SMESH_Comment("makeNormals") << i );
4297 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4299 _LayerEdge* edge = n2e->second;
4300 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4301 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4302 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4303 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4307 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4308 dumpCmd( "faceId1 = mesh.NbElements()" );
4309 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4310 for ( ; fExp.More(); fExp.Next() )
4312 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4314 if ( sm->NbElements() == 0 ) continue;
4315 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4316 while ( fIt->more())
4318 const SMDS_MeshElement* e = fIt->next();
4319 SMESH_Comment cmd("mesh.AddFace([");
4320 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4321 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4326 dumpCmd( "faceId2 = mesh.NbElements()" );
4327 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4328 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4329 << "'%s-%s' % (faceId1+1, faceId2))");
4335 //================================================================================
4337 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4339 //================================================================================
4341 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4343 data._geomSize = Precision::Infinite();
4344 double intersecDist;
4345 const SMDS_MeshElement* face;
4346 SMESH_MesherHelper helper( *_mesh );
4348 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4349 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4350 data._proxyMesh->GetFaces( data._solid )));
4352 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4354 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4355 if ( eos._edges.empty() )
4357 // get neighbor faces, intersection with which should not be considered since
4358 // collisions are avoided by means of smoothing
4359 set< TGeomID > neighborFaces;
4360 if ( eos._hyp.ToSmooth() )
4362 SMESH_subMeshIteratorPtr subIt =
4363 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4364 while ( subIt->more() )
4366 SMESH_subMesh* sm = subIt->next();
4367 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4368 while ( const TopoDS_Shape* face = fIt->next() )
4369 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4372 // find intersections
4373 double thinkness = eos._hyp.GetTotalThickness();
4374 for ( size_t i = 0; i < eos._edges.size(); ++i )
4376 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4377 eos._edges[i]->_maxLen = thinkness;
4378 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4379 if ( intersecDist > 0 && face )
4381 data._geomSize = Min( data._geomSize, intersecDist );
4382 if ( !neighborFaces.count( face->getshapeId() ))
4383 eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4388 data._maxThickness = 0;
4389 data._minThickness = 1e100;
4390 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4391 for ( ; hyp != data._hyps.end(); ++hyp )
4393 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4394 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4397 // Limit inflation step size by geometry size found by intersecting
4398 // normals of _LayerEdge's with mesh faces
4399 if ( data._stepSize > 0.3 * data._geomSize )
4400 limitStepSize( data, 0.3 * data._geomSize );
4402 if ( data._stepSize > data._minThickness )
4403 limitStepSize( data, data._minThickness );
4406 // -------------------------------------------------------------------------
4407 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4408 // so no need in detecting intersection at each inflation step
4409 // -------------------------------------------------------------------------
4411 int nbSteps = data._maxThickness / data._stepSize;
4412 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4415 vector< const SMDS_MeshElement* > closeFaces;
4418 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4420 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4421 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4424 for ( size_t i = 0; i < eos.size(); ++i )
4426 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4427 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4429 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4431 bool toIgnore = true;
4432 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4433 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4434 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4436 // check if a _LayerEdge will inflate in a direction opposite to a direction
4437 // toward a close face
4438 bool allBehind = true;
4439 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4441 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4442 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4444 toIgnore = allBehind;
4448 if ( toIgnore ) // no need to detect intersection
4450 eos[i]->Set( _LayerEdge::INTERSECTED );
4456 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4461 //================================================================================
4463 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4465 //================================================================================
4467 bool _ViscousBuilder::inflate(_SolidData& data)
4469 SMESH_MesherHelper helper( *_mesh );
4471 const double tgtThick = data._maxThickness;
4473 if ( data._stepSize < 1. )
4474 data._epsilon = data._stepSize * 1e-7;
4476 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4479 findCollisionEdges( data, helper );
4481 limitMaxLenByCurvature( data, helper );
4485 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4486 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4487 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4488 data._edgesOnShape[i]._edges.size() > 0 &&
4489 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4491 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4492 data._edgesOnShape[i]._edges[0]->Block( data );
4495 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4497 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4498 int nbSteps = 0, nbRepeats = 0;
4499 while ( avgThick < 0.99 )
4501 // new target length
4502 double prevThick = curThick;
4503 curThick += data._stepSize;
4504 if ( curThick > tgtThick )
4506 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4510 double stepSize = curThick - prevThick;
4511 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4513 // Elongate _LayerEdge's
4514 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4515 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4517 _EdgesOnShape& eos = data._edgesOnShape[iS];
4518 if ( eos._edges.empty() ) continue;
4520 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4521 for ( size_t i = 0; i < eos._edges.size(); ++i )
4523 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4528 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4531 // Improve and check quality
4532 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4536 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4537 debugMsg("NOT INVALIDATED STEP!");
4538 return error("Smoothing failed", data._index);
4540 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4541 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4543 _EdgesOnShape& eos = data._edgesOnShape[iS];
4544 for ( size_t i = 0; i < eos._edges.size(); ++i )
4545 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4549 break; // no more inflating possible
4553 // Evaluate achieved thickness
4555 int nbActiveEdges = 0;
4556 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4558 _EdgesOnShape& eos = data._edgesOnShape[iS];
4559 if ( eos._edges.empty() ) continue;
4561 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4562 for ( size_t i = 0; i < eos._edges.size(); ++i )
4564 if ( eos._edges[i]->_nodes.size() > 1 )
4565 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4567 avgThick += shapeTgtThick;
4568 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4571 avgThick /= data._n2eMap.size();
4572 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4574 #ifdef BLOCK_INFLATION
4575 if ( nbActiveEdges == 0 )
4577 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4581 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4583 debugMsg( "-- Stop inflation since "
4584 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4585 << tgtThick * avgThick << " ) * " << safeFactor );
4591 limitStepSize( data, 0.25 * distToIntersection );
4592 if ( data._stepSizeNodes[0] )
4593 data._stepSize = data._stepSizeCoeff *
4594 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4596 } // while ( avgThick < 0.99 )
4599 return error("failed at the very first inflation step", data._index);
4601 if ( avgThick < 0.99 )
4603 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4605 data._proxyMesh->_warning.reset
4606 ( new SMESH_ComputeError (COMPERR_WARNING,
4607 SMESH_Comment("Thickness ") << tgtThick <<
4608 " of viscous layers not reached,"
4609 " average reached thickness is " << avgThick*tgtThick));
4613 // Restore position of src nodes moved by inflation on _noShrinkShapes
4614 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4615 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4617 _EdgesOnShape& eos = data._edgesOnShape[iS];
4618 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4619 for ( size_t i = 0; i < eos._edges.size(); ++i )
4621 restoreNoShrink( *eos._edges[ i ] );
4626 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4629 //================================================================================
4631 * \brief Improve quality of layer inner surface and check intersection
4633 //================================================================================
4635 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4637 double & distToIntersection)
4639 if ( data._nbShapesToSmooth == 0 )
4640 return true; // no shapes needing smoothing
4642 bool moved, improved;
4644 vector< _LayerEdge* > movedEdges, badEdges;
4645 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4646 vector< bool > isConcaveFace;
4648 SMESH_MesherHelper helper(*_mesh);
4649 Handle(ShapeAnalysis_Surface) surface;
4652 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4654 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4656 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4658 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4659 if ( !eos._toSmooth ||
4660 eos.ShapeType() != shapeType ||
4661 eos._edges.empty() )
4664 // already smoothed?
4665 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4666 // if ( !toSmooth ) continue;
4668 if ( !eos._hyp.ToSmooth() )
4670 // smooth disabled by the user; check validy only
4671 if ( !isFace ) continue;
4673 for ( size_t i = 0; i < eos._edges.size(); ++i )
4675 _LayerEdge* edge = eos._edges[i];
4676 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4677 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4679 // debugMsg( "-- Stop inflation. Bad simplex ("
4680 // << " "<< edge->_nodes[0]->GetID()
4681 // << " "<< edge->_nodes.back()->GetID()
4682 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4683 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4685 badEdges.push_back( edge );
4688 if ( !badEdges.empty() )
4692 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4696 continue; // goto the next EDGE or FACE
4700 if ( eos.SWOLType() == TopAbs_FACE )
4702 if ( !F.IsSame( eos._sWOL )) {
4703 F = TopoDS::Face( eos._sWOL );
4704 helper.SetSubShape( F );
4705 surface = helper.GetSurface( F );
4710 F.Nullify(); surface.Nullify();
4712 const TGeomID sInd = eos._shapeID;
4714 // perform smoothing
4716 if ( eos.ShapeType() == TopAbs_EDGE )
4718 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4720 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4722 // smooth on EDGE's (normally we should not get here)
4726 for ( size_t i = 0; i < eos._edges.size(); ++i )
4728 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4730 dumpCmd( SMESH_Comment("# end step ")<<step);
4732 while ( moved && step++ < 5 );
4737 else // smooth on FACE
4740 eosC1.push_back( & eos );
4741 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4744 isConcaveFace.resize( eosC1.size() );
4745 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4747 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4748 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4749 for ( size_t i = 0; i < edges.size(); ++i )
4750 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4751 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4752 movedEdges.push_back( edges[i] );
4754 makeOffsetSurface( *eosC1[ iEOS ], helper );
4757 int step = 0, stepLimit = 5, nbBad = 0;
4758 while (( ++step <= stepLimit ) || improved )
4760 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4761 <<"_InfStep"<<infStep<<"_"<<step); // debug
4762 int oldBadNb = nbBad;
4765 #ifdef INCREMENTAL_SMOOTH
4766 bool findBest = false; // ( step == stepLimit );
4767 for ( size_t i = 0; i < movedEdges.size(); ++i )
4769 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4770 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4771 badEdges.push_back( movedEdges[i] );
4774 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4775 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4777 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4778 for ( size_t i = 0; i < edges.size(); ++i )
4780 edges[i]->Unset( _LayerEdge::SMOOTHED );
4781 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4782 badEdges.push_back( eos._edges[i] );
4786 nbBad = badEdges.size();
4789 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4791 if ( !badEdges.empty() && step >= stepLimit / 2 )
4793 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4796 // resolve hard smoothing situation around concave VERTEXes
4797 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4799 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4800 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4801 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4804 // look for the best smooth of _LayerEdge's neighboring badEdges
4806 for ( size_t i = 0; i < badEdges.size(); ++i )
4808 _LayerEdge* ledge = badEdges[i];
4809 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4811 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4812 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4814 ledge->Unset( _LayerEdge::SMOOTHED );
4815 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4817 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4820 if ( nbBad == oldBadNb &&
4822 step < stepLimit ) // smooth w/o chech of validity
4825 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4826 <<"_InfStep"<<infStep<<"_"<<step); // debug
4827 for ( size_t i = 0; i < movedEdges.size(); ++i )
4829 movedEdges[i]->SmoothWoCheck();
4831 if ( stepLimit < 9 )
4835 improved = ( nbBad < oldBadNb );
4839 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4840 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4842 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4845 } // smoothing steps
4847 // project -- to prevent intersections or fix bad simplices
4848 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4850 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4851 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4854 //if ( !badEdges.empty() )
4857 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4859 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4861 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4863 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4864 edge->CheckNeiborsOnBoundary( & badEdges );
4865 if (( nbBad > 0 ) ||
4866 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4868 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4869 gp_XYZ prevXYZ = edge->PrevCheckPos();
4870 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4871 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4873 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4874 << " "<< tgtXYZ._node->GetID()
4875 << " "<< edge->_simplices[j]._nPrev->GetID()
4876 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4877 badEdges.push_back( edge );
4884 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4885 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4891 } // // smooth on FACE's
4893 } // smooth on [ EDGEs, FACEs ]
4895 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4897 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4899 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4900 if ( eos.ShapeType() == TopAbs_FACE ||
4901 eos._edges.empty() ||
4902 !eos._sWOL.IsNull() )
4906 for ( size_t i = 0; i < eos._edges.size(); ++i )
4908 _LayerEdge* edge = eos._edges[i];
4909 if ( edge->_nodes.size() < 2 ) continue;
4910 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4911 SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
4912 //gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4913 //const gp_XYZ& prevXYZ = edge->PrevPos();
4914 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4915 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4917 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4918 << " "<< tgtXYZ._node->GetID()
4919 << " "<< edge->_simplices[j]._nPrev->GetID()
4920 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4921 badEdges.push_back( edge );
4926 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4928 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4934 // Check if the last segments of _LayerEdge intersects 2D elements;
4935 // checked elements are either temporary faces or faces on surfaces w/o the layers
4937 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4938 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4939 data._proxyMesh->GetFaces( data._solid )) );
4941 #ifdef BLOCK_INFLATION
4942 const bool toBlockInfaltion = true;
4944 const bool toBlockInfaltion = false;
4946 distToIntersection = Precision::Infinite();
4948 const SMDS_MeshElement* intFace = 0;
4949 const SMDS_MeshElement* closestFace = 0;
4951 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4953 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4954 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4956 for ( size_t i = 0; i < eos._edges.size(); ++i )
4958 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4959 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4961 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4964 // commented due to "Illegal hash-positionPosition" error in NETGEN
4965 // on Debian60 on viscous_layers_01/B2 case
4966 // Collision; try to deflate _LayerEdge's causing it
4967 // badEdges.clear();
4968 // badEdges.push_back( eos._edges[i] );
4969 // eosC1[0] = & eos;
4970 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4974 // badEdges.clear();
4975 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4977 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4979 // const SMDS_MeshElement* srcFace =
4980 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4981 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4982 // while ( nIt->more() )
4984 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4985 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4986 // if ( n2e != data._n2eMap.end() )
4987 // badEdges.push_back( n2e->second );
4990 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4995 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5002 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5007 const bool isShorterDist = ( distToIntersection > dist );
5008 if ( toBlockInfaltion || isShorterDist )
5010 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5011 // lying on this _ConvexFace
5012 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5013 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5016 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5017 // ( avoid limiting the thickness on the case of issue 22576)
5018 if ( intFace->getshapeId() == eos._shapeID )
5021 // ignore intersection with intFace of an adjacent FACE
5024 bool toIgnore = false;
5025 if ( eos._toSmooth )
5027 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5028 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5030 TopExp_Explorer sub( eos._shape,
5031 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5032 for ( ; !toIgnore && sub.More(); sub.Next() )
5033 // is adjacent - has a common EDGE or VERTEX
5034 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5036 if ( toIgnore ) // check angle between normals
5039 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5040 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5044 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5046 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5048 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5049 toIgnore = ( nInd >= 0 );
5056 // intersection not ignored
5058 if ( toBlockInfaltion &&
5059 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5061 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5062 eos._edges[i]->Block( data ); // not to inflate
5064 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5066 // block _LayerEdge's, on top of which intFace is
5067 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5069 const SMDS_MeshElement* srcFace =
5070 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5071 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5072 while ( nIt->more() )
5074 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5075 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5076 if ( n2e != data._n2eMap.end() )
5077 n2e->second->Block( data );
5083 if ( isShorterDist )
5085 distToIntersection = dist;
5087 closestFace = intFace;
5090 } // if ( toBlockInfaltion || isShorterDist )
5091 } // loop on eos._edges
5092 } // loop on data._edgesOnShape
5094 if ( closestFace && le )
5097 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5098 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5099 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5100 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5101 << ") distance = " << distToIntersection<< endl;
5108 //================================================================================
5110 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5111 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5112 * \return int - resulting nb of bad _LayerEdge's
5114 //================================================================================
5116 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5117 SMESH_MesherHelper& helper,
5118 vector< _LayerEdge* >& badSmooEdges,
5119 vector< _EdgesOnShape* >& eosC1,
5122 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5124 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5127 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5128 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5129 ADDED = _LayerEdge::UNUSED_FLAG * 4
5131 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5134 bool haveInvalidated = true;
5135 while ( haveInvalidated )
5137 haveInvalidated = false;
5138 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5140 _LayerEdge* edge = badSmooEdges[i];
5141 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5143 bool invalidated = false;
5144 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5146 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5147 edge->Block( data );
5148 edge->Set( INVALIDATED );
5149 edge->Unset( TO_INVALIDATE );
5151 haveInvalidated = true;
5154 // look for _LayerEdge's of bad _simplices
5156 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5157 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5158 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5159 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5161 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5162 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5166 _LayerEdge* ee[2] = { 0,0 };
5167 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5168 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5169 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5171 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5172 while ( maxNbSteps > edge->NbSteps() && isBad )
5175 for ( int iE = 0; iE < 2; ++iE )
5177 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5178 ee[ iE ]->NbSteps() > 1 )
5180 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5181 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5182 ee[ iE ]->Block( data );
5183 ee[ iE ]->Set( INVALIDATED );
5184 haveInvalidated = true;
5187 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5188 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5192 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5193 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5194 ee[0]->Set( ADDED );
5195 ee[1]->Set( ADDED );
5198 ee[0]->Set( TO_INVALIDATE );
5199 ee[1]->Set( TO_INVALIDATE );
5203 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5205 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5206 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5207 edge->Block( data );
5208 edge->Set( INVALIDATED );
5209 edge->Unset( TO_INVALIDATE );
5210 haveInvalidated = true;
5212 } // loop on badSmooEdges
5213 } // while ( haveInvalidated )
5215 // re-smooth on analytical EDGEs
5216 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5218 _LayerEdge* edge = badSmooEdges[i];
5219 if ( !edge->Is( INVALIDATED )) continue;
5221 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5222 if ( eos->ShapeType() == TopAbs_VERTEX )
5224 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5225 while ( const TopoDS_Shape* e = eIt->next() )
5226 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5227 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5229 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5230 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5231 // F = TopoDS::Face( eoe->_sWOL );
5232 // surface = helper.GetSurface( F );
5234 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5235 eoe->_edgeSmoother->_anaCurve.Nullify();
5241 // check result of invalidation
5244 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5246 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5248 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5249 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5250 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5251 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5252 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5253 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5256 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5257 << " "<< tgtXYZ._node->GetID()
5258 << " "<< edge->_simplices[j]._nPrev->GetID()
5259 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5268 //================================================================================
5270 * \brief Create an offset surface
5272 //================================================================================
5274 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5276 if ( eos._offsetSurf.IsNull() ||
5277 eos._edgeForOffset == 0 ||
5278 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5281 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5284 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5285 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5286 double offset = baseSurface->Gap();
5288 eos._offsetSurf.Nullify();
5292 BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5293 if ( !offsetMaker.IsDone() ) return;
5295 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5296 if ( !fExp.More() ) return;
5298 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5299 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5300 if ( surf.IsNull() ) return;
5302 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5304 catch ( Standard_Failure )
5309 //================================================================================
5311 * \brief Put nodes of a curved FACE to its offset surface
5313 //================================================================================
5315 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5317 vector< _EdgesOnShape* >& eosC1,
5321 _EdgesOnShape * eof = & eos;
5322 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5325 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5327 if ( eosC1[i]->_offsetSurf.IsNull() ||
5328 eosC1[i]->ShapeType() != TopAbs_FACE ||
5329 eosC1[i]->_edgeForOffset == 0 ||
5330 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5332 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5337 eof->_offsetSurf.IsNull() ||
5338 eof->ShapeType() != TopAbs_FACE ||
5339 eof->_edgeForOffset == 0 ||
5340 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5343 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5344 for ( size_t i = 0; i < eos._edges.size(); ++i )
5346 _LayerEdge* edge = eos._edges[i];
5347 edge->Unset( _LayerEdge::MARKED );
5348 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5350 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5352 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5355 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5358 int nbBlockedAround = 0;
5359 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5360 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5361 if ( nbBlockedAround > 1 )
5364 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5365 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5366 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5367 edge->_curvature->_uv = uv;
5368 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5370 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5371 gp_XYZ prevP = edge->PrevCheckPos();
5374 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5376 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5380 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5381 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5382 edge->_pos.back() = newP;
5384 edge->Set( _LayerEdge::MARKED );
5385 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5387 edge->_normal = ( newP - prevP ).Normalized();
5395 // dumpMove() for debug
5397 for ( ; i < eos._edges.size(); ++i )
5398 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5400 if ( i < eos._edges.size() )
5402 dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5403 << "_InfStep" << infStep << "_" << smooStep );
5404 for ( ; i < eos._edges.size(); ++i )
5406 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5407 dumpMove( eos._edges[i]->_nodes.back() );
5413 _ConvexFace* cnvFace;
5414 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5415 eos.ShapeType() == TopAbs_FACE &&
5416 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5417 !cnvFace->_normalsFixedOnBorders )
5419 // put on the surface nodes built on FACE boundaries
5420 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5421 while ( smIt->more() )
5423 SMESH_subMesh* sm = smIt->next();
5424 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5425 if ( !subEOS->_sWOL.IsNull() ) continue;
5426 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5428 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5430 cnvFace->_normalsFixedOnBorders = true;
5434 //================================================================================
5436 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5437 * _LayerEdge's to be in a consequent order
5439 //================================================================================
5441 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5443 SMESH_MesherHelper& helper)
5445 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5447 TopLoc_Location loc; double f,l;
5449 Handle(Geom_Line) line;
5450 Handle(Geom_Circle) circle;
5451 bool isLine, isCirc;
5452 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5454 // check if the EDGE is a line
5455 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5456 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5457 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5459 line = Handle(Geom_Line)::DownCast( curve );
5460 circle = Handle(Geom_Circle)::DownCast( curve );
5461 isLine = (!line.IsNull());
5462 isCirc = (!circle.IsNull());
5464 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5466 isLine = SMESH_Algo::IsStraight( E );
5469 line = new Geom_Line( gp::OX() ); // only type does matter
5471 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5476 else //////////////////////////////////////////////////////////////////////// 2D case
5478 if ( !eos._isRegularSWOL ) // 23190
5481 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5483 // check if the EDGE is a line
5484 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5485 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5486 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5488 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5489 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5490 isLine = (!line2d.IsNull());
5491 isCirc = (!circle2d.IsNull());
5493 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5496 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5497 while ( nIt->more() )
5498 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5499 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5501 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5502 for ( int i = 0; i < 2 && !isLine; ++i )
5503 isLine = ( size.Coord( i+1 ) <= lineTol );
5505 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5511 line = new Geom_Line( gp::OX() ); // only type does matter
5515 gp_Pnt2d p = circle2d->Location();
5516 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5517 circle = new Geom_Circle( ax, 1.); // only center position does matter
5526 return Handle(Geom_Curve)();
5529 //================================================================================
5531 * \brief Smooth edges on EDGE
5533 //================================================================================
5535 bool _Smoother1D::Perform(_SolidData& data,
5536 Handle(ShapeAnalysis_Surface)& surface,
5537 const TopoDS_Face& F,
5538 SMESH_MesherHelper& helper )
5540 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5543 findEdgesToSmooth();
5545 return smoothAnalyticEdge( data, surface, F, helper );
5547 return smoothComplexEdge ( data, surface, F, helper );
5550 //================================================================================
5552 * \brief Find edges to smooth
5554 //================================================================================
5556 void _Smoother1D::findEdgesToSmooth()
5558 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5559 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5560 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5561 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5563 _eToSmooth[0].first = _eToSmooth[0].second = 0;
5565 for ( size_t i = 0; i < _eos.size(); ++i )
5567 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5569 if ( needSmoothing( _leOnV[0]._cosin, _eos[i]->_len, _curveLen * _leParams[i] ) ||
5571 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5575 _eToSmooth[0].second = i+1;
5578 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5580 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5582 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5584 if ( needSmoothing( _leOnV[1]._cosin, _eos[i]->_len, _curveLen * ( 1.-_leParams[i] )) ||
5586 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5590 _eToSmooth[1].first = i;
5594 //================================================================================
5596 * \brief Check if iE-th _LayerEdge needs smoothing
5598 //================================================================================
5600 bool _Smoother1D::isToSmooth( int iE )
5602 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5603 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5604 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5605 gp_XYZ seg0 = pi - p0;
5606 gp_XYZ seg1 = p1 - pi;
5607 gp_XYZ tangent = seg0 + seg1;
5608 double tangentLen = tangent.Modulus();
5609 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5610 if ( tangentLen < std::numeric_limits<double>::min() )
5612 tangent /= tangentLen;
5614 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5616 _LayerEdge* ne = _eos[iE]->_neibors[i];
5617 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5618 ne->_nodes.size() < 2 ||
5619 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5621 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5622 double proj = edgeVec * tangent;
5623 if ( needSmoothing( 1., proj, segMinLen ))
5629 //================================================================================
5631 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5633 //================================================================================
5635 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5636 Handle(ShapeAnalysis_Surface)& surface,
5637 const TopoDS_Face& F,
5638 SMESH_MesherHelper& helper)
5640 if ( !isAnalytic() ) return false;
5642 size_t iFrom = 0, iTo = _eos._edges.size();
5644 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5646 if ( F.IsNull() ) // 3D
5648 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5649 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5650 //const gp_XYZ lineDir = pSrc1 - pSrc0;
5651 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5652 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5653 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5654 // vLE0->Is( _LayerEdge::BLOCKED ) ||
5655 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5656 // vLE1->Is( _LayerEdge::BLOCKED ));
5657 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5659 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5660 if ( iFrom >= iTo ) continue;
5661 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5662 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5663 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5664 double param1 = _leParams[ iTo ];
5665 for ( size_t i = iFrom; i < iTo; ++i )
5667 _LayerEdge* edge = _eos[i];
5668 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5669 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5670 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
5672 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5674 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5675 // double shift = ( lineDir * ( newPos - pSrc0 ) -
5676 // lineDir * ( curPos - pSrc0 ));
5677 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5679 if ( edge->Is( _LayerEdge::BLOCKED ))
5681 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5682 double curThick = pSrc.SquareDistance( tgtNode );
5683 double newThink = ( pSrc - newPos ).SquareModulus();
5684 if ( newThink > curThick )
5687 edge->_pos.back() = newPos;
5688 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5689 dumpMove( tgtNode );
5695 _LayerEdge* eV0 = getLEdgeOnV( 0 );
5696 _LayerEdge* eV1 = getLEdgeOnV( 1 );
5697 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5698 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5699 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5701 int iPeriodic = helper.GetPeriodicIndex();
5702 if ( iPeriodic == 1 || iPeriodic == 2 )
5704 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5705 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5706 std::swap( uvV0, uvV1 );
5709 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5711 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5712 if ( iFrom >= iTo ) continue;
5713 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5714 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5715 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5716 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5717 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5718 double param1 = _leParams[ iTo ];
5719 gp_XY rangeUV = uv1 - uv0;
5720 for ( size_t i = iFrom; i < iTo; ++i )
5722 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5723 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5724 gp_XY newUV = uv0 + param * rangeUV;
5726 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5727 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5728 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5729 dumpMove( tgtNode );
5731 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5732 pos->SetUParameter( newUV.X() );
5733 pos->SetVParameter( newUV.Y() );
5735 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5737 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5739 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5740 if ( _eos[i]->_pos.size() > 2 )
5742 // modify previous positions to make _LayerEdge less sharply bent
5743 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5744 const gp_XYZ uvShift = newUV0 - uvVec.back();
5745 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5746 int iPrev = uvVec.size() - 2;
5749 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5750 uvVec[ iPrev ] += uvShift * r;
5755 _eos[i]->_pos.back() = newUV0;
5762 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5764 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5765 gp_Pnt center3D = circle->Location();
5767 if ( F.IsNull() ) // 3D
5769 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5770 return true; // closed EDGE - nothing to do
5772 // circle is a real curve of EDGE
5773 gp_Circ circ = circle->Circ();
5775 // new center is shifted along its axis
5776 const gp_Dir& axis = circ.Axis().Direction();
5777 _LayerEdge* e0 = getLEdgeOnV(0);
5778 _LayerEdge* e1 = getLEdgeOnV(1);
5779 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5780 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5781 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5782 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5783 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5785 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5787 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5788 gp_Circ newCirc( newAxis, newRadius );
5789 gp_Vec vecC1 ( newCenter, p1 );
5791 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5795 for ( size_t i = 0; i < _eos.size(); ++i )
5797 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5798 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5799 double u = uLast * _leParams[i];
5800 gp_Pnt p = ElCLib::Value( u, newCirc );
5801 _eos._edges[i]->_pos.back() = p.XYZ();
5803 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5804 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5805 dumpMove( tgtNode );
5811 const gp_XY center( center3D.X(), center3D.Y() );
5813 _LayerEdge* e0 = getLEdgeOnV(0);
5814 _LayerEdge* eM = _eos._edges[ 0 ];
5815 _LayerEdge* e1 = getLEdgeOnV(1);
5816 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5817 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5818 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5819 gp_Vec2d vec0( center, uv0 );
5820 gp_Vec2d vecM( center, uvM );
5821 gp_Vec2d vec1( center, uv1 );
5822 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5823 double uMidl = vec0.Angle( vecM );
5824 if ( uLast * uMidl <= 0. )
5825 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5826 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5828 gp_Ax2d axis( center, vec0 );
5829 gp_Circ2d circ( axis, radius );
5830 for ( size_t i = 0; i < _eos.size(); ++i )
5832 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5833 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5834 double newU = uLast * _leParams[i];
5835 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5836 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5838 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5839 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5840 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5841 dumpMove( tgtNode );
5843 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5844 pos->SetUParameter( newUV.X() );
5845 pos->SetVParameter( newUV.Y() );
5847 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5856 //================================================================================
5858 * \brief smooth _LayerEdge's on a an EDGE
5860 //================================================================================
5862 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5863 Handle(ShapeAnalysis_Surface)& surface,
5864 const TopoDS_Face& F,
5865 SMESH_MesherHelper& helper)
5867 if ( _offPoints.empty() )
5870 // ----------------------------------------------
5871 // move _offPoints along normals of _LayerEdge's
5872 // ----------------------------------------------
5874 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5875 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5876 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5877 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5878 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5879 _leOnV[0]._len = e[0]->_len;
5880 _leOnV[1]._len = e[1]->_len;
5881 for ( size_t i = 0; i < _offPoints.size(); i++ )
5883 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5884 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5885 const double w0 = _offPoints[i]._2edges._wgt[0];
5886 const double w1 = _offPoints[i]._2edges._wgt[1];
5887 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5888 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5889 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5890 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5891 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5892 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5894 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5895 _offPoints[i]._len = avgLen;
5899 if ( !surface.IsNull() ) // project _offPoints to the FACE
5901 fTol = 100 * BRep_Tool::Tolerance( F );
5902 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5904 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5905 //if ( surface->Gap() < 0.5 * segLen )
5906 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5908 for ( size_t i = 1; i < _offPoints.size(); ++i )
5910 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5911 //if ( surface->Gap() < 0.5 * segLen )
5912 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5916 // -----------------------------------------------------------------
5917 // project tgt nodes of extreme _LayerEdge's to the offset segments
5918 // -----------------------------------------------------------------
5920 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
5921 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
5922 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
5924 gp_Pnt pExtreme[2], pProj[2];
5925 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5927 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5928 int i = _iSeg[ is2nd ];
5929 int di = is2nd ? -1 : +1;
5930 bool projected = false;
5931 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5934 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5935 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5936 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5937 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5938 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5939 if ( dist < distMin || projected )
5942 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5945 else if ( dist > distPrev )
5947 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5953 while ( !projected &&
5954 i >= 0 && i+1 < (int)_offPoints.size() );
5958 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5961 _iSeg[1] = _offPoints.size()-2;
5962 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5967 if ( _iSeg[0] > _iSeg[1] )
5969 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5973 // adjust length of extreme LE (test viscous_layers_01/B7)
5974 gp_Vec vDiv0( pExtreme[0], pProj[0] );
5975 gp_Vec vDiv1( pExtreme[1], pProj[1] );
5976 double d0 = vDiv0.Magnitude();
5977 double d1 = vDiv1.Magnitude();
5978 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
5979 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5980 else e[0]->_len -= d0;
5982 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
5983 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5984 else e[1]->_len -= d1;
5987 // ---------------------------------------------------------------------------------
5988 // compute normalized length of the offset segments located between the projections
5989 // ---------------------------------------------------------------------------------
5991 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5992 vector< double > len( nbSeg + 1 );
5994 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5995 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5997 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5999 len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
6001 // d0 *= e[0]->_lenFactor;
6002 // d1 *= e[1]->_lenFactor;
6003 double fullLen = len.back() - d0 - d1;
6004 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6005 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6007 // temporary replace extreme _offPoints by pExtreme
6008 gp_XYZ op[2] = { _offPoints[ _iSeg[0] ]._xyz,
6009 _offPoints[ _iSeg[1]+1 ]._xyz };
6010 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6011 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6013 // -------------------------------------------------------------
6014 // distribute tgt nodes of _LayerEdge's between the projections
6015 // -------------------------------------------------------------
6018 for ( size_t i = 0; i < _eos.size(); ++i )
6020 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6021 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6022 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6024 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6025 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6026 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6028 if ( surface.IsNull() )
6030 _eos[i]->_pos.back() = p;
6032 else // project a new node position to a FACE
6034 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6035 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6037 p = surface->Value( uv2 ).XYZ();
6038 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6040 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6041 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6042 dumpMove( tgtNode );
6045 _offPoints[ _iSeg[0] ]._xyz = op[0];
6046 _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
6051 //================================================================================
6053 * \brief Prepare for smoothing
6055 //================================================================================
6057 void _Smoother1D::prepare(_SolidData& data)
6059 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6060 _curveLen = SMESH_Algo::EdgeLength( E );
6062 // sort _LayerEdge's by position on the EDGE
6063 data.SortOnEdge( E, _eos._edges );
6065 // compute normalized param of _eos._edges on EDGE
6066 _leParams.resize( _eos._edges.size() + 1 );
6069 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6071 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6073 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6074 curLen = p.Distance( pPrev );
6075 _leParams[i+1] = _leParams[i] + curLen;
6078 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6079 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6080 _leParams[i] = _leParams[i+1] / fullLen;
6081 _leParams.back() = 1.;
6084 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6086 // get cosin to use in findEdgesToSmooth()
6087 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6088 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6089 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6090 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6091 if ( _eos._sWOL.IsNull() ) // 3D
6092 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6093 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6098 // divide E to have offset segments with low deflection
6099 BRepAdaptor_Curve c3dAdaptor( E );
6100 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6101 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6102 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6103 if ( discret.NbPoints() <= 2 )
6105 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6109 const double u0 = c3dAdaptor.FirstParameter();
6110 gp_Pnt p; gp_Vec tangent;
6111 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6113 _offPoints.resize( discret.NbPoints() );
6114 for ( size_t i = 0; i < _offPoints.size(); i++ )
6116 double u = discret.Parameter( i+1 );
6117 c3dAdaptor.D1( u, p, tangent );
6118 _offPoints[i]._xyz = p.XYZ();
6119 _offPoints[i]._edgeDir = tangent.XYZ();
6120 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6125 std::vector< double > params( _eos.size() + 2 );
6127 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6128 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6129 for ( size_t i = 0; i < _eos.size(); i++ )
6130 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6132 if ( params[1] > params[ _eos.size() ] )
6133 std::reverse( params.begin() + 1, params.end() - 1 );
6135 _offPoints.resize( _eos.size() + 2 );
6136 for ( size_t i = 0; i < _offPoints.size(); i++ )
6138 const double u = params[i];
6139 c3dAdaptor.D1( u, p, tangent );
6140 _offPoints[i]._xyz = p.XYZ();
6141 _offPoints[i]._edgeDir = tangent.XYZ();
6142 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6147 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6148 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6149 _2NearEdges tmp2edges;
6150 tmp2edges._edges[1] = _eos._edges[0];
6151 _leOnV[0]._2neibors = & tmp2edges;
6152 _leOnV[0]._nodes = leOnV[0]->_nodes;
6153 _leOnV[1]._nodes = leOnV[1]->_nodes;
6154 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6155 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6157 // find _LayerEdge's located before and after an offset point
6158 // (_eos._edges[ iLE ] is next after ePrev)
6159 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6160 ePrev = _eos._edges[ iLE++ ];
6161 eNext = ePrev->_2neibors->_edges[1];
6163 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6164 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6165 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6166 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6169 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6170 for ( size_t i = 0; i < _offPoints.size(); i++ )
6171 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6172 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6174 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6175 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6176 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6179 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6181 int iLBO = _offPoints.size() - 2; // last but one
6183 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6184 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6186 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6187 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6188 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6190 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6191 _leOnV[ 0 ]._len = 0;
6192 _leOnV[ 1 ]._len = 0;
6193 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6194 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6197 _iSeg[1] = _offPoints.size()-2;
6199 // initialize OffPnt::_len
6200 for ( size_t i = 0; i < _offPoints.size(); ++i )
6201 _offPoints[i]._len = 0;
6203 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6205 _leOnV[0]._len = leOnV[0]->_len;
6206 _leOnV[1]._len = leOnV[1]->_len;
6207 for ( size_t i = 0; i < _offPoints.size(); i++ )
6209 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6210 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6211 const double w0 = _offPoints[i]._2edges._wgt[0];
6212 const double w1 = _offPoints[i]._2edges._wgt[1];
6213 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6214 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6215 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6216 _offPoints[i]._xyz = avgXYZ;
6217 _offPoints[i]._len = avgLen;
6222 //================================================================================
6224 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6226 //================================================================================
6228 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6229 const gp_XYZ& edgeDir)
6231 gp_XYZ cross = normal ^ edgeDir;
6232 gp_XYZ norm = edgeDir ^ cross;
6233 double size = norm.Modulus();
6235 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6236 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6241 //================================================================================
6243 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6245 //================================================================================
6247 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6248 vector< _LayerEdge* >& edges)
6250 map< double, _LayerEdge* > u2edge;
6251 for ( size_t i = 0; i < edges.size(); ++i )
6252 u2edge.insert( u2edge.end(),
6253 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6255 ASSERT( u2edge.size() == edges.size() );
6256 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6257 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6258 edges[i] = u2e->second;
6260 Sort2NeiborsOnEdge( edges );
6263 //================================================================================
6265 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6267 //================================================================================
6269 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6271 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6273 for ( size_t i = 0; i < edges.size()-1; ++i )
6274 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6275 edges[i]->_2neibors->reverse();
6277 const size_t iLast = edges.size() - 1;
6278 if ( edges.size() > 1 &&
6279 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6280 edges[iLast]->_2neibors->reverse();
6283 //================================================================================
6285 * \brief Return _EdgesOnShape* corresponding to the shape
6287 //================================================================================
6289 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6291 if ( shapeID < (int)_edgesOnShape.size() &&
6292 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6293 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6295 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6296 if ( _edgesOnShape[i]._shapeID == shapeID )
6297 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6302 //================================================================================
6304 * \brief Return _EdgesOnShape* corresponding to the shape
6306 //================================================================================
6308 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6310 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6311 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6314 //================================================================================
6316 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6318 //================================================================================
6320 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6322 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6324 set< TGeomID > vertices;
6326 if ( eos->ShapeType() == TopAbs_FACE )
6328 // check FACE concavity and get concave VERTEXes
6329 F = TopoDS::Face( eos->_shape );
6330 if ( isConcave( F, helper, &vertices ))
6331 _concaveFaces.insert( eos->_shapeID );
6333 // set eos._eosConcaVer
6334 eos->_eosConcaVer.clear();
6335 eos->_eosConcaVer.reserve( vertices.size() );
6336 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6338 _EdgesOnShape* eov = GetShapeEdges( *v );
6339 if ( eov && eov->_edges.size() == 1 )
6341 eos->_eosConcaVer.push_back( eov );
6342 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6343 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6347 // SetSmooLen() to _LayerEdge's on FACE
6348 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6350 eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6352 SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6353 while ( smIt->more() ) // loop on sub-shapes of the FACE
6355 _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6356 if ( !eoe ) continue;
6358 vector<_LayerEdge*>& eE = eoe->_edges;
6359 for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6361 if ( eE[iE]->_cosin <= theMinSmoothCosin )
6364 SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6365 while ( segIt->more() )
6367 const SMDS_MeshElement* seg = segIt->next();
6368 if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6370 if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6371 continue; // not to check a seg twice
6372 for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6374 _LayerEdge* eN = eE[iE]->_neibors[iN];
6375 if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6377 double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6378 double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6379 eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6380 eN->Set( _LayerEdge::NEAR_BOUNDARY );
6385 } // if ( eos->ShapeType() == TopAbs_FACE )
6387 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6389 eos->_edges[i]->_smooFunction = 0;
6390 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6392 bool isCurved = false;
6393 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6395 _LayerEdge* edge = eos->_edges[i];
6397 // get simplices sorted
6398 _Simplex::SortSimplices( edge->_simplices );
6400 // smoothing function
6401 edge->ChooseSmooFunction( vertices, _n2eMap );
6404 double avgNormProj = 0, avgLen = 0;
6405 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6407 _Simplex& s = edge->_simplices[iS];
6409 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6410 avgNormProj += edge->_normal * vec;
6411 avgLen += vec.Modulus();
6412 if ( substituteSrcNodes )
6414 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6415 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6418 avgNormProj /= edge->_simplices.size();
6419 avgLen /= edge->_simplices.size();
6420 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6423 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6425 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6426 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6428 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6432 // prepare for putOnOffsetSurface()
6433 if (( eos->ShapeType() == TopAbs_FACE ) &&
6434 ( isCurved || !eos->_eosConcaVer.empty() ))
6436 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6437 eos->_edgeForOffset = 0;
6439 double maxCosin = -1;
6440 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6442 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6443 if ( !eoe || eoe->_edges.empty() ) continue;
6445 vector<_LayerEdge*>& eE = eoe->_edges;
6446 _LayerEdge* e = eE[ eE.size() / 2 ];
6447 if ( e->_cosin > maxCosin )
6449 eos->_edgeForOffset = e;
6450 maxCosin = e->_cosin;
6456 //================================================================================
6458 * \brief Add faces for smoothing
6460 //================================================================================
6462 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6463 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6465 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6466 for ( ; eos != eosToSmooth.end(); ++eos )
6468 if ( !*eos || (*eos)->_toSmooth ) continue;
6470 (*eos)->_toSmooth = true;
6472 if ( (*eos)->ShapeType() == TopAbs_FACE )
6474 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6475 (*eos)->_toSmooth = true;
6479 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6480 if ( edgesNoAnaSmooth )
6481 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6483 if ( (*eos)->_edgeSmoother )
6484 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6488 //================================================================================
6490 * \brief Limit _LayerEdge::_maxLen according to local curvature
6492 //================================================================================
6494 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6496 // find intersection of neighbor _LayerEdge's to limit _maxLen
6497 // according to local curvature (IPAL52648)
6499 // This method must be called after findCollisionEdges() where _LayerEdge's
6500 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6502 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6504 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6505 if ( eosI._edges.empty() ) continue;
6506 if ( !eosI._hyp.ToSmooth() )
6508 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6510 _LayerEdge* eI = eosI._edges[i];
6511 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6513 _LayerEdge* eN = eI->_neibors[iN];
6514 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6516 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6517 limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6522 else if ( eosI.ShapeType() == TopAbs_EDGE )
6524 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6525 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6527 _LayerEdge* e0 = eosI._edges[0];
6528 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6530 _LayerEdge* eI = eosI._edges[i];
6531 limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6538 //================================================================================
6540 * \brief Limit _LayerEdge::_maxLen according to local curvature
6542 //================================================================================
6544 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6546 _EdgesOnShape& eos1,
6547 _EdgesOnShape& eos2,
6548 SMESH_MesherHelper& helper )
6550 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6551 double norSize = plnNorm.SquareModulus();
6552 if ( norSize < std::numeric_limits<double>::min() )
6553 return; // parallel normals
6555 // find closest points of skew _LayerEdge's
6556 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6557 gp_XYZ dir12 = src2 - src1;
6558 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6559 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6560 double dot1 = perp2 * e1->_normal;
6561 double dot2 = perp1 * e2->_normal;
6562 double u1 = ( perp2 * dir12 ) / dot1;
6563 double u2 = - ( perp1 * dir12 ) / dot2;
6564 if ( u1 > 0 && u2 > 0 )
6566 double ovl = ( u1 * e1->_normal * dir12 -
6567 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6568 if ( ovl > theSmoothThickToElemSizeRatio )
6570 e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6571 e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6576 //================================================================================
6578 * \brief Fill data._collisionEdges
6580 //================================================================================
6582 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6584 data._collisionEdges.clear();
6586 // set the full thickness of the layers to LEs
6587 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6589 _EdgesOnShape& eos = data._edgesOnShape[iS];
6590 if ( eos._edges.empty() ) continue;
6591 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6593 for ( size_t i = 0; i < eos._edges.size(); ++i )
6595 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6596 double maxLen = eos._edges[i]->_maxLen;
6597 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6598 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6599 eos._edges[i]->_maxLen = maxLen;
6603 // make temporary quadrangles got by extrusion of
6604 // mesh edges along _LayerEdge._normal's
6606 vector< const SMDS_MeshElement* > tmpFaces;
6608 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6610 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6611 if ( eos.ShapeType() != TopAbs_EDGE )
6613 if ( eos._edges.empty() )
6615 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6616 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6617 while ( smIt->more() )
6618 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6619 if ( eov->_edges.size() == 1 )
6620 edge[ bool( edge[0]) ] = eov->_edges[0];
6624 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6625 tmpFaces.push_back( f );
6628 for ( size_t i = 0; i < eos._edges.size(); ++i )
6630 _LayerEdge* edge = eos._edges[i];
6631 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6633 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6634 if ( src2->GetPosition()->GetDim() > 0 &&
6635 src2->GetID() < edge->_nodes[0]->GetID() )
6636 continue; // avoid using same segment twice
6638 // a _LayerEdge containg tgt2
6639 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6641 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6642 tmpFaces.push_back( f );
6647 // Find _LayerEdge's intersecting tmpFaces.
6649 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6651 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6652 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6654 double dist1, dist2, segLen, eps = 0.5;
6655 _CollisionEdges collEdges;
6656 vector< const SMDS_MeshElement* > suspectFaces;
6657 const double angle45 = Cos( 45. * M_PI / 180. );
6659 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6661 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6662 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6664 // find sub-shapes whose VL can influence VL on eos
6665 set< TGeomID > neighborShapes;
6666 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6667 while ( const TopoDS_Shape* face = fIt->next() )
6669 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6670 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6672 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6673 while ( subIt->more() )
6674 neighborShapes.insert( subIt->next()->GetId() );
6677 if ( eos.ShapeType() == TopAbs_VERTEX )
6679 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6680 while ( const TopoDS_Shape* edge = eIt->next() )
6681 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6683 // find intersecting _LayerEdge's
6684 for ( size_t i = 0; i < eos._edges.size(); ++i )
6686 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6687 _LayerEdge* edge = eos._edges[i];
6688 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6691 gp_Vec eSegDir0, eSegDir1;
6692 if ( edge->IsOnEdge() )
6694 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6695 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6696 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6698 suspectFaces.clear();
6699 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6700 SMDSAbs_Face, suspectFaces );
6701 collEdges._intEdges.clear();
6702 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6704 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6705 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6706 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6707 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6708 if ( edge->IsOnEdge() ) {
6709 if ( edge->_2neibors->include( f->_le1 ) ||
6710 edge->_2neibors->include( f->_le2 )) continue;
6713 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6714 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6716 dist1 = dist2 = Precision::Infinite();
6717 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6718 dist1 = Precision::Infinite();
6719 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6720 dist2 = Precision::Infinite();
6721 if (( dist1 > segLen ) && ( dist2 > segLen ))
6724 if ( edge->IsOnEdge() )
6726 // skip perpendicular EDGEs
6727 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6728 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6729 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6730 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6731 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6736 // either limit inflation of edges or remember them for updating _normal
6737 // double dot = edge->_normal * f->GetDir();
6740 collEdges._intEdges.push_back( f->_le1 );
6741 collEdges._intEdges.push_back( f->_le2 );
6745 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6746 // edge->_maxLen = Min( shortLen, edge->_maxLen );
6750 if ( !collEdges._intEdges.empty() )
6752 collEdges._edge = edge;
6753 data._collisionEdges.push_back( collEdges );
6758 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6761 // restore the zero thickness
6762 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6764 _EdgesOnShape& eos = data._edgesOnShape[iS];
6765 if ( eos._edges.empty() ) continue;
6766 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6768 for ( size_t i = 0; i < eos._edges.size(); ++i )
6770 eos._edges[i]->InvalidateStep( 1, eos );
6771 eos._edges[i]->_len = 0;
6776 //================================================================================
6778 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6779 * will be updated at each inflation step
6781 //================================================================================
6783 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
6785 SMESH_MesherHelper& helper )
6787 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6788 const double preci = BRep_Tool::Tolerance( convFace._face );
6789 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6791 bool edgesToUpdateFound = false;
6793 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6794 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6796 _EdgesOnShape& eos = * id2eos->second;
6797 if ( !eos._sWOL.IsNull() ) continue;
6798 if ( !eos._hyp.ToSmooth() ) continue;
6799 for ( size_t i = 0; i < eos._edges.size(); ++i )
6801 _LayerEdge* ledge = eos._edges[ i ];
6802 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6803 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6805 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6806 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6808 // the normal must be updated if distance from tgtPos to surface is less than
6811 // find an initial UV for search of a projection of tgtPos to surface
6812 const SMDS_MeshNode* nodeInFace = 0;
6813 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6814 while ( fIt->more() && !nodeInFace )
6816 const SMDS_MeshElement* f = fIt->next();
6817 if ( convFaceID != f->getshapeId() ) continue;
6819 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6820 while ( nIt->more() && !nodeInFace )
6822 const SMDS_MeshElement* n = nIt->next();
6823 if ( n->getshapeId() == convFaceID )
6824 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6829 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6832 surface->NextValueOfUV( uv, tgtPos, preci );
6833 double dist = surface->Gap();
6834 if ( dist < 0.95 * ledge->_maxLen )
6836 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6837 if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6838 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6839 edgesToUpdateFound = true;
6844 if ( !convFace._isTooCurved && edgesToUpdateFound )
6846 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6850 //================================================================================
6852 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6853 * _LayerEdge's on neighbor EDGE's
6855 //================================================================================
6857 bool _ViscousBuilder::updateNormals( _SolidData& data,
6858 SMESH_MesherHelper& helper,
6862 updateNormalsOfC1Vertices( data );
6864 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6867 // map to store new _normal and _cosin for each intersected edge
6868 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6869 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6870 _LayerEdge zeroEdge;
6871 zeroEdge._normal.SetCoord( 0,0,0 );
6872 zeroEdge._maxLen = Precision::Infinite();
6873 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6875 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6877 double segLen, dist1, dist2, dist;
6878 vector< pair< _LayerEdge*, double > > intEdgesDist;
6879 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6881 for ( int iter = 0; iter < 5; ++iter )
6883 edge2newEdge.clear();
6885 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6887 _CollisionEdges& ce = data._collisionEdges[iE];
6888 _LayerEdge* edge1 = ce._edge;
6889 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6890 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6891 if ( !eos1 ) continue;
6893 // detect intersections
6894 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6895 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6897 intEdgesDist.clear();
6898 double minIntDist = Precision::Infinite();
6899 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6901 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6902 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6903 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6905 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6906 double fact = ( 1.1 + dot * dot );
6907 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6908 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6909 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6910 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6911 dist1 = dist2 = Precision::Infinite();
6912 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
6913 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6916 if ( dist > testLen || dist <= 0 )
6919 if ( dist > testLen || dist <= 0 )
6922 // choose a closest edge
6923 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6924 double d1 = intP.SquareDistance( pSrc0 );
6925 double d2 = intP.SquareDistance( pSrc1 );
6926 int iClose = i + ( d2 < d1 );
6927 _LayerEdge* edge2 = ce._intEdges[iClose];
6928 edge2->Unset( _LayerEdge::MARKED );
6930 // choose a closest edge among neighbors
6931 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6932 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6933 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6935 _LayerEdge * edgeJ = intEdgesDist[j].first;
6936 if ( edge2->IsNeiborOnEdge( edgeJ ))
6938 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6939 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6942 intEdgesDist.push_back( make_pair( edge2, dist ));
6943 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6945 // iClose = i + !( d2 < d1 );
6946 // intEdges.push_back( ce._intEdges[iClose] );
6947 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6949 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6954 // compute new _normals
6955 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6957 _LayerEdge* edge2 = intEdgesDist[i].first;
6958 double distWgt = edge1->_len / intEdgesDist[i].second;
6959 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6960 // edge2->Is( _LayerEdge::BLOCKED )) continue;
6961 if ( edge2->Is( _LayerEdge::MARKED )) continue;
6962 edge2->Set( _LayerEdge::MARKED );
6965 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6967 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6968 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6969 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6970 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6971 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6972 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6973 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6974 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6975 newNormal.Normalize();
6979 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6980 if ( cos1 < theMinSmoothCosin )
6982 newCos = cos2 * sgn1;
6984 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6986 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6990 newCos = edge1->_cosin;
6993 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6994 e2neIt->second._normal += distWgt * newNormal;
6995 e2neIt->second._cosin = newCos;
6996 e2neIt->second._maxLen = 0.7 * minIntDist / edge1->_lenFactor;
6997 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6998 e2neIt->second._normal += dir2;
7000 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7001 e2neIt->second._normal += distWgt * newNormal;
7002 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7004 e2neIt->second._cosin = edge2->_cosin;
7005 e2neIt->second._maxLen = 1.3 * minIntDist / edge1->_lenFactor;
7007 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7008 e2neIt->second._normal += dir1;
7012 if ( edge2newEdge.empty() )
7013 break; //return true;
7015 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7017 // Update data of edges depending on a new _normal
7020 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7022 _LayerEdge* edge = e2neIt->first;
7023 if ( edge->Is( _LayerEdge::BLOCKED )) continue;
7024 _LayerEdge& newEdge = e2neIt->second;
7025 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7027 // Check if a new _normal is OK:
7028 newEdge._normal.Normalize();
7029 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7031 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7033 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7034 edge->_maxLen = newEdge._maxLen;
7035 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7037 continue; // the new _normal is bad
7039 // the new _normal is OK
7041 // find shapes that need smoothing due to change of _normal
7042 if ( edge->_cosin < theMinSmoothCosin &&
7043 newEdge._cosin > theMinSmoothCosin )
7045 if ( eos->_sWOL.IsNull() )
7047 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7048 while ( fIt->more() )
7049 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7051 else // edge inflates along a FACE
7053 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7054 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7055 while ( const TopoDS_Shape* E = eIt->next() )
7057 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7058 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7059 if ( angle < M_PI / 2 )
7060 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7065 double len = edge->_len;
7066 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7067 edge->SetNormal( newEdge._normal );
7068 edge->SetCosin( newEdge._cosin );
7069 edge->SetNewLength( len, *eos, helper );
7070 edge->Set( _LayerEdge::MARKED );
7071 edge->Set( _LayerEdge::NORMAL_UPDATED );
7072 edgesNoAnaSmooth.insert( eos );
7075 // Update normals and other dependent data of not intersecting _LayerEdge's
7076 // neighboring the intersecting ones
7078 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7080 _LayerEdge* edge1 = e2neIt->first;
7081 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7082 if ( !edge1->Is( _LayerEdge::MARKED ))
7085 if ( edge1->IsOnEdge() )
7087 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7088 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7089 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7092 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7094 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7096 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7097 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7098 continue; // j-th neighbor is also intersected
7099 _LayerEdge* prevEdge = edge1;
7100 const int nbSteps = 10;
7101 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7103 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7104 neighbor->Is( _LayerEdge::MARKED ))
7106 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7107 if ( !eos ) continue;
7108 _LayerEdge* nextEdge = neighbor;
7109 if ( neighbor->_2neibors )
7112 nextEdge = neighbor->_2neibors->_edges[iNext];
7113 if ( nextEdge == prevEdge )
7114 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7116 double r = double(step-1)/nbSteps/(iter+1);
7117 if ( !nextEdge->_2neibors )
7120 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7121 newNorm.Normalize();
7122 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7125 double len = neighbor->_len;
7126 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7127 neighbor->SetNormal( newNorm );
7128 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7129 if ( neighbor->_2neibors )
7130 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7131 neighbor->SetNewLength( len, *eos, helper );
7132 neighbor->Set( _LayerEdge::MARKED );
7133 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7134 edgesNoAnaSmooth.insert( eos );
7136 if ( !neighbor->_2neibors )
7137 break; // neighbor is on VERTEX
7139 // goto the next neighbor
7140 prevEdge = neighbor;
7141 neighbor = nextEdge;
7148 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7153 //================================================================================
7155 * \brief Check if a new normal is OK
7157 //================================================================================
7159 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7161 const gp_XYZ& newNormal)
7163 // check a min angle between the newNormal and surrounding faces
7164 vector<_Simplex> simplices;
7165 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7166 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7167 double newMinDot = 1, curMinDot = 1;
7168 for ( size_t i = 0; i < simplices.size(); ++i )
7170 n1.Set( simplices[i]._nPrev );
7171 n2.Set( simplices[i]._nNext );
7172 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7173 double normLen2 = normFace.SquareModulus();
7174 if ( normLen2 < std::numeric_limits<double>::min() )
7176 normFace /= Sqrt( normLen2 );
7177 newMinDot = Min( newNormal * normFace, newMinDot );
7178 curMinDot = Min( edge._normal * normFace, curMinDot );
7181 if ( newMinDot < 0.5 )
7183 ok = ( newMinDot >= curMinDot * 0.9 );
7184 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7185 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7186 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7192 //================================================================================
7194 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7196 //================================================================================
7198 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7199 SMESH_MesherHelper& helper,
7201 const double stepSize )
7203 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7204 return true; // no shapes needing smoothing
7206 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7208 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7209 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7210 !eos._hyp.ToSmooth() ||
7211 eos.ShapeType() != TopAbs_FACE ||
7212 eos._edges.empty() )
7215 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7216 if ( !toSmooth ) continue;
7218 for ( size_t i = 0; i < eos._edges.size(); ++i )
7220 _LayerEdge* edge = eos._edges[i];
7221 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7223 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7226 const gp_XYZ& pPrev = edge->PrevPos();
7227 const gp_XYZ& pLast = edge->_pos.back();
7228 gp_XYZ stepVec = pLast - pPrev;
7229 double realStepSize = stepVec.Modulus();
7230 if ( realStepSize < numeric_limits<double>::min() )
7233 edge->_lenFactor = realStepSize / stepSize;
7234 edge->_normal = stepVec / realStepSize;
7235 edge->Set( _LayerEdge::NORMAL_UPDATED );
7242 //================================================================================
7244 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7246 //================================================================================
7248 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7250 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7252 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7253 if ( eov._eosC1.empty() ||
7254 eov.ShapeType() != TopAbs_VERTEX ||
7255 eov._edges.empty() )
7258 gp_XYZ newNorm = eov._edges[0]->_normal;
7259 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7260 bool normChanged = false;
7262 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7264 _EdgesOnShape* eoe = eov._eosC1[i];
7265 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7266 const double eLen = SMESH_Algo::EdgeLength( e );
7267 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7268 if ( oppV.IsSame( eov._shape ))
7269 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7270 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7271 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7272 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7274 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7275 if ( curThickOpp + curThick < eLen )
7278 double wgt = 2. * curThick / eLen;
7279 newNorm += wgt * eovOpp->_edges[0]->_normal;
7284 eov._edges[0]->SetNormal( newNorm.Normalized() );
7285 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7290 //================================================================================
7292 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7294 //================================================================================
7296 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7297 SMESH_MesherHelper& helper,
7300 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7303 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7304 for ( ; id2face != data._convexFaces.end(); ++id2face )
7306 _ConvexFace & convFace = (*id2face).second;
7307 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7309 if ( convFace._normalsFixed )
7310 continue; // already fixed
7311 if ( convFace.CheckPrisms() )
7312 continue; // nothing to fix
7314 convFace._normalsFixed = true;
7316 BRepAdaptor_Surface surface ( convFace._face, false );
7317 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7319 // check if the convex FACE is of spherical shape
7321 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7325 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7326 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7328 _EdgesOnShape& eos = *(id2eos->second);
7329 if ( eos.ShapeType() == TopAbs_VERTEX )
7331 _LayerEdge* ledge = eos._edges[ 0 ];
7332 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7333 centersBox.Add( center );
7335 for ( size_t i = 0; i < eos._edges.size(); ++i )
7336 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7338 if ( centersBox.IsVoid() )
7340 debugMsg( "Error: centersBox.IsVoid()" );
7343 const bool isSpherical =
7344 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7346 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7347 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7351 // set _LayerEdge::_normal as average of all normals
7353 // WARNING: different density of nodes on EDGEs is not taken into account that
7354 // can lead to an improper new normal
7356 gp_XYZ avgNormal( 0,0,0 );
7358 id2eos = convFace._subIdToEOS.begin();
7359 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7361 _EdgesOnShape& eos = *(id2eos->second);
7362 // set data of _CentralCurveOnEdge
7363 if ( eos.ShapeType() == TopAbs_EDGE )
7365 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7366 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7367 if ( !eos._sWOL.IsNull() )
7368 ceCurve._adjFace.Nullify();
7370 ceCurve._ledges.insert( ceCurve._ledges.end(),
7371 eos._edges.begin(), eos._edges.end());
7373 // summarize normals
7374 for ( size_t i = 0; i < eos._edges.size(); ++i )
7375 avgNormal += eos._edges[ i ]->_normal;
7377 double normSize = avgNormal.SquareModulus();
7378 if ( normSize < 1e-200 )
7380 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7383 avgNormal /= Sqrt( normSize );
7385 // compute new _LayerEdge::_cosin on EDGEs
7386 double avgCosin = 0;
7389 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7391 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7392 if ( ceCurve._adjFace.IsNull() )
7394 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7396 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7397 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7400 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7401 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7402 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7408 avgCosin /= nbCosin;
7410 // set _LayerEdge::_normal = avgNormal
7411 id2eos = convFace._subIdToEOS.begin();
7412 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7414 _EdgesOnShape& eos = *(id2eos->second);
7415 if ( eos.ShapeType() != TopAbs_EDGE )
7416 for ( size_t i = 0; i < eos._edges.size(); ++i )
7417 eos._edges[ i ]->_cosin = avgCosin;
7419 for ( size_t i = 0; i < eos._edges.size(); ++i )
7421 eos._edges[ i ]->SetNormal( avgNormal );
7422 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7426 else // if ( isSpherical )
7428 // We suppose that centers of curvature at all points of the FACE
7429 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7430 // having a common center of curvature we define the same new normal
7431 // as a sum of normals of _LayerEdge's on EDGEs among them.
7433 // get all centers of curvature for each EDGE
7435 helper.SetSubShape( convFace._face );
7436 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7438 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7439 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7441 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7443 // set adjacent FACE
7444 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7446 // get _LayerEdge's of the EDGE
7447 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7448 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7449 if ( !eos || eos->_edges.empty() )
7451 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7452 for ( int iV = 0; iV < 2; ++iV )
7454 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7455 TGeomID vID = meshDS->ShapeToIndex( v );
7456 eos = data.GetShapeEdges( vID );
7457 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7459 edgeLEdge = &vertexLEdges[0];
7460 edgeLEdgeEnd = edgeLEdge + 2;
7462 centerCurves[ iE ]._adjFace.Nullify();
7466 if ( ! eos->_toSmooth )
7467 data.SortOnEdge( edge, eos->_edges );
7468 edgeLEdge = &eos->_edges[ 0 ];
7469 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7470 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7471 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7473 if ( ! eos->_sWOL.IsNull() )
7474 centerCurves[ iE ]._adjFace.Nullify();
7477 // Get curvature centers
7481 if ( edgeLEdge[0]->IsOnEdge() &&
7482 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7484 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7485 centersBox.Add( center );
7487 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7488 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7489 { // EDGE or VERTEXes
7490 centerCurves[ iE ].Append( center, *edgeLEdge );
7491 centersBox.Add( center );
7493 if ( edgeLEdge[-1]->IsOnEdge() &&
7494 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7496 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7497 centersBox.Add( center );
7499 centerCurves[ iE ]._isDegenerated =
7500 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7502 } // loop on EDGES of convFace._face to set up data of centerCurves
7504 // Compute new normals for _LayerEdge's on EDGEs
7506 double avgCosin = 0;
7509 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7511 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7512 if ( ceCurve._isDegenerated )
7514 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7515 vector< gp_XYZ > & newNormals = ceCurve._normals;
7516 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7519 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7522 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7524 if ( isOK && !ceCurve._adjFace.IsNull() )
7526 // compute new _LayerEdge::_cosin
7527 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7528 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7531 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7532 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7533 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7539 // set new normals to _LayerEdge's of NOT degenerated central curves
7540 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7542 if ( centerCurves[ iE ]._isDegenerated )
7544 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7546 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7547 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7550 // set new normals to _LayerEdge's of degenerated central curves
7551 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7553 if ( !centerCurves[ iE ]._isDegenerated ||
7554 centerCurves[ iE ]._ledges.size() < 3 )
7556 // new normal is an average of new normals at VERTEXes that
7557 // was computed on non-degenerated _CentralCurveOnEdge's
7558 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7559 centerCurves[ iE ]._ledges.back ()->_normal );
7560 double sz = newNorm.Modulus();
7564 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7565 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7566 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7568 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7569 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7570 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7574 // Find new normals for _LayerEdge's based on FACE
7577 avgCosin /= nbCosin;
7578 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7579 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7580 if ( id2eos != convFace._subIdToEOS.end() )
7584 _EdgesOnShape& eos = * ( id2eos->second );
7585 for ( size_t i = 0; i < eos._edges.size(); ++i )
7587 _LayerEdge* ledge = eos._edges[ i ];
7588 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7590 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7592 iE = iE % centerCurves.size();
7593 if ( centerCurves[ iE ]._isDegenerated )
7595 newNorm.SetCoord( 0,0,0 );
7596 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7598 ledge->SetNormal( newNorm );
7599 ledge->_cosin = avgCosin;
7600 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7607 } // not a quasi-spherical FACE
7609 // Update _LayerEdge's data according to a new normal
7611 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7612 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7614 id2eos = convFace._subIdToEOS.begin();
7615 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7617 _EdgesOnShape& eos = * ( id2eos->second );
7618 for ( size_t i = 0; i < eos._edges.size(); ++i )
7620 _LayerEdge* & ledge = eos._edges[ i ];
7621 double len = ledge->_len;
7622 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7623 ledge->SetCosin( ledge->_cosin );
7624 ledge->SetNewLength( len, eos, helper );
7626 if ( eos.ShapeType() != TopAbs_FACE )
7627 for ( size_t i = 0; i < eos._edges.size(); ++i )
7629 _LayerEdge* ledge = eos._edges[ i ];
7630 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7632 _LayerEdge* neibor = ledge->_neibors[iN];
7633 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7635 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7636 neibor->Set( _LayerEdge::MOVED );
7637 neibor->SetSmooLen( neibor->_len );
7641 } // loop on sub-shapes of convFace._face
7643 // Find FACEs adjacent to convFace._face that got necessity to smooth
7644 // as a result of normals modification
7646 set< _EdgesOnShape* > adjFacesToSmooth;
7647 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7649 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7650 centerCurves[ iE ]._adjFaceToSmooth )
7652 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7654 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7656 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7661 data.AddShapesToSmooth( adjFacesToSmooth );
7666 } // loop on data._convexFaces
7671 //================================================================================
7673 * \brief Return max curvature of a FACE
7675 //================================================================================
7677 double _ConvexFace::GetMaxCurvature( _SolidData& data,
7679 BRepLProp_SLProps& surfProp,
7680 SMESH_MesherHelper& helper)
7682 double maxCurvature = 0;
7684 TopoDS_Face F = TopoDS::Face( eof._shape );
7686 const int nbTestPnt = 5;
7687 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7688 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7689 while ( smIt->more() )
7691 SMESH_subMesh* sm = smIt->next();
7692 const TGeomID subID = sm->GetId();
7694 // find _LayerEdge's of a sub-shape
7696 if (( eos = data.GetShapeEdges( subID )))
7697 this->_subIdToEOS.insert( make_pair( subID, eos ));
7701 // check concavity and curvature and limit data._stepSize
7702 const double minCurvature =
7703 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7704 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7705 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7707 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7708 surfProp.SetParameters( uv.X(), uv.Y() );
7709 if ( surfProp.IsCurvatureDefined() )
7711 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7712 surfProp.MinCurvature() * oriFactor );
7713 maxCurvature = Max( maxCurvature, curvature );
7715 if ( curvature > minCurvature )
7716 this->_isTooCurved = true;
7719 } // loop on sub-shapes of the FACE
7721 return maxCurvature;
7724 //================================================================================
7726 * \brief Finds a center of curvature of a surface at a _LayerEdge
7728 //================================================================================
7730 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7731 BRepLProp_SLProps& surfProp,
7732 SMESH_MesherHelper& helper,
7733 gp_Pnt & center ) const
7735 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7736 surfProp.SetParameters( uv.X(), uv.Y() );
7737 if ( !surfProp.IsCurvatureDefined() )
7740 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7741 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7742 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7743 if ( surfCurvatureMin > surfCurvatureMax )
7744 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7746 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7751 //================================================================================
7753 * \brief Check that prisms are not distorted
7755 //================================================================================
7757 bool _ConvexFace::CheckPrisms() const
7760 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7762 const _LayerEdge* edge = _simplexTestEdges[i];
7763 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7764 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7765 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7767 debugMsg( "Bad simplex of _simplexTestEdges ("
7768 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7769 << " "<< edge->_simplices[j]._nPrev->GetID()
7770 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7777 //================================================================================
7779 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7780 * stored in this _CentralCurveOnEdge.
7781 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7782 * \param [in,out] newNormal - current normal at this point, to be redefined
7783 * \return bool - true if succeeded.
7785 //================================================================================
7787 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7789 if ( this->_isDegenerated )
7792 // find two centers the given one lies between
7794 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7796 double sl2 = 1.001 * _segLength2[ i ];
7798 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7802 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7803 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7808 double r = d1 / ( d1 + d2 );
7809 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7810 ( r ) * _ledges[ i+1 ]->_normal );
7814 double sz = newNormal.Modulus();
7823 //================================================================================
7825 * \brief Set shape members
7827 //================================================================================
7829 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7830 const _ConvexFace& convFace,
7832 SMESH_MesherHelper& helper)
7836 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7837 while ( const TopoDS_Shape* F = fIt->next())
7838 if ( !convFace._face.IsSame( *F ))
7840 _adjFace = TopoDS::Face( *F );
7841 _adjFaceToSmooth = false;
7842 // _adjFace already in a smoothing queue ?
7843 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7844 _adjFaceToSmooth = eos->_toSmooth;
7849 //================================================================================
7851 * \brief Looks for intersection of it's last segment with faces
7852 * \param distance - returns shortest distance from the last node to intersection
7854 //================================================================================
7856 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7858 const double& epsilon,
7860 const SMDS_MeshElement** intFace)
7862 vector< const SMDS_MeshElement* > suspectFaces;
7864 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7865 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7867 bool segmentIntersected = false;
7868 distance = Precision::Infinite();
7869 int iFace = -1; // intersected face
7870 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7872 const SMDS_MeshElement* face = suspectFaces[j];
7873 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7874 face->GetNodeIndex( _nodes[0] ) >= 0 )
7875 continue; // face sharing _LayerEdge node
7876 const int nbNodes = face->NbCornerNodes();
7877 bool intFound = false;
7879 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7882 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7886 const SMDS_MeshNode* tria[3];
7889 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7892 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7898 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7899 segmentIntersected = true;
7900 if ( distance > dist )
7901 distance = dist, iFace = j;
7904 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7908 if ( segmentIntersected )
7911 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7912 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7913 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7914 << ", intersection with face ("
7915 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7916 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7917 << ") distance = " << distance << endl;
7921 return segmentIntersected;
7924 //================================================================================
7926 * \brief Returns a point used to check orientation of _simplices
7928 //================================================================================
7930 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7932 size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7934 if ( !eos || eos->_sWOL.IsNull() )
7937 if ( eos->SWOLType() == TopAbs_EDGE )
7939 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7941 //else // TopAbs_FACE
7943 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7946 //================================================================================
7948 * \brief Returns size and direction of the last segment
7950 //================================================================================
7952 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7954 // find two non-coincident positions
7955 gp_XYZ orig = _pos.back();
7957 int iPrev = _pos.size() - 2;
7958 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7959 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7960 while ( iPrev >= 0 )
7962 vec = orig - _pos[iPrev];
7963 if ( vec.SquareModulus() > tol*tol )
7973 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7974 segDir.SetDirection( _normal );
7979 gp_Pnt pPrev = _pos[ iPrev ];
7980 if ( !eos._sWOL.IsNull() )
7982 TopLoc_Location loc;
7983 if ( eos.SWOLType() == TopAbs_EDGE )
7986 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7987 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7991 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7992 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7994 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7996 segDir.SetLocation( pPrev );
7997 segDir.SetDirection( vec );
7998 segLen = vec.Modulus();
8004 //================================================================================
8006 * \brief Return the last (or \a which) position of the target node on a FACE.
8007 * \param [in] F - the FACE this _LayerEdge is inflated along
8008 * \param [in] which - index of position
8009 * \return gp_XY - result UV
8011 //================================================================================
8013 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8015 if ( F.IsSame( eos._sWOL )) // F is my FACE
8016 return gp_XY( _pos.back().X(), _pos.back().Y() );
8018 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8019 return gp_XY( 1e100, 1e100 );
8021 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8022 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8023 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8024 if ( !C2d.IsNull() && f <= u && u <= l )
8025 return C2d->Value( u ).XY();
8027 return gp_XY( 1e100, 1e100 );
8030 //================================================================================
8032 * \brief Test intersection of the last segment with a given triangle
8033 * using Moller-Trumbore algorithm
8034 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8036 //================================================================================
8038 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8039 const gp_XYZ& vert0,
8040 const gp_XYZ& vert1,
8041 const gp_XYZ& vert2,
8043 const double& EPSILON) const
8045 const gp_Pnt& orig = lastSegment.Location();
8046 const gp_Dir& dir = lastSegment.Direction();
8048 /* calculate distance from vert0 to ray origin */
8049 //gp_XYZ tvec = orig.XYZ() - vert0;
8051 //if ( tvec * dir > EPSILON )
8052 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8055 gp_XYZ edge1 = vert1 - vert0;
8056 gp_XYZ edge2 = vert2 - vert0;
8058 /* begin calculating determinant - also used to calculate U parameter */
8059 gp_XYZ pvec = dir.XYZ() ^ edge2;
8061 /* if determinant is near zero, ray lies in plane of triangle */
8062 double det = edge1 * pvec;
8064 const double ANGL_EPSILON = 1e-12;
8065 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8068 /* calculate distance from vert0 to ray origin */
8069 gp_XYZ tvec = orig.XYZ() - vert0;
8071 /* calculate U parameter and test bounds */
8072 double u = ( tvec * pvec ) / det;
8073 //if (u < 0.0 || u > 1.0)
8074 if ( u < -EPSILON || u > 1.0 + EPSILON )
8077 /* prepare to test V parameter */
8078 gp_XYZ qvec = tvec ^ edge1;
8080 /* calculate V parameter and test bounds */
8081 double v = (dir.XYZ() * qvec) / det;
8082 //if ( v < 0.0 || u + v > 1.0 )
8083 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8086 /* calculate t, ray intersects triangle */
8087 t = (edge2 * qvec) / det;
8093 //================================================================================
8095 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8096 * neighbor _LayerEdge's by it's own inflation vector.
8097 * \param [in] eov - EOS of the VERTEX
8098 * \param [in] eos - EOS of the FACE
8099 * \param [in] step - inflation step
8100 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8102 //================================================================================
8104 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8105 const _EdgesOnShape* eos,
8107 vector< _LayerEdge* > & badSmooEdges )
8109 // check if any of _neibors is in badSmooEdges
8110 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8111 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8114 // get all edges to move
8116 set< _LayerEdge* > edges;
8118 // find a distance between _LayerEdge on VERTEX and its neighbors
8119 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8121 for ( size_t i = 0; i < _neibors.size(); ++i )
8123 _LayerEdge* nEdge = _neibors[i];
8124 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8126 edges.insert( nEdge );
8127 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8130 // add _LayerEdge's close to curPosV
8134 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8136 _LayerEdge* edgeF = *e;
8137 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8139 _LayerEdge* nEdge = edgeF->_neibors[i];
8140 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8141 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8142 edges.insert( nEdge );
8146 while ( nbE < edges.size() );
8148 // move the target node of the got edges
8150 gp_XYZ prevPosV = PrevPos();
8151 if ( eov->SWOLType() == TopAbs_EDGE )
8153 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8154 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8156 else if ( eov->SWOLType() == TopAbs_FACE )
8158 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8159 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8162 SMDS_FacePosition* fPos;
8163 //double r = 1. - Min( 0.9, step / 10. );
8164 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8166 _LayerEdge* edgeF = *e;
8167 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8168 const gp_XYZ newPosF = curPosV + prevVF;
8169 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8170 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8171 edgeF->_pos.back() = newPosF;
8172 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8174 // set _curvature to make edgeF updated by putOnOffsetSurface()
8175 if ( !edgeF->_curvature )
8176 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
8178 edgeF->_curvature = new _Curvature;
8179 edgeF->_curvature->_r = 0;
8180 edgeF->_curvature->_k = 0;
8181 edgeF->_curvature->_h2lenRatio = 0;
8182 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8185 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8186 // SMESH_TNodeXYZ( _nodes[0] ));
8187 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8189 // _LayerEdge* edgeF = *e;
8190 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8191 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8192 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8193 // edgeF->_pos.back() = newPosF;
8194 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8197 // smooth _LayerEdge's around moved nodes
8198 //size_t nbBadBefore = badSmooEdges.size();
8199 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8201 _LayerEdge* edgeF = *e;
8202 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8203 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8204 //&& !edges.count( edgeF->_neibors[j] ))
8206 _LayerEdge* edgeFN = edgeF->_neibors[j];
8207 edgeFN->Unset( SMOOTHED );
8208 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8211 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8212 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8213 // int nbBadAfter = edgeFN->_simplices.size();
8215 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8217 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8219 // if ( nbBadAfter <= nbBad )
8221 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8222 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8223 // edgeF->_pos.back() = newPosF;
8224 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8225 // nbBad = nbBadAfter;
8229 badSmooEdges.push_back( edgeFN );
8232 // move a bit not smoothed around moved nodes
8233 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8235 // _LayerEdge* edgeF = badSmooEdges[i];
8236 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8237 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8238 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8239 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8240 // edgeF->_pos.back() = newPosF;
8241 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8245 //================================================================================
8247 * \brief Perform smooth of _LayerEdge's based on EDGE's
8248 * \retval bool - true if node has been moved
8250 //================================================================================
8252 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8253 const TopoDS_Face& F,
8254 SMESH_MesherHelper& helper)
8256 ASSERT( IsOnEdge() );
8258 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8259 SMESH_TNodeXYZ oldPos( tgtNode );
8260 double dist01, distNewOld;
8262 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8263 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8264 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8266 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8267 double lenDelta = 0;
8270 //lenDelta = _curvature->lenDelta( _len );
8271 lenDelta = _curvature->lenDeltaByDist( dist01 );
8272 newPos.ChangeCoord() += _normal * lenDelta;
8275 distNewOld = newPos.Distance( oldPos );
8279 if ( _2neibors->_plnNorm )
8281 // put newPos on the plane defined by source node and _plnNorm
8282 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8283 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8284 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8286 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8287 _pos.back() = newPos.XYZ();
8291 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8292 gp_XY uv( Precision::Infinite(), 0 );
8293 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8294 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8296 newPos = surface->Value( uv );
8297 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8300 // commented for IPAL0052478
8301 // if ( _curvature && lenDelta < 0 )
8303 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8304 // _len -= prevPos.Distance( oldPos );
8305 // _len += prevPos.Distance( newPos );
8307 bool moved = distNewOld > dist01/50;
8309 dumpMove( tgtNode ); // debug
8314 //================================================================================
8316 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8318 //================================================================================
8320 void _LayerEdge::SmoothWoCheck()
8322 if ( Is( DIFFICULT ))
8325 bool moved = Is( SMOOTHED );
8326 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8327 moved = _neibors[i]->Is( SMOOTHED );
8331 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8333 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8334 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8335 _pos.back() = newPos;
8337 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8340 //================================================================================
8342 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8344 //================================================================================
8346 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8348 if ( ! Is( NEAR_BOUNDARY ))
8353 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8355 _LayerEdge* eN = _neibors[iN];
8356 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8359 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8360 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8361 eN->_pos.size() != _pos.size() );
8363 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8364 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8365 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8366 if ( eN->_nodes.size() > 1 &&
8367 eN->_simplices[i].Includes( _nodes.back() ) &&
8368 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8373 badNeibors->push_back( eN );
8374 debugMsg("Bad boundary simplex ( "
8375 << " "<< eN->_nodes[0]->GetID()
8376 << " "<< eN->_nodes.back()->GetID()
8377 << " "<< eN->_simplices[i]._nPrev->GetID()
8378 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8389 //================================================================================
8391 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8392 * \retval int - nb of bad simplices around this _LayerEdge
8394 //================================================================================
8396 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8398 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8399 return 0; // shape of simplices not changed
8400 if ( _simplices.size() < 2 )
8401 return 0; // _LayerEdge inflated along EDGE or FACE
8403 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8406 const gp_XYZ& curPos = _pos.back();
8407 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8409 // quality metrics (orientation) of tetras around _tgtNode
8411 double vol, minVolBefore = 1e100;
8412 for ( size_t i = 0; i < _simplices.size(); ++i )
8414 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8415 minVolBefore = Min( minVolBefore, vol );
8417 int nbBad = _simplices.size() - nbOkBefore;
8419 bool bndNeedSmooth = false;
8421 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8425 // evaluate min angle
8426 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8428 size_t nbGoodAngles = _simplices.size();
8430 for ( size_t i = 0; i < _simplices.size(); ++i )
8432 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8435 if ( nbGoodAngles == _simplices.size() )
8441 if ( Is( ON_CONCAVE_FACE ))
8444 if ( step % 2 == 0 )
8447 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8449 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8450 _smooFunction = _funs[ FUN_CENTROIDAL ];
8452 _smooFunction = _funs[ FUN_LAPLACIAN ];
8455 // compute new position for the last _pos using different _funs
8458 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8461 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8462 else if ( _funs[ iFun ] == _smooFunction )
8463 continue; // _smooFunction again
8464 else if ( step > 1 )
8465 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8467 break; // let "easy" functions improve elements around distorted ones
8471 double delta = _curvature->lenDelta( _len );
8473 newPos += _normal * delta;
8476 double segLen = _normal * ( newPos - prevPos );
8477 if ( segLen + delta > 0 )
8478 newPos += _normal * delta;
8480 // double segLenChange = _normal * ( curPos - newPos );
8481 // newPos += 0.5 * _normal * segLenChange;
8485 double minVolAfter = 1e100;
8486 for ( size_t i = 0; i < _simplices.size(); ++i )
8488 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8489 minVolAfter = Min( minVolAfter, vol );
8492 if ( nbOkAfter < nbOkBefore )
8496 ( nbOkAfter == nbOkBefore ) &&
8497 ( minVolAfter <= minVolBefore ))
8500 nbBad = _simplices.size() - nbOkAfter;
8501 minVolBefore = minVolAfter;
8502 nbOkBefore = nbOkAfter;
8505 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8506 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8507 _pos.back() = newPos;
8509 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8510 << (nbBad ? " --BAD" : ""));
8514 continue; // look for a better function
8520 } // loop on smoothing functions
8522 if ( moved ) // notify _neibors
8525 for ( size_t i = 0; i < _neibors.size(); ++i )
8526 if ( !_neibors[i]->Is( MOVED ))
8528 _neibors[i]->Set( MOVED );
8529 toSmooth.push_back( _neibors[i] );
8536 //================================================================================
8538 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8539 * \retval int - nb of bad simplices around this _LayerEdge
8541 //================================================================================
8543 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8545 if ( !_smooFunction )
8546 return 0; // _LayerEdge inflated along EDGE or FACE
8548 return 0; // not inflated
8550 const gp_XYZ& curPos = _pos.back();
8551 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8553 // quality metrics (orientation) of tetras around _tgtNode
8555 double vol, minVolBefore = 1e100;
8556 for ( size_t i = 0; i < _simplices.size(); ++i )
8558 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8559 minVolBefore = Min( minVolBefore, vol );
8561 int nbBad = _simplices.size() - nbOkBefore;
8563 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8565 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8566 _smooFunction = _funs[ FUN_LAPLACIAN ];
8567 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8568 _smooFunction = _funs[ FUN_CENTROIDAL ];
8571 // compute new position for the last _pos using different _funs
8573 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8576 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8577 else if ( _funs[ iFun ] == _smooFunction )
8578 continue; // _smooFunction again
8579 else if ( step > 1 )
8580 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8582 break; // let "easy" functions improve elements around distorted ones
8586 double delta = _curvature->lenDelta( _len );
8588 newPos += _normal * delta;
8591 double segLen = _normal * ( newPos - prevPos );
8592 if ( segLen + delta > 0 )
8593 newPos += _normal * delta;
8595 // double segLenChange = _normal * ( curPos - newPos );
8596 // newPos += 0.5 * _normal * segLenChange;
8600 double minVolAfter = 1e100;
8601 for ( size_t i = 0; i < _simplices.size(); ++i )
8603 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8604 minVolAfter = Min( minVolAfter, vol );
8607 if ( nbOkAfter < nbOkBefore )
8609 if (( isConcaveFace || findBest ) &&
8610 ( nbOkAfter == nbOkBefore ) &&
8611 ( minVolAfter <= minVolBefore )
8615 nbBad = _simplices.size() - nbOkAfter;
8616 minVolBefore = minVolAfter;
8617 nbOkBefore = nbOkAfter;
8619 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8620 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8621 _pos.back() = newPos;
8623 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8624 << ( nbBad ? "--BAD" : ""));
8626 // commented for IPAL0052478
8627 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8628 // _len += prevPos.Distance(newPos);
8630 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8632 //_smooFunction = _funs[ iFun ];
8633 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8634 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8635 // << " minVol: " << minVolAfter
8636 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8638 continue; // look for a better function
8644 } // loop on smoothing functions
8649 //================================================================================
8651 * \brief Chooses a smoothing technic giving a position most close to an initial one.
8652 * For a correct result, _simplices must contain nodes lying on geometry.
8654 //================================================================================
8656 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8657 const TNode2Edge& n2eMap)
8659 if ( _smooFunction ) return;
8661 // use smoothNefPolygon() near concaveVertices
8662 if ( !concaveVertices.empty() )
8664 _smooFunction = _funs[ FUN_CENTROIDAL ];
8666 Set( ON_CONCAVE_FACE );
8668 for ( size_t i = 0; i < _simplices.size(); ++i )
8670 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8672 _smooFunction = _funs[ FUN_NEFPOLY ];
8674 // set FUN_CENTROIDAL to neighbor edges
8675 for ( i = 0; i < _neibors.size(); ++i )
8677 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8679 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8686 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8687 // // where the nodes are smoothed too far along a sphere thus creating
8688 // // inverted _simplices
8689 // double dist[theNbSmooFuns];
8690 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8691 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8693 // double minDist = Precision::Infinite();
8694 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8695 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8697 // gp_Pnt newP = (this->*_funs[i])();
8698 // dist[i] = p.SquareDistance( newP );
8699 // if ( dist[i]*coef[i] < minDist )
8701 // _smooFunction = _funs[i];
8702 // minDist = dist[i]*coef[i];
8708 _smooFunction = _funs[ FUN_LAPLACIAN ];
8711 // for ( size_t i = 0; i < _simplices.size(); ++i )
8712 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8713 // if ( minDim == 0 )
8714 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8715 // else if ( minDim == 1 )
8716 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8720 // for ( int i = 0; i < FUN_NB; ++i )
8722 // //cout << dist[i] << " ";
8723 // if ( _smooFunction == _funs[i] ) {
8725 // //debugMsg( fNames[i] );
8729 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8732 //================================================================================
8734 * \brief Returns a name of _SmooFunction
8736 //================================================================================
8738 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8741 fun = _smooFunction;
8742 for ( int i = 0; i < theNbSmooFuns; ++i )
8743 if ( fun == _funs[i] )
8746 return theNbSmooFuns;
8749 //================================================================================
8751 * \brief Computes a new node position using Laplacian smoothing
8753 //================================================================================
8755 gp_XYZ _LayerEdge::smoothLaplacian()
8757 gp_XYZ newPos (0,0,0);
8758 for ( size_t i = 0; i < _simplices.size(); ++i )
8759 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8760 newPos /= _simplices.size();
8765 //================================================================================
8767 * \brief Computes a new node position using angular-based smoothing
8769 //================================================================================
8771 gp_XYZ _LayerEdge::smoothAngular()
8773 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8774 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8775 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8777 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8779 for ( size_t i = 0; i < _simplices.size(); ++i )
8781 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8782 edgeDir.push_back( p - pPrev );
8783 edgeSize.push_back( edgeDir.back().Magnitude() );
8784 if ( edgeSize.back() < numeric_limits<double>::min() )
8787 edgeSize.pop_back();
8791 edgeDir.back() /= edgeSize.back();
8792 points.push_back( p );
8797 edgeDir.push_back ( edgeDir[0] );
8798 edgeSize.push_back( edgeSize[0] );
8799 pN /= points.size();
8801 gp_XYZ newPos(0,0,0);
8803 for ( size_t i = 0; i < points.size(); ++i )
8805 gp_Vec toN = pN - points[i];
8806 double toNLen = toN.Magnitude();
8807 if ( toNLen < numeric_limits<double>::min() )
8812 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8813 double bisecLen = bisec.SquareMagnitude();
8814 if ( bisecLen < numeric_limits<double>::min() )
8816 gp_Vec norm = edgeDir[i] ^ toN;
8817 bisec = norm ^ edgeDir[i];
8818 bisecLen = bisec.SquareMagnitude();
8820 bisecLen = Sqrt( bisecLen );
8824 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8825 sumSize += bisecLen;
8827 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8828 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8834 // project newPos to an average plane
8836 gp_XYZ norm(0,0,0); // plane normal
8837 points.push_back( points[0] );
8838 for ( size_t i = 1; i < points.size(); ++i )
8840 gp_XYZ vec1 = points[ i-1 ] - pN;
8841 gp_XYZ vec2 = points[ i ] - pN;
8842 gp_XYZ cross = vec1 ^ vec2;
8845 if ( cross * norm < numeric_limits<double>::min() )
8846 norm += cross.Reversed();
8850 catch (Standard_Failure) { // if |cross| == 0.
8853 gp_XYZ vec = newPos - pN;
8854 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8855 newPos = newPos - r * norm;
8860 //================================================================================
8862 * \brief Computes a new node position using weigthed node positions
8864 //================================================================================
8866 gp_XYZ _LayerEdge::smoothLengthWeighted()
8868 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8869 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8871 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8872 for ( size_t i = 0; i < _simplices.size(); ++i )
8874 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8875 edgeSize.push_back( ( p - pPrev ).Modulus() );
8876 if ( edgeSize.back() < numeric_limits<double>::min() )
8878 edgeSize.pop_back();
8882 points.push_back( p );
8886 edgeSize.push_back( edgeSize[0] );
8888 gp_XYZ newPos(0,0,0);
8890 for ( size_t i = 0; i < points.size(); ++i )
8892 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8893 sumSize += edgeSize[i] + edgeSize[i+1];
8899 //================================================================================
8901 * \brief Computes a new node position using angular-based smoothing
8903 //================================================================================
8905 gp_XYZ _LayerEdge::smoothCentroidal()
8907 gp_XYZ newPos(0,0,0);
8908 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8910 for ( size_t i = 0; i < _simplices.size(); ++i )
8912 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8913 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8914 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8915 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8918 newPos += gc * size;
8925 //================================================================================
8927 * \brief Computes a new node position located inside a Nef polygon
8929 //================================================================================
8931 gp_XYZ _LayerEdge::smoothNefPolygon()
8932 #ifdef OLD_NEF_POLYGON
8934 gp_XYZ newPos(0,0,0);
8936 // get a plane to search a solution on
8938 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8940 const double tol = numeric_limits<double>::min();
8941 gp_XYZ center(0,0,0);
8942 for ( i = 0; i < _simplices.size(); ++i )
8944 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8945 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8946 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8948 vecs.back() = vecs[0];
8949 center /= _simplices.size();
8951 gp_XYZ zAxis(0,0,0);
8952 for ( i = 0; i < _simplices.size(); ++i )
8953 zAxis += vecs[i] ^ vecs[i+1];
8956 for ( i = 0; i < _simplices.size(); ++i )
8959 if ( yAxis.SquareModulus() > tol )
8962 gp_XYZ xAxis = yAxis ^ zAxis;
8963 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8964 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8965 // p0.Distance( _simplices[2]._nPrev ));
8966 // gp_XYZ center = smoothLaplacian();
8967 // gp_XYZ xAxis, yAxis, zAxis;
8968 // for ( i = 0; i < _simplices.size(); ++i )
8970 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8971 // if ( xAxis.SquareModulus() > tol*tol )
8974 // for ( i = 1; i < _simplices.size(); ++i )
8976 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8977 // zAxis = xAxis ^ yAxis;
8978 // if ( zAxis.SquareModulus() > tol*tol )
8981 // if ( i == _simplices.size() ) return newPos;
8983 yAxis = zAxis ^ xAxis;
8984 xAxis /= xAxis.Modulus();
8985 yAxis /= yAxis.Modulus();
8987 // get half-planes of _simplices
8989 vector< _halfPlane > halfPlns( _simplices.size() );
8991 for ( size_t i = 0; i < _simplices.size(); ++i )
8993 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8994 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8995 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8996 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8997 gp_XY vec12 = p2 - p1;
8998 double dist12 = vec12.Modulus();
9002 halfPlns[ nbHP ]._pos = p1;
9003 halfPlns[ nbHP ]._dir = vec12;
9004 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9008 // intersect boundaries of half-planes, define state of intersection points
9009 // in relation to all half-planes and calculate internal point of a 2D polygon
9012 gp_XY newPos2D (0,0);
9014 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9015 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9016 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9018 vector< vector< TIntPntState > > allIntPnts( nbHP );
9019 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9021 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9022 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9024 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9025 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9028 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9030 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9032 if ( iHP1 == iHP2 ) continue;
9034 TIntPntState & ips1 = intPnts1[ iHP2 ];
9035 if ( ips1.second == UNDEF )
9037 // find an intersection point of boundaries of iHP1 and iHP2
9039 if ( iHP2 == iPrev ) // intersection with neighbors is known
9040 ips1.first = halfPlns[ iHP1 ]._pos;
9041 else if ( iHP2 == iNext )
9042 ips1.first = halfPlns[ iHP2 ]._pos;
9043 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9044 ips1.second = NO_INT;
9046 // classify the found intersection point
9047 if ( ips1.second != NO_INT )
9049 ips1.second = NOT_OUT;
9050 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9051 if ( i != iHP1 && i != iHP2 &&
9052 halfPlns[ i ].IsOut( ips1.first, tol ))
9053 ips1.second = IS_OUT;
9055 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9056 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9057 TIntPntState & ips2 = intPnts2[ iHP1 ];
9060 if ( ips1.second == NOT_OUT )
9063 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9067 // find a NOT_OUT segment of boundary which is located between
9068 // two NOT_OUT int points
9071 continue; // no such a segment
9075 // sort points along the boundary
9076 map< double, TIntPntState* > ipsByParam;
9077 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9079 TIntPntState & ips1 = intPnts1[ iHP2 ];
9080 if ( ips1.second != NO_INT )
9082 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9083 double param = op * halfPlns[ iHP1 ]._dir;
9084 ipsByParam.insert( make_pair( param, & ips1 ));
9087 // look for two neighboring NOT_OUT points
9089 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9090 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9092 TIntPntState & ips1 = *(u2ips->second);
9093 if ( ips1.second == NOT_OUT )
9094 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9095 else if ( nbNotOut >= 2 )
9102 if ( nbNotOut >= 2 )
9104 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9107 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9114 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9123 #else // OLD_NEF_POLYGON
9124 { ////////////////////////////////// NEW
9125 gp_XYZ newPos(0,0,0);
9127 // get a plane to search a solution on
9130 gp_XYZ center(0,0,0);
9131 for ( i = 0; i < _simplices.size(); ++i )
9132 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9133 center /= _simplices.size();
9135 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9136 for ( i = 0; i < _simplices.size(); ++i )
9137 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9138 vecs.back() = vecs[0];
9140 const double tol = numeric_limits<double>::min();
9141 gp_XYZ zAxis(0,0,0);
9142 for ( i = 0; i < _simplices.size(); ++i )
9144 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9147 if ( cross * zAxis < tol )
9148 zAxis += cross.Reversed();
9152 catch (Standard_Failure) { // if |cross| == 0.
9157 for ( i = 0; i < _simplices.size(); ++i )
9160 if ( yAxis.SquareModulus() > tol )
9163 gp_XYZ xAxis = yAxis ^ zAxis;
9164 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9165 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9166 // p0.Distance( _simplices[2]._nPrev ));
9167 // gp_XYZ center = smoothLaplacian();
9168 // gp_XYZ xAxis, yAxis, zAxis;
9169 // for ( i = 0; i < _simplices.size(); ++i )
9171 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9172 // if ( xAxis.SquareModulus() > tol*tol )
9175 // for ( i = 1; i < _simplices.size(); ++i )
9177 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9178 // zAxis = xAxis ^ yAxis;
9179 // if ( zAxis.SquareModulus() > tol*tol )
9182 // if ( i == _simplices.size() ) return newPos;
9184 yAxis = zAxis ^ xAxis;
9185 xAxis /= xAxis.Modulus();
9186 yAxis /= yAxis.Modulus();
9188 // get half-planes of _simplices
9190 vector< _halfPlane > halfPlns( _simplices.size() );
9192 for ( size_t i = 0; i < _simplices.size(); ++i )
9194 const gp_XYZ& OP1 = vecs[ i ];
9195 const gp_XYZ& OP2 = vecs[ i+1 ];
9196 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9197 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9198 gp_XY vec12 = p2 - p1;
9199 double dist12 = vec12.Modulus();
9203 halfPlns[ nbHP ]._pos = p1;
9204 halfPlns[ nbHP ]._dir = vec12;
9205 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9209 // intersect boundaries of half-planes, define state of intersection points
9210 // in relation to all half-planes and calculate internal point of a 2D polygon
9213 gp_XY newPos2D (0,0);
9215 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9216 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9217 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9219 vector< vector< TIntPntState > > allIntPnts( nbHP );
9220 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9222 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9223 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9225 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9226 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9229 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9231 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9233 if ( iHP1 == iHP2 ) continue;
9235 TIntPntState & ips1 = intPnts1[ iHP2 ];
9236 if ( ips1.second == UNDEF )
9238 // find an intersection point of boundaries of iHP1 and iHP2
9240 if ( iHP2 == iPrev ) // intersection with neighbors is known
9241 ips1.first = halfPlns[ iHP1 ]._pos;
9242 else if ( iHP2 == iNext )
9243 ips1.first = halfPlns[ iHP2 ]._pos;
9244 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9245 ips1.second = NO_INT;
9247 // classify the found intersection point
9248 if ( ips1.second != NO_INT )
9250 ips1.second = NOT_OUT;
9251 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9252 if ( i != iHP1 && i != iHP2 &&
9253 halfPlns[ i ].IsOut( ips1.first, tol ))
9254 ips1.second = IS_OUT;
9256 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9257 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9258 TIntPntState & ips2 = intPnts2[ iHP1 ];
9261 if ( ips1.second == NOT_OUT )
9264 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9268 // find a NOT_OUT segment of boundary which is located between
9269 // two NOT_OUT int points
9272 continue; // no such a segment
9276 // sort points along the boundary
9277 map< double, TIntPntState* > ipsByParam;
9278 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9280 TIntPntState & ips1 = intPnts1[ iHP2 ];
9281 if ( ips1.second != NO_INT )
9283 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9284 double param = op * halfPlns[ iHP1 ]._dir;
9285 ipsByParam.insert( make_pair( param, & ips1 ));
9288 // look for two neighboring NOT_OUT points
9290 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9291 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9293 TIntPntState & ips1 = *(u2ips->second);
9294 if ( ips1.second == NOT_OUT )
9295 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9296 else if ( nbNotOut >= 2 )
9303 if ( nbNotOut >= 2 )
9305 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9308 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9315 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9324 #endif // OLD_NEF_POLYGON
9326 //================================================================================
9328 * \brief Add a new segment to _LayerEdge during inflation
9330 //================================================================================
9332 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9337 if ( len > _maxLen )
9340 Block( eos.GetData() );
9342 const double lenDelta = len - _len;
9343 if ( lenDelta < len * 1e-3 )
9345 Block( eos.GetData() );
9349 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9350 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9352 if ( eos._hyp.IsOffsetMethod() )
9356 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9357 while ( faceIt->more() )
9359 const SMDS_MeshElement* face = faceIt->next();
9360 if ( !eos.GetNormal( face, faceNorm ))
9363 // translate plane of a face
9364 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9366 // find point of intersection of the face plane located at baryCenter
9367 // and _normal located at newXYZ
9368 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9369 double dot = ( faceNorm.XYZ() * _normal );
9370 if ( dot < std::numeric_limits<double>::min() )
9371 dot = lenDelta * 1e-3;
9372 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9373 newXYZ += step * _normal;
9375 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9379 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9382 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9383 _pos.push_back( newXYZ );
9385 if ( !eos._sWOL.IsNull() )
9389 if ( eos.SWOLType() == TopAbs_EDGE )
9391 double u = Precision::Infinite(); // to force projection w/o distance check
9392 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9393 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9394 _pos.back().SetCoord( u, 0, 0 );
9395 if ( _nodes.size() > 1 && uvOK )
9397 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9398 pos->SetUParameter( u );
9403 gp_XY uv( Precision::Infinite(), 0 );
9404 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9405 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9406 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9407 if ( _nodes.size() > 1 && uvOK )
9409 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9410 pos->SetUParameter( uv.X() );
9411 pos->SetVParameter( uv.Y() );
9416 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9420 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9422 Block( eos.GetData() );
9430 if ( eos.ShapeType() != TopAbs_FACE )
9432 for ( size_t i = 0; i < _neibors.size(); ++i )
9433 //if ( _len > _neibors[i]->GetSmooLen() )
9434 _neibors[i]->Set( MOVED );
9438 dumpMove( n ); //debug
9441 //================================================================================
9443 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9445 //================================================================================
9447 void _LayerEdge::Block( _SolidData& data )
9449 //if ( Is( BLOCKED )) return;
9452 SMESH_Comment msg( "#BLOCK shape=");
9453 msg << data.GetShapeEdges( this )->_shapeID
9454 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9455 dumpCmd( msg + " -- BEGIN")
9458 std::queue<_LayerEdge*> queue;
9461 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9462 while ( !queue.empty() )
9464 _LayerEdge* edge = queue.front(); queue.pop();
9465 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9466 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9467 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9469 _LayerEdge* neibor = edge->_neibors[iN];
9470 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9472 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9473 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9474 double minDist = pSrc.SquareDistance( pSrcN );
9475 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9476 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9477 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9478 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9479 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9481 newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9482 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9483 // neibor->_lenFactor / edge->_lenFactor );
9485 if ( neibor->_maxLen > newMaxLen )
9487 neibor->_maxLen = newMaxLen;
9488 if ( neibor->_maxLen < neibor->_len )
9490 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9491 while ( neibor->_len > neibor->_maxLen &&
9492 neibor->NbSteps() > 1 )
9493 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9494 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9495 //neibor->Block( data );
9497 queue.push( neibor );
9501 dumpCmd( msg + " -- END")
9504 //================================================================================
9506 * \brief Remove last inflation step
9508 //================================================================================
9510 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9512 if ( _pos.size() > curStep && _nodes.size() > 1 )
9514 _pos.resize( curStep );
9516 gp_Pnt nXYZ = _pos.back();
9517 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9518 SMESH_TNodeXYZ curXYZ( n );
9519 if ( !eos._sWOL.IsNull() )
9521 TopLoc_Location loc;
9522 if ( eos.SWOLType() == TopAbs_EDGE )
9524 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9525 pos->SetUParameter( nXYZ.X() );
9527 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9528 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9532 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9533 pos->SetUParameter( nXYZ.X() );
9534 pos->SetVParameter( nXYZ.Y() );
9535 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9536 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9539 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9542 if ( restoreLength )
9544 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9549 //================================================================================
9551 * \brief Return index of a _pos distant from _normal
9553 //================================================================================
9555 int _LayerEdge::GetSmoothedPos( const double tol )
9558 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9560 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9561 if ( normDist > tol * tol )
9567 //================================================================================
9569 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9571 //================================================================================
9573 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9575 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9578 // find the 1st smoothed _pos
9579 int iSmoothed = GetSmoothedPos( tol );
9580 if ( !iSmoothed ) return;
9582 //if ( 1 || Is( DISTORTED ))
9584 gp_XYZ normal = _normal;
9585 if ( Is( NORMAL_UPDATED ))
9586 for ( size_t i = 1; i < _pos.size(); ++i )
9588 normal = _pos[i] - _pos[0];
9589 double size = normal.Modulus();
9590 if ( size > RealSmall() )
9596 const double r = 0.2;
9597 for ( int iter = 0; iter < 50; ++iter )
9600 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9602 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9603 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9605 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9606 double newLen = ( 1-r ) * midLen + r * segLen[i];
9607 const_cast< double& >( segLen[i] ) = newLen;
9608 // check angle between normal and (_pos[i+1], _pos[i] )
9609 gp_XYZ posDir = _pos[i+1] - _pos[i];
9610 double size = posDir.SquareModulus();
9611 if ( size > RealSmall() )
9612 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9614 if ( minDot > 0.5 * 0.5 )
9620 // for ( size_t i = 1; i < _pos.size()-1; ++i )
9622 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
9625 // double wgt = segLen[i] / segLen.back();
9626 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9627 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
9628 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
9629 // _pos[i] = newPos;
9634 //================================================================================
9636 * \brief Print flags
9638 //================================================================================
9640 std::string _LayerEdge::DumpFlags() const
9643 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9644 if ( _flags & flag )
9646 EFlags f = (EFlags) flag;
9648 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
9649 case MOVED: dump << "MOVED"; break;
9650 case SMOOTHED: dump << "SMOOTHED"; break;
9651 case DIFFICULT: dump << "DIFFICULT"; break;
9652 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9653 case BLOCKED: dump << "BLOCKED"; break;
9654 case INTERSECTED: dump << "INTERSECTED"; break;
9655 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
9656 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9657 case MARKED: dump << "MARKED"; break;
9658 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
9659 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
9660 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
9661 case DISTORTED: dump << "DISTORTED"; break;
9662 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
9663 case SHRUNK: dump << "SHRUNK"; break;
9664 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
9668 cout << dump << endl;
9672 //================================================================================
9677 //================================================================================
9679 bool _ViscousBuilder::refine(_SolidData& data)
9681 SMESH_MesherHelper& helper = data.GetHelper();
9682 helper.SetElementsOnShape(false);
9684 Handle(Geom_Curve) curve;
9685 Handle(ShapeAnalysis_Surface) surface;
9686 TopoDS_Edge geomEdge;
9687 TopoDS_Face geomFace;
9688 TopLoc_Location loc;
9691 vector< gp_XYZ > pos3D;
9692 bool isOnEdge, isTooConvexFace = false;
9693 TGeomID prevBaseId = -1;
9694 TNode2Edge* n2eMap = 0;
9695 TNode2Edge::iterator n2e;
9697 // Create intermediate nodes on each _LayerEdge
9699 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9701 _EdgesOnShape& eos = data._edgesOnShape[iS];
9702 if ( eos._edges.empty() ) continue;
9704 if ( eos._edges[0]->_nodes.size() < 2 )
9705 continue; // on _noShrinkShapes
9707 // get data of a shrink shape
9709 geomEdge.Nullify(); geomFace.Nullify();
9710 curve.Nullify(); surface.Nullify();
9711 if ( !eos._sWOL.IsNull() )
9713 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9716 geomEdge = TopoDS::Edge( eos._sWOL );
9717 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9721 geomFace = TopoDS::Face( eos._sWOL );
9722 surface = helper.GetSurface( geomFace );
9725 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9727 geomFace = TopoDS::Face( eos._shape );
9728 surface = helper.GetSurface( geomFace );
9729 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9730 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9732 eos._eosC1[ i ]->_toSmooth = true;
9733 for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9734 eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9736 isTooConvexFace = false;
9737 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9738 isTooConvexFace = cf->_isTooCurved;
9741 vector< double > segLen;
9742 for ( size_t i = 0; i < eos._edges.size(); ++i )
9744 _LayerEdge& edge = *eos._edges[i];
9745 if ( edge._pos.size() < 2 )
9748 // get accumulated length of segments
9749 segLen.resize( edge._pos.size() );
9751 if ( eos._sWOL.IsNull() )
9753 bool useNormal = true;
9754 bool usePos = false;
9755 bool smoothed = false;
9756 double preci = 0.1 * edge._len;
9757 if ( eos._toSmooth && edge._pos.size() > 2 )
9759 smoothed = edge.GetSmoothedPos( preci );
9763 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9765 useNormal = usePos = false;
9766 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9767 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9769 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9770 if ( surface->Gap() < 2. * edge._len )
9771 segLen[j] = surface->Gap();
9777 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9779 #ifndef __NODES_AT_POS
9780 useNormal = usePos = false;
9781 edge._pos[1] = edge._pos.back();
9782 edge._pos.resize( 2 );
9784 segLen[ 1 ] = edge._len;
9787 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9789 useNormal = usePos = false;
9790 _LayerEdge tmpEdge; // get original _normal
9791 tmpEdge._nodes.push_back( edge._nodes[0] );
9792 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9795 for ( size_t j = 1; j < edge._pos.size(); ++j )
9796 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9800 for ( size_t j = 1; j < edge._pos.size(); ++j )
9801 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9805 for ( size_t j = 1; j < edge._pos.size(); ++j )
9806 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9810 bool swapped = ( edge._pos.size() > 2 );
9814 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9815 if ( segLen[j] > segLen.back() )
9817 segLen.erase( segLen.begin() + j );
9818 edge._pos.erase( edge._pos.begin() + j );
9821 else if ( segLen[j] < segLen[j-1] )
9823 std::swap( segLen[j], segLen[j-1] );
9824 std::swap( edge._pos[j], edge._pos[j-1] );
9829 // smooth a path formed by edge._pos
9830 #ifndef __NODES_AT_POS
9831 if (( smoothed ) /*&&
9832 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9833 edge.SmoothPos( segLen, preci );
9836 else if ( eos._isRegularSWOL ) // usual SWOL
9838 if ( edge.Is( _LayerEdge::SMOOTHED ))
9840 SMESH_NodeXYZ p0( edge._nodes[0] );
9841 for ( size_t j = 1; j < edge._pos.size(); ++j )
9843 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9844 segLen[j] = ( pj - p0 ) * edge._normal;
9849 for ( size_t j = 1; j < edge._pos.size(); ++j )
9850 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9853 else if ( !surface.IsNull() ) // SWOL surface with singularities
9855 pos3D.resize( edge._pos.size() );
9856 for ( size_t j = 0; j < edge._pos.size(); ++j )
9857 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9859 for ( size_t j = 1; j < edge._pos.size(); ++j )
9860 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9863 // allocate memory for new nodes if it is not yet refined
9864 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9865 if ( edge._nodes.size() == 2 )
9867 #ifdef __NODES_AT_POS
9868 int nbNodes = edge._pos.size();
9870 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9872 edge._nodes.resize( nbNodes, 0 );
9874 edge._nodes.back() = tgtNode;
9876 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9877 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9878 if ( baseShapeId != prevBaseId )
9880 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9881 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9882 prevBaseId = baseShapeId;
9884 _LayerEdge* edgeOnSameNode = 0;
9885 bool useExistingPos = false;
9886 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9888 edgeOnSameNode = n2e->second;
9889 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9890 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9891 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9894 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9895 epos->SetUParameter( otherTgtPos.X() );
9899 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9900 fpos->SetUParameter( otherTgtPos.X() );
9901 fpos->SetVParameter( otherTgtPos.Y() );
9904 // calculate height of the first layer
9906 const double T = segLen.back(); //data._hyp.GetTotalThickness();
9907 const double f = eos._hyp.GetStretchFactor();
9908 const int N = eos._hyp.GetNumberLayers();
9909 const double fPowN = pow( f, N );
9910 if ( fPowN - 1 <= numeric_limits<double>::min() )
9913 h0 = T * ( f - 1 )/( fPowN - 1 );
9915 const double zeroLen = std::numeric_limits<double>::min();
9917 // create intermediate nodes
9918 double hSum = 0, hi = h0/f;
9920 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9922 // compute an intermediate position
9925 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9927 int iPrevSeg = iSeg-1;
9928 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9930 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9931 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9932 #ifdef __NODES_AT_POS
9933 pos = edge._pos[ iStep ];
9935 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9936 if ( !eos._sWOL.IsNull() )
9938 // compute XYZ by parameters <pos>
9943 pos = curve->Value( u ).Transformed(loc);
9945 else if ( eos._isRegularSWOL )
9947 uv.SetCoord( pos.X(), pos.Y() );
9949 pos = surface->Value( pos.X(), pos.Y() );
9953 uv.SetCoord( pos.X(), pos.Y() );
9954 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9955 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9957 pos = surface->Value( uv );
9960 // create or update the node
9963 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9964 if ( !eos._sWOL.IsNull() )
9967 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9969 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9973 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9978 if ( !eos._sWOL.IsNull() )
9980 // make average pos from new and current parameters
9983 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9984 if ( useExistingPos )
9985 u = helper.GetNodeU( geomEdge, node );
9986 pos = curve->Value( u ).Transformed(loc);
9988 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9989 epos->SetUParameter( u );
9993 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9994 if ( useExistingPos )
9995 uv = helper.GetNodeUV( geomFace, node );
9996 pos = surface->Value( uv );
9998 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9999 fpos->SetUParameter( uv.X() );
10000 fpos->SetVParameter( uv.Y() );
10003 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10005 } // loop on edge._nodes
10007 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10010 edge._pos.back().SetCoord( u, 0,0);
10012 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10014 if ( edgeOnSameNode )
10015 edgeOnSameNode->_pos.back() = edge._pos.back();
10018 } // loop on eos._edges to create nodes
10021 if ( !getMeshDS()->IsEmbeddedMode() )
10022 // Log node movement
10023 for ( size_t i = 0; i < eos._edges.size(); ++i )
10025 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10026 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10033 helper.SetElementsOnShape(true);
10035 vector< vector<const SMDS_MeshNode*>* > nnVec;
10036 set< vector<const SMDS_MeshNode*>* > nnSet;
10037 set< int > degenEdgeInd;
10038 vector<const SMDS_MeshElement*> degenVols;
10040 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10041 for ( ; exp.More(); exp.Next() )
10043 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10044 if ( data._ignoreFaceIds.count( faceID ))
10046 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10047 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10048 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10049 while ( fIt->more() )
10051 const SMDS_MeshElement* face = fIt->next();
10052 const int nbNodes = face->NbCornerNodes();
10053 nnVec.resize( nbNodes );
10055 degenEdgeInd.clear();
10056 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10057 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10058 for ( int iN = 0; iN < nbNodes; ++iN )
10060 const SMDS_MeshNode* n = nIt->next();
10061 _LayerEdge* edge = data._n2eMap[ n ];
10062 const int i = isReversedFace ? nbNodes-1-iN : iN;
10063 nnVec[ i ] = & edge->_nodes;
10064 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10065 minZ = std::min( minZ, nnVec[ i ]->size() );
10067 if ( helper.HasDegeneratedEdges() )
10068 nnSet.insert( nnVec[ i ]);
10073 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10081 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10082 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10083 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10085 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10087 for ( int iN = 0; iN < nbNodes; ++iN )
10088 if ( nnVec[ iN ]->size() < iZ+1 )
10089 degenEdgeInd.insert( iN );
10091 if ( degenEdgeInd.size() == 1 ) // PYRAM
10093 int i2 = *degenEdgeInd.begin();
10094 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10095 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10096 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10097 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10101 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10102 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10103 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10104 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10105 (*nnVec[ i3 ])[ iZ ]);
10113 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10114 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10115 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10116 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10117 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10119 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10121 for ( int iN = 0; iN < nbNodes; ++iN )
10122 if ( nnVec[ iN ]->size() < iZ+1 )
10123 degenEdgeInd.insert( iN );
10125 switch ( degenEdgeInd.size() )
10129 int i2 = *degenEdgeInd.begin();
10130 int i3 = *degenEdgeInd.rbegin();
10131 bool ok = ( i3 - i2 == 1 );
10132 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10133 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10134 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10136 const SMDS_MeshElement* vol =
10137 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10138 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10140 degenVols.push_back( vol );
10144 default: // degen HEX
10146 const SMDS_MeshElement* vol =
10147 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10148 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10149 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10150 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10151 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10152 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10153 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10154 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10155 degenVols.push_back( vol );
10162 return error("Not supported type of element", data._index);
10164 } // switch ( nbNodes )
10165 } // while ( fIt->more() )
10168 if ( !degenVols.empty() )
10170 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10171 if ( !err || err->IsOK() )
10173 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
10174 "Bad quality volumes created" ));
10175 err->myBadElements.insert( err->myBadElements.end(),
10176 degenVols.begin(),degenVols.end() );
10183 //================================================================================
10185 * \brief Shrink 2D mesh on faces to let space for inflated layers
10187 //================================================================================
10189 bool _ViscousBuilder::shrink(_SolidData& theData)
10191 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10192 // _LayerEdge's inflated along FACE or EDGE)
10193 map< TGeomID, list< _SolidData* > > f2sdMap;
10194 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10196 _SolidData& data = _sdVec[i];
10197 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10198 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10199 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10201 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10203 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10204 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10205 // by StdMeshers_QuadToTriaAdaptor
10206 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10208 SMESH_ProxyMesh::SubMesh* proxySub =
10209 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10210 if ( proxySub->NbElements() == 0 )
10212 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10213 while ( fIt->more() )
10215 const SMDS_MeshElement* f = fIt->next();
10216 // as a result 3D algo will use elements from proxySub and not from smDS
10217 proxySub->AddElement( f );
10218 f->setIsMarked( true );
10220 // Mark nodes on the FACE to discriminate them from nodes
10221 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10222 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10224 const SMDS_MeshNode* n = f->GetNode( iN );
10225 if ( n->GetPosition()->GetDim() == 2 )
10226 n->setIsMarked( true );
10234 SMESH_MesherHelper helper( *_mesh );
10235 helper.ToFixNodeParameters( true );
10238 map< TGeomID, _Shrinker1D > e2shrMap;
10239 vector< _EdgesOnShape* > subEOS;
10240 vector< _LayerEdge* > lEdges;
10242 // loop on FACEs to srink mesh on
10243 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10244 for ( ; f2sd != f2sdMap.end(); ++f2sd )
10246 list< _SolidData* > & dataList = f2sd->second;
10247 if ( dataList.front()->_n2eMap.empty() ||
10248 dataList.back() ->_n2eMap.empty() )
10249 continue; // not yet computed
10250 if ( dataList.front() != &theData &&
10251 dataList.back() != &theData )
10254 _SolidData& data = *dataList.front();
10255 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
10256 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10257 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
10258 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10260 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10262 _shrinkedFaces.Add( F );
10263 helper.SetSubShape( F );
10265 // ===========================
10266 // Prepare data for shrinking
10267 // ===========================
10269 // Collect nodes to smooth (they are marked at the beginning of this method)
10270 vector < const SMDS_MeshNode* > smoothNodes;
10272 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10273 while ( nIt->more() )
10275 const SMDS_MeshNode* n = nIt->next();
10276 if ( n->isMarked() )
10277 smoothNodes.push_back( n );
10280 // Find out face orientation
10281 double refSign = 1;
10282 const set<TGeomID> ignoreShapes;
10284 if ( !smoothNodes.empty() )
10286 vector<_Simplex> simplices;
10287 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10288 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10289 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10290 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10291 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10295 // Find _LayerEdge's inflated along F
10299 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10300 /*complexFirst=*/true); //!!!
10301 while ( subIt->more() )
10303 const TGeomID subID = subIt->next()->GetId();
10304 if ( data._noShrinkShapes.count( subID ))
10306 _EdgesOnShape* eos = data.GetShapeEdges( subID );
10307 if ( !eos || eos->_sWOL.IsNull() )
10308 if ( data2 ) // check in adjacent SOLID
10310 eos = data2->GetShapeEdges( subID );
10311 if ( !eos || eos->_sWOL.IsNull() )
10314 subEOS.push_back( eos );
10316 for ( size_t i = 0; i < eos->_edges.size(); ++i )
10318 lEdges.push_back( eos->_edges[ i ] );
10319 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10324 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10325 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10326 while ( fIt->more() )
10327 if ( const SMDS_MeshElement* f = fIt->next() )
10328 dumpChangeNodes( f );
10331 // Replace source nodes by target nodes in mesh faces to shrink
10332 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10333 const SMDS_MeshNode* nodes[20];
10334 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10336 _EdgesOnShape& eos = * subEOS[ iS ];
10337 for ( size_t i = 0; i < eos._edges.size(); ++i )
10339 _LayerEdge& edge = *eos._edges[i];
10340 const SMDS_MeshNode* srcNode = edge._nodes[0];
10341 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10342 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10343 while ( fIt->more() )
10345 const SMDS_MeshElement* f = fIt->next();
10346 if ( !smDS->Contains( f ) || !f->isMarked() )
10348 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10349 for ( int iN = 0; nIt->more(); ++iN )
10351 const SMDS_MeshNode* n = nIt->next();
10352 nodes[iN] = ( n == srcNode ? tgtNode : n );
10354 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10355 dumpChangeNodes( f );
10361 // find out if a FACE is concave
10362 const bool isConcaveFace = isConcave( F, helper );
10364 // Create _SmoothNode's on face F
10365 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10367 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10368 const bool sortSimplices = isConcaveFace;
10369 for ( size_t i = 0; i < smoothNodes.size(); ++i )
10371 const SMDS_MeshNode* n = smoothNodes[i];
10372 nodesToSmooth[ i ]._node = n;
10373 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10374 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10375 // fix up incorrect uv of nodes on the FACE
10376 helper.GetNodeUV( F, n, 0, &isOkUV);
10381 //if ( nodesToSmooth.empty() ) continue;
10383 // Find EDGE's to shrink and set simpices to LayerEdge's
10384 set< _Shrinker1D* > eShri1D;
10386 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10388 _EdgesOnShape& eos = * subEOS[ iS ];
10389 if ( eos.SWOLType() == TopAbs_EDGE )
10391 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10392 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
10393 eShri1D.insert( & srinker );
10394 srinker.AddEdge( eos._edges[0], eos, helper );
10395 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10396 // restore params of nodes on EGDE if the EDGE has been already
10397 // srinked while srinking other FACE
10398 srinker.RestoreParams();
10400 for ( size_t i = 0; i < eos._edges.size(); ++i )
10402 _LayerEdge& edge = * eos._edges[i];
10403 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10405 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10406 // not-marked nodes are those added by refine()
10407 edge._nodes.back()->setIsMarked( true );
10412 bool toFixTria = false; // to improve quality of trias by diagonal swap
10413 if ( isConcaveFace )
10415 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10416 if ( hasTria != hasQuad ) {
10417 toFixTria = hasTria;
10420 set<int> nbNodesSet;
10421 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10422 while ( fIt->more() && nbNodesSet.size() < 2 )
10423 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10424 toFixTria = ( *nbNodesSet.begin() == 3 );
10428 // ==================
10429 // Perform shrinking
10430 // ==================
10432 bool shrinked = true;
10433 int nbBad, shriStep=0, smooStep=0;
10434 _SmoothNode::SmoothType smoothType
10435 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10436 SMESH_Comment errMsg;
10440 // Move boundary nodes (actually just set new UV)
10441 // -----------------------------------------------
10442 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10444 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10446 _EdgesOnShape& eos = * subEOS[ iS ];
10447 for ( size_t i = 0; i < eos._edges.size(); ++i )
10449 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10454 // Move nodes on EDGE's
10455 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10456 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10457 for ( ; shr != eShri1D.end(); ++shr )
10458 (*shr)->Compute( /*set3D=*/false, helper );
10461 // -----------------
10462 int nbNoImpSteps = 0;
10465 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10467 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10469 int oldBadNb = nbBad;
10472 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10473 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10474 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10476 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10477 smooTy, /*set3D=*/isConcaveFace);
10479 if ( nbBad < oldBadNb )
10489 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10490 if ( shriStep > 200 )
10491 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10492 if ( !errMsg.empty() )
10495 // Fix narrow triangles by swapping diagonals
10496 // ---------------------------------------
10499 set<const SMDS_MeshNode*> usedNodes;
10500 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10502 // update working data
10503 set<const SMDS_MeshNode*>::iterator n;
10504 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10506 n = usedNodes.find( nodesToSmooth[ i ]._node );
10507 if ( n != usedNodes.end())
10509 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10510 nodesToSmooth[ i ]._simplices,
10511 ignoreShapes, NULL,
10512 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10513 usedNodes.erase( n );
10516 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10518 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10519 if ( n != usedNodes.end())
10521 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10522 lEdges[i]->_simplices,
10524 usedNodes.erase( n );
10528 // TODO: check effect of this additional smooth
10529 // additional laplacian smooth to increase allowed shrink step
10530 // for ( int st = 1; st; --st )
10532 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10533 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10535 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10536 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10540 } // while ( shrinked )
10542 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10544 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10547 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10549 vector< const SMDS_MeshElement* > facesToRm;
10552 facesToRm.reserve( psm->NbElements() );
10553 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10554 facesToRm.push_back( ite->next() );
10556 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10557 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10560 for ( size_t i = 0; i < facesToRm.size(); ++i )
10561 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10565 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10566 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10567 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10568 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10569 subEOS[iS]->_edges[i]->_nodes.end() );
10571 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10572 while ( itn->more() ) {
10573 const SMDS_MeshNode* n = itn->next();
10574 if ( !nodesToKeep.count( n ))
10575 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10578 // restore position and UV of target nodes
10580 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10581 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10583 _LayerEdge* edge = subEOS[iS]->_edges[i];
10584 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10585 if ( edge->_pos.empty() ||
10586 edge->Is( _LayerEdge::SHRUNK )) continue;
10587 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10589 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10590 pos->SetUParameter( edge->_pos[0].X() );
10591 pos->SetVParameter( edge->_pos[0].Y() );
10592 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10596 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10597 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10598 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10600 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10601 dumpMove( tgtNode );
10603 // shrink EDGE sub-meshes and set proxy sub-meshes
10604 UVPtStructVec uvPtVec;
10605 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10606 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10608 _Shrinker1D* shr = (*shrIt);
10609 shr->Compute( /*set3D=*/true, helper );
10611 // set proxy mesh of EDGEs w/o layers
10612 map< double, const SMDS_MeshNode* > nodes;
10613 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10614 // remove refinement nodes
10615 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10616 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10617 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10618 if ( u2n->second == sn0 || u2n->second == sn1 )
10620 while ( u2n->second != tn0 && u2n->second != tn1 )
10622 nodes.erase( nodes.begin(), u2n );
10624 u2n = --nodes.end();
10625 if ( u2n->second == sn0 || u2n->second == sn1 )
10627 while ( u2n->second != tn0 && u2n->second != tn1 )
10629 nodes.erase( ++u2n, nodes.end() );
10631 // set proxy sub-mesh
10632 uvPtVec.resize( nodes.size() );
10633 u2n = nodes.begin();
10634 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10635 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10637 uvPtVec[ i ].node = u2n->second;
10638 uvPtVec[ i ].param = u2n->first;
10639 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10641 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10642 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10645 // set proxy mesh of EDGEs with layers
10646 vector< _LayerEdge* > edges;
10647 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10649 _EdgesOnShape& eos = * subEOS[ iS ];
10650 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10652 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10653 data.SortOnEdge( E, eos._edges );
10656 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10657 if ( !eov->_edges.empty() )
10658 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10660 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10662 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10663 if ( !eov->_edges.empty() )
10664 edges.push_back( eov->_edges[0] ); // on last VERTEX
10666 uvPtVec.resize( edges.size() );
10667 for ( size_t i = 0; i < edges.size(); ++i )
10669 uvPtVec[ i ].node = edges[i]->_nodes.back();
10670 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10671 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10673 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10674 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10675 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10677 // temporary clear the FACE sub-mesh from faces made by refine()
10678 vector< const SMDS_MeshElement* > elems;
10679 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10680 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10681 elems.push_back( ite->next() );
10682 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10683 elems.push_back( ite->next() );
10686 // compute the mesh on the FACE
10687 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10688 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10690 // re-fill proxy sub-meshes of the FACE
10691 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10692 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10693 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10694 psm->AddElement( ite->next() );
10697 for ( size_t i = 0; i < elems.size(); ++i )
10698 smDS->AddElement( elems[i] );
10700 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10701 return error( errMsg );
10703 } // end of re-meshing in case of failed smoothing
10706 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10707 bool isStructuredFixed = false;
10708 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10709 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10710 if ( !isStructuredFixed )
10712 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10713 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10715 for ( int st = 3; st; --st )
10718 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10719 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10720 case 3: smoothType = _SmoothNode::ANGULAR; break;
10722 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10723 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10725 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10726 smoothType,/*set3D=*/st==1 );
10731 if ( !getMeshDS()->IsEmbeddedMode() )
10732 // Log node movement
10733 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10735 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10736 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10740 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10741 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10743 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10745 } // loop on FACES to srink mesh on
10748 // Replace source nodes by target nodes in shrinked mesh edges
10750 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10751 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10752 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10757 //================================================================================
10759 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10761 //================================================================================
10763 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10764 _EdgesOnShape& eos,
10765 SMESH_MesherHelper& helper,
10766 const SMESHDS_SubMesh* faceSubMesh)
10768 const SMDS_MeshNode* srcNode = edge._nodes[0];
10769 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10771 if ( eos.SWOLType() == TopAbs_FACE )
10773 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10776 edge.Set( _LayerEdge::SHRUNK );
10777 return srcNode == tgtNode;
10779 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10780 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10781 gp_Vec2d uvDir( srcUV, tgtUV );
10782 double uvLen = uvDir.Magnitude();
10784 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10787 //edge._pos.resize(1);
10788 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10790 // set UV of source node to target node
10791 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10792 pos->SetUParameter( srcUV.X() );
10793 pos->SetVParameter( srcUV.Y() );
10795 else // _sWOL is TopAbs_EDGE
10797 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10800 edge.Set( _LayerEdge::SHRUNK );
10801 return srcNode == tgtNode;
10803 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10804 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10805 if ( !edgeSM || edgeSM->NbElements() == 0 )
10806 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10808 const SMDS_MeshNode* n2 = 0;
10809 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10810 while ( eIt->more() && !n2 )
10812 const SMDS_MeshElement* e = eIt->next();
10813 if ( !edgeSM->Contains(e)) continue;
10814 n2 = e->GetNode( 0 );
10815 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10818 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10820 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10821 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10822 double u2 = helper.GetNodeU( E, n2, srcNode );
10824 //edge._pos.clear();
10826 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10828 // tgtNode is located so that it does not make faces with wrong orientation
10829 edge.Set( _LayerEdge::SHRUNK );
10832 //edge._pos.resize(1);
10833 edge._pos[0].SetCoord( U_TGT, uTgt );
10834 edge._pos[0].SetCoord( U_SRC, uSrc );
10835 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10837 edge._simplices.resize( 1 );
10838 edge._simplices[0]._nPrev = n2;
10840 // set U of source node to the target node
10841 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10842 pos->SetUParameter( uSrc );
10847 //================================================================================
10849 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10851 //================================================================================
10853 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10855 if ( edge._nodes.size() == 1 )
10860 const SMDS_MeshNode* srcNode = edge._nodes[0];
10861 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10862 if ( S.IsNull() ) return;
10866 switch ( S.ShapeType() )
10871 TopLoc_Location loc;
10872 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10873 if ( curve.IsNull() ) return;
10874 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10875 p = curve->Value( ePos->GetUParameter() );
10878 case TopAbs_VERTEX:
10880 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10885 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10886 dumpMove( srcNode );
10890 //================================================================================
10892 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10894 //================================================================================
10896 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10897 SMESH_MesherHelper& helper,
10900 set<const SMDS_MeshNode*> * involvedNodes)
10902 SMESH::Controls::AspectRatio qualifier;
10903 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10904 const double maxAspectRatio = is2D ? 4. : 2;
10905 _NodeCoordHelper xyz( F, helper, is2D );
10907 // find bad triangles
10909 vector< const SMDS_MeshElement* > badTrias;
10910 vector< double > badAspects;
10911 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
10912 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10913 while ( fIt->more() )
10915 const SMDS_MeshElement * f = fIt->next();
10916 if ( f->NbCornerNodes() != 3 ) continue;
10917 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10918 double aspect = qualifier.GetValue( points );
10919 if ( aspect > maxAspectRatio )
10921 badTrias.push_back( f );
10922 badAspects.push_back( aspect );
10927 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10928 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10929 while ( fIt->more() )
10931 const SMDS_MeshElement * f = fIt->next();
10932 if ( f->NbCornerNodes() == 3 )
10933 dumpChangeNodes( f );
10937 if ( badTrias.empty() )
10940 // find couples of faces to swap diagonal
10942 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10943 vector< T2Trias > triaCouples;
10945 TIDSortedElemSet involvedFaces, emptySet;
10946 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10949 double aspRatio [3];
10952 if ( !involvedFaces.insert( badTrias[iTia] ).second )
10954 for ( int iP = 0; iP < 3; ++iP )
10955 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10957 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10958 int bestCouple = -1;
10959 for ( int iSide = 0; iSide < 3; ++iSide )
10961 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10962 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10963 trias [iSide].first = badTrias[iTia];
10964 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10966 if (( ! trias[iSide].second ) ||
10967 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10968 ( ! sm->Contains( trias[iSide].second )))
10971 // aspect ratio of an adjacent tria
10972 for ( int iP = 0; iP < 3; ++iP )
10973 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10974 double aspectInit = qualifier.GetValue( points2 );
10976 // arrange nodes as after diag-swaping
10977 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10978 i3 = helper.WrapIndex( i1-1, 3 );
10980 i3 = helper.WrapIndex( i1+1, 3 );
10982 points1( 1+ iSide ) = points2( 1+ i3 );
10983 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
10985 // aspect ratio after diag-swaping
10986 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10987 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10990 // prevent inversion of a triangle
10991 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10992 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10993 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10996 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10997 bestCouple = iSide;
11000 if ( bestCouple >= 0 )
11002 triaCouples.push_back( trias[bestCouple] );
11003 involvedFaces.insert ( trias[bestCouple].second );
11007 involvedFaces.erase( badTrias[iTia] );
11010 if ( triaCouples.empty() )
11015 SMESH_MeshEditor editor( helper.GetMesh() );
11016 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11017 for ( size_t i = 0; i < triaCouples.size(); ++i )
11019 dumpChangeNodes( triaCouples[i].first );
11020 dumpChangeNodes( triaCouples[i].second );
11021 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11024 if ( involvedNodes )
11025 for ( size_t i = 0; i < triaCouples.size(); ++i )
11027 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11028 triaCouples[i].first->end_nodes() );
11029 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11030 triaCouples[i].second->end_nodes() );
11033 // just for debug dump resulting triangles
11034 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11035 for ( size_t i = 0; i < triaCouples.size(); ++i )
11037 dumpChangeNodes( triaCouples[i].first );
11038 dumpChangeNodes( triaCouples[i].second );
11042 //================================================================================
11044 * \brief Move target node to it's final position on the FACE during shrinking
11046 //================================================================================
11048 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11049 const TopoDS_Face& F,
11050 _EdgesOnShape& eos,
11051 SMESH_MesherHelper& helper )
11054 return false; // already at the target position
11056 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11058 if ( eos.SWOLType() == TopAbs_FACE )
11060 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
11061 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11062 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11063 const double uvLen = tgtUV.Distance( curUV );
11064 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11066 // Select shrinking step such that not to make faces with wrong orientation.
11067 double stepSize = 1e100;
11068 for ( size_t i = 0; i < _simplices.size(); ++i )
11070 if ( !_simplices[i]._nPrev->isMarked() ||
11071 !_simplices[i]._nNext->isMarked() )
11072 continue; // simplex of quadrangle created by addBoundaryElements()
11074 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11075 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11076 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11077 gp_XY dirN = uvN2 - uvN1;
11078 double det = uvDir.Crossed( dirN );
11079 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
11080 gp_XY dirN2Cur = curUV - uvN1;
11081 double step = dirN.Crossed( dirN2Cur ) / det;
11083 stepSize = Min( step, stepSize );
11086 if ( uvLen <= stepSize )
11092 else if ( stepSize > 0 )
11094 newUV = curUV + uvDir.XY() * stepSize * kSafe;
11100 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
11101 pos->SetUParameter( newUV.X() );
11102 pos->SetVParameter( newUV.Y() );
11105 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11106 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11107 dumpMove( tgtNode );
11110 else // _sWOL is TopAbs_EDGE
11112 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11113 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
11114 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
11116 const double u2 = helper.GetNodeU( E, n2, tgtNode );
11117 const double uSrc = _pos[0].Coord( U_SRC );
11118 const double lenTgt = _pos[0].Coord( LEN_TGT );
11120 double newU = _pos[0].Coord( U_TGT );
11121 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11123 Set( _LayerEdge::SHRUNK );
11128 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11130 tgtPos->SetUParameter( newU );
11132 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11133 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11134 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11135 dumpMove( tgtNode );
11142 //================================================================================
11144 * \brief Perform smooth on the FACE
11145 * \retval bool - true if the node has been moved
11147 //================================================================================
11149 bool _SmoothNode::Smooth(int& nbBad,
11150 Handle(Geom_Surface)& surface,
11151 SMESH_MesherHelper& helper,
11152 const double refSign,
11156 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11158 // get uv of surrounding nodes
11159 vector<gp_XY> uv( _simplices.size() );
11160 for ( size_t i = 0; i < _simplices.size(); ++i )
11161 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11163 // compute new UV for the node
11164 gp_XY newPos (0,0);
11165 if ( how == TFI && _simplices.size() == 4 )
11168 for ( size_t i = 0; i < _simplices.size(); ++i )
11169 if ( _simplices[i]._nOpp )
11170 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11172 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11174 newPos = helper.calcTFI ( 0.5, 0.5,
11175 corners[0], corners[1], corners[2], corners[3],
11176 uv[1], uv[2], uv[3], uv[0] );
11178 else if ( how == ANGULAR )
11180 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11182 else if ( how == CENTROIDAL && _simplices.size() > 3 )
11184 // average centers of diagonals wieghted with their reciprocal lengths
11185 if ( _simplices.size() == 4 )
11187 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11188 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11189 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11193 double sumWeight = 0;
11194 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11195 for ( int i = 0; i < nb; ++i )
11198 int iTo = i + _simplices.size() - 1;
11199 for ( int j = iFrom; j < iTo; ++j )
11201 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11202 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11204 newPos += w * ( uv[i]+uv[i2] );
11207 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11212 // Laplacian smooth
11213 for ( size_t i = 0; i < _simplices.size(); ++i )
11215 newPos /= _simplices.size();
11218 // count quality metrics (orientation) of triangles around the node
11219 int nbOkBefore = 0;
11220 gp_XY tgtUV = helper.GetNodeUV( face, _node );
11221 for ( size_t i = 0; i < _simplices.size(); ++i )
11222 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11225 for ( size_t i = 0; i < _simplices.size(); ++i )
11226 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11228 if ( nbOkAfter < nbOkBefore )
11230 nbBad += _simplices.size() - nbOkBefore;
11234 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
11235 pos->SetUParameter( newPos.X() );
11236 pos->SetVParameter( newPos.Y() );
11243 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11244 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11248 nbBad += _simplices.size() - nbOkAfter;
11249 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11252 //================================================================================
11254 * \brief Computes new UV using angle based smoothing technic
11256 //================================================================================
11258 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11259 const gp_XY& uvToFix,
11260 const double refSign)
11262 uv.push_back( uv.front() );
11264 vector< gp_XY > edgeDir ( uv.size() );
11265 vector< double > edgeSize( uv.size() );
11266 for ( size_t i = 1; i < edgeDir.size(); ++i )
11268 edgeDir [i-1] = uv[i] - uv[i-1];
11269 edgeSize[i-1] = edgeDir[i-1].Modulus();
11270 if ( edgeSize[i-1] < numeric_limits<double>::min() )
11271 edgeDir[i-1].SetX( 100 );
11273 edgeDir[i-1] /= edgeSize[i-1] * refSign;
11275 edgeDir.back() = edgeDir.front();
11276 edgeSize.back() = edgeSize.front();
11280 double sumSize = 0;
11281 for ( size_t i = 1; i < edgeDir.size(); ++i )
11283 if ( edgeDir[i-1].X() > 1. ) continue;
11285 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11286 if ( i == edgeDir.size() ) break;
11288 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11289 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
11290 gp_XY bisec = norm1 + norm2;
11291 double bisecSize = bisec.Modulus();
11292 if ( bisecSize < numeric_limits<double>::min() )
11294 bisec = -edgeDir[i1] + edgeDir[i];
11295 bisecSize = bisec.Modulus();
11297 bisec /= bisecSize;
11299 gp_XY dirToN = uvToFix - p;
11300 double distToN = dirToN.Modulus();
11301 if ( bisec * dirToN < 0 )
11302 distToN = -distToN;
11304 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11306 sumSize += edgeSize[i1] + edgeSize[i];
11308 newPos /= /*nbEdges * */sumSize;
11312 //================================================================================
11314 * \brief Delete _SolidData
11316 //================================================================================
11318 _SolidData::~_SolidData()
11320 TNode2Edge::iterator n2e = _n2eMap.begin();
11321 for ( ; n2e != _n2eMap.end(); ++n2e )
11323 _LayerEdge* & e = n2e->second;
11326 delete e->_curvature;
11327 if ( e->_2neibors )
11328 delete e->_2neibors->_plnNorm;
11329 delete e->_2neibors;
11340 //================================================================================
11342 * \brief Keep a _LayerEdge inflated along the EDGE
11344 //================================================================================
11346 void _Shrinker1D::AddEdge( const _LayerEdge* e,
11347 _EdgesOnShape& eos,
11348 SMESH_MesherHelper& helper )
11351 if ( _nodes.empty() )
11353 _edges[0] = _edges[1] = 0;
11356 // check _LayerEdge
11357 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11359 if ( eos.SWOLType() != TopAbs_EDGE )
11360 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11361 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11362 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11364 // store _LayerEdge
11365 _geomEdge = TopoDS::Edge( eos._sWOL );
11367 BRep_Tool::Range( _geomEdge, f,l );
11368 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11369 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11373 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11374 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11376 if ( _nodes.empty() )
11378 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11379 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11381 TopLoc_Location loc;
11382 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11383 GeomAdaptor_Curve aCurve(C, f,l);
11384 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11386 int nbExpectNodes = eSubMesh->NbNodes();
11387 _initU .reserve( nbExpectNodes );
11388 _normPar.reserve( nbExpectNodes );
11389 _nodes .reserve( nbExpectNodes );
11390 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11391 while ( nIt->more() )
11393 const SMDS_MeshNode* node = nIt->next();
11395 // skip refinement nodes
11396 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11397 node == tgtNode0 || node == tgtNode1 )
11399 bool hasMarkedFace = false;
11400 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11401 while ( fIt->more() && !hasMarkedFace )
11402 hasMarkedFace = fIt->next()->isMarked();
11403 if ( !hasMarkedFace )
11406 _nodes.push_back( node );
11407 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11408 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11409 _normPar.push_back( len / totLen );
11414 // remove target node of the _LayerEdge from _nodes
11415 size_t nbFound = 0;
11416 for ( size_t i = 0; i < _nodes.size(); ++i )
11417 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11418 _nodes[i] = 0, nbFound++;
11419 if ( nbFound == _nodes.size() )
11424 //================================================================================
11426 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11428 //================================================================================
11430 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11432 if ( _done || _nodes.empty())
11434 const _LayerEdge* e = _edges[0];
11435 if ( !e ) e = _edges[1];
11438 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11439 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11442 if ( set3D || _done )
11444 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11445 GeomAdaptor_Curve aCurve(C, f,l);
11448 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11450 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11451 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11453 for ( size_t i = 0; i < _nodes.size(); ++i )
11455 if ( !_nodes[i] ) continue;
11456 double len = totLen * _normPar[i];
11457 GCPnts_AbscissaPoint discret( aCurve, len, f );
11458 if ( !discret.IsDone() )
11459 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11460 double u = discret.Parameter();
11461 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11462 pos->SetUParameter( u );
11463 gp_Pnt p = C->Value( u );
11464 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11469 BRep_Tool::Range( _geomEdge, f,l );
11471 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11473 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11475 for ( size_t i = 0; i < _nodes.size(); ++i )
11477 if ( !_nodes[i] ) continue;
11478 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11479 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11480 pos->SetUParameter( u );
11485 //================================================================================
11487 * \brief Restore initial parameters of nodes on EDGE
11489 //================================================================================
11491 void _Shrinker1D::RestoreParams()
11494 for ( size_t i = 0; i < _nodes.size(); ++i )
11496 if ( !_nodes[i] ) continue;
11497 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11498 pos->SetUParameter( _initU[i] );
11503 //================================================================================
11505 * \brief Replace source nodes by target nodes in shrinked mesh edges
11507 //================================================================================
11509 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11511 const SMDS_MeshNode* nodes[3];
11512 for ( int i = 0; i < 2; ++i )
11514 if ( !_edges[i] ) continue;
11516 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11517 if ( !eSubMesh ) return;
11518 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11519 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11520 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11521 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11522 while ( eIt->more() )
11524 const SMDS_MeshElement* e = eIt->next();
11525 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11527 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11528 for ( int iN = 0; iN < e->NbNodes(); ++iN )
11530 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11531 nodes[iN] = ( n == srcNode ? tgtNode : n );
11533 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11538 //================================================================================
11540 * \brief Creates 2D and 1D elements on boundaries of new prisms
11542 //================================================================================
11544 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11546 SMESH_MesherHelper helper( *_mesh );
11548 vector< const SMDS_MeshNode* > faceNodes;
11550 //for ( size_t i = 0; i < _sdVec.size(); ++i )
11552 //_SolidData& data = _sdVec[i];
11553 TopTools_IndexedMapOfShape geomEdges;
11554 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11555 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11557 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11558 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11559 if ( data._noShrinkShapes.count( edgeID ))
11562 // Get _LayerEdge's based on E
11564 map< double, const SMDS_MeshNode* > u2nodes;
11565 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11568 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11569 TNode2Edge & n2eMap = data._n2eMap;
11570 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11572 //check if 2D elements are needed on E
11573 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11574 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11575 ledges.push_back( n2e->second );
11577 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11578 continue; // no layers on E
11579 ledges.push_back( n2eMap[ u2n->second ]);
11581 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11582 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11583 int nbSharedPyram = 0;
11584 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11585 while ( vIt->more() )
11587 const SMDS_MeshElement* v = vIt->next();
11588 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11590 if ( nbSharedPyram > 1 )
11591 continue; // not free border of the pyramid
11594 faceNodes.push_back( ledges[0]->_nodes[0] );
11595 faceNodes.push_back( ledges[1]->_nodes[0] );
11596 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11597 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11599 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11600 continue; // faces already created
11602 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11603 ledges.push_back( n2eMap[ u2n->second ]);
11605 // Find out orientation and type of face to create
11607 bool reverse = false, isOnFace;
11610 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11611 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11613 F = e2f->second.Oriented( TopAbs_FORWARD );
11614 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11615 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11616 reverse = !reverse, F.Reverse();
11617 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11618 reverse = !reverse;
11620 else if ( !data._ignoreFaceIds.count( e2f->first ))
11622 // find FACE with layers sharing E
11623 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11625 F = *( fIt->next() );
11627 // Find the sub-mesh to add new faces
11628 SMESHDS_SubMesh* sm = 0;
11630 sm = getMeshDS()->MeshElements( F );
11632 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11634 return error("error in addBoundaryElements()", data._index);
11636 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11637 // faces for 3D meshing (PAL23414)
11638 SMESHDS_SubMesh* adjSM = 0;
11641 const TGeomID faceID = sm->GetID();
11642 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11643 while ( const TopoDS_Shape* solid = soIt->next() )
11644 if ( !solid->IsSame( data._solid ))
11646 size_t iData = _solids.FindIndex( *solid ) - 1;
11647 if ( iData < _sdVec.size() &&
11648 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11649 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11651 SMESH_ProxyMesh::SubMesh* proxySub =
11652 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11653 if ( proxySub && proxySub->NbElements() > 0 )
11660 const int dj1 = reverse ? 0 : 1;
11661 const int dj2 = reverse ? 1 : 0;
11662 vector< const SMDS_MeshElement*> ff; // new faces row
11663 SMESHDS_Mesh* m = getMeshDS();
11664 for ( size_t j = 1; j < ledges.size(); ++j )
11666 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11667 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11668 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11669 if ( nn1.size() == nn2.size() )
11672 for ( size_t z = 1; z < nn1.size(); ++z )
11673 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11675 for ( size_t z = 1; z < nn1.size(); ++z )
11676 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11678 else if ( nn1.size() == 1 )
11681 for ( size_t z = 1; z < nn2.size(); ++z )
11682 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11684 for ( size_t z = 1; z < nn2.size(); ++z )
11685 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11690 for ( size_t z = 1; z < nn1.size(); ++z )
11691 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11693 for ( size_t z = 1; z < nn1.size(); ++z )
11694 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11697 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11699 for ( size_t z = 0; z < ff.size(); ++z )
11701 adjSM->AddElement( ff[ z ]);
11707 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11709 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11710 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11711 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11713 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11714 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11716 helper.SetSubShape( eos->_sWOL );
11717 helper.SetElementsOnShape( true );
11718 for ( size_t z = 1; z < nn.size(); ++z )
11719 helper.AddEdge( nn[z-1], nn[z] );
11723 } // loop on EDGE's
11724 } // loop on _SolidData's