1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_ViscousLayers2D.hxx"
54 #include <Adaptor3d_HSurface.hxx>
55 #include <BRepAdaptor_Curve.hxx>
56 #include <BRepAdaptor_Curve2d.hxx>
57 #include <BRepAdaptor_Surface.hxx>
58 //#include <BRepLProp_CLProps.hxx>
59 #include <BRepLProp_SLProps.hxx>
60 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_B2d.hxx>
63 #include <Bnd_B3d.hxx>
65 #include <GCPnts_AbscissaPoint.hxx>
66 #include <GCPnts_TangentialDeflection.hxx>
67 #include <Geom2d_Circle.hxx>
68 #include <Geom2d_Line.hxx>
69 #include <Geom2d_TrimmedCurve.hxx>
70 #include <GeomAdaptor_Curve.hxx>
71 #include <GeomLib.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Line.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Precision.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <Standard_Failure.hxx>
79 #include <TColStd_Array1OfReal.hxx>
81 #include <TopExp_Explorer.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListOfShape.hxx>
84 #include <TopTools_MapIteratorOfMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
87 #include <TopoDS_Edge.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Vertex.hxx>
91 #include <gp_Cone.hxx>
92 #include <gp_Sphere.hxx>
101 #include <unordered_map>
105 //#define __NOT_INVALIDATE_BAD_SMOOTH
106 //#define __NODES_AT_POS
109 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
110 #define BLOCK_INFLATION // of individual _LayerEdge's
111 #define OLD_NEF_POLYGON
115 //================================================================================
120 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
122 const double theMinSmoothCosin = 0.1;
123 const double theSmoothThickToElemSizeRatio = 0.6;
124 const double theMinSmoothTriaAngle = 30;
125 const double theMinSmoothQuadAngle = 45;
127 // what part of thickness is allowed till intersection
128 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
129 const double theThickToIntersection = 1.5;
131 bool needSmoothing( double cosin, double tgtThick, double elemSize )
133 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
135 double getSmoothingThickness( double cosin, double elemSize )
137 return theSmoothThickToElemSizeRatio * elemSize / cosin;
141 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
142 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
144 struct _MeshOfSolid : public SMESH_ProxyMesh,
145 public SMESH_subMeshEventListenerData
147 bool _n2nMapComputed;
148 SMESH_ComputeErrorPtr _warning;
150 _MeshOfSolid( SMESH_Mesh* mesh)
151 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
153 SMESH_ProxyMesh::setMesh( *mesh );
156 // returns submesh for a geom face
157 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
159 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
160 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
162 void setNode2Node(const SMDS_MeshNode* srcNode,
163 const SMDS_MeshNode* proxyNode,
164 const SMESH_ProxyMesh::SubMesh* subMesh)
166 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
169 //--------------------------------------------------------------------------------
171 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
172 * It is used to clear an inferior dim sub-meshes modified by viscous layers
174 class _ShrinkShapeListener : SMESH_subMeshEventListener
176 _ShrinkShapeListener()
177 : SMESH_subMeshEventListener(/*isDeletable=*/false,
178 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
180 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
181 virtual void ProcessEvent(const int event,
183 SMESH_subMesh* solidSM,
184 SMESH_subMeshEventListenerData* data,
185 const SMESH_Hypothesis* hyp)
187 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
189 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
193 //--------------------------------------------------------------------------------
195 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
196 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
197 * delete the data as soon as it has been used
199 class _ViscousListener : SMESH_subMeshEventListener
202 SMESH_subMeshEventListener(/*isDeletable=*/false,
203 "StdMeshers_ViscousLayers::_ViscousListener") {}
204 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
206 virtual void ProcessEvent(const int event,
208 SMESH_subMesh* subMesh,
209 SMESH_subMeshEventListenerData* data,
210 const SMESH_Hypothesis* hyp)
212 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
213 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
214 SMESH_subMesh::SUBMESH_COMPUTED != event ))
216 // delete SMESH_ProxyMesh containing temporary faces
217 subMesh->DeleteEventListener( this );
220 // Finds or creates proxy mesh of the solid
221 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
222 const TopoDS_Shape& solid,
225 if ( !mesh ) return 0;
226 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
227 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
228 if ( !data && toCreate )
230 data = new _MeshOfSolid(mesh);
231 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
232 sm->SetEventListener( Get(), data, sm );
236 // Removes proxy mesh of the solid
237 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
239 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
243 //================================================================================
245 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
246 * the main shape when sub-mesh of the main shape is cleared,
247 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
250 //================================================================================
252 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
254 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
255 SMESH_subMeshEventListenerData* data =
256 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
259 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
260 data->mySubMeshes.end())
261 data->mySubMeshes.push_back( sub );
265 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
266 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
270 //--------------------------------------------------------------------------------
272 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
273 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
274 * The class is used to check validity of face or volumes around a smoothed node;
275 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
279 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
280 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
281 _Simplex(const SMDS_MeshNode* nPrev=0,
282 const SMDS_MeshNode* nNext=0,
283 const SMDS_MeshNode* nOpp=0)
284 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
285 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
287 const double M[3][3] =
288 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
289 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
290 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
291 vol = ( + M[0][0] * M[1][1] * M[2][2]
292 + M[0][1] * M[1][2] * M[2][0]
293 + M[0][2] * M[1][0] * M[2][1]
294 - M[0][0] * M[1][2] * M[2][1]
295 - M[0][1] * M[1][0] * M[2][2]
296 - M[0][2] * M[1][1] * M[2][0]);
299 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
301 SMESH_TNodeXYZ pSrc( nSrc );
302 return IsForward( &pSrc, &pTgt, vol );
304 bool IsForward(const gp_XY& tgtUV,
305 const SMDS_MeshNode* smoothedNode,
306 const TopoDS_Face& face,
307 SMESH_MesherHelper& helper,
308 const double refSign) const
310 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
311 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
312 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
314 return d*refSign > 1e-100;
316 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
318 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
319 if ( !_nOpp ) // triangle
321 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
322 double tp2 = tp.SquareMagnitude();
323 double pn2 = pn.SquareMagnitude();
324 double nt2 = nt.SquareMagnitude();
326 if ( tp2 < pn2 && tp2 < nt2 )
327 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
328 else if ( pn2 < nt2 )
329 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
331 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
333 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
334 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
335 return minAngle < theMaxCos2;
339 SMESH_TNodeXYZ pOpp( _nOpp );
340 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
341 double tp2 = tp.SquareMagnitude();
342 double po2 = po.SquareMagnitude();
343 double on2 = on.SquareMagnitude();
344 double nt2 = nt.SquareMagnitude();
345 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
346 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
347 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
348 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
350 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
351 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
352 return minAngle < theMaxCos2;
355 bool IsNeighbour(const _Simplex& other) const
357 return _nPrev == other._nNext || _nNext == other._nPrev;
359 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
360 static void GetSimplices( const SMDS_MeshNode* node,
361 vector<_Simplex>& simplices,
362 const set<TGeomID>& ingnoreShapes,
363 const _SolidData* dataToCheckOri = 0,
364 const bool toSort = false);
365 static void SortSimplices(vector<_Simplex>& simplices);
367 //--------------------------------------------------------------------------------
369 * Structure used to take into account surface curvature while smoothing
374 double _k; // factor to correct node smoothed position
375 double _h2lenRatio; // avgNormProj / (2*avgDist)
376 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
378 static _Curvature* New( double avgNormProj, double avgDist );
379 double lenDelta(double len) const { return _k * ( _r + len ); }
380 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
382 //--------------------------------------------------------------------------------
386 struct _EdgesOnShape;
388 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
390 //--------------------------------------------------------------------------------
392 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
393 * and a node of the most internal layer (_nodes.back())
397 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
399 vector< const SMDS_MeshNode*> _nodes;
401 gp_XYZ _normal; // to boundary of solid
402 vector<gp_XYZ> _pos; // points computed during inflation
403 double _len; // length achieved with the last inflation step
404 double _maxLen; // maximal possible length
405 double _cosin; // of angle (_normal ^ surface)
406 double _minAngle; // of _simplices
407 double _lenFactor; // to compute _len taking _cosin into account
410 // simplices connected to the source node (_nodes[0]);
411 // used for smoothing and quality check of _LayerEdge's based on the FACE
412 vector<_Simplex> _simplices;
413 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
414 PSmooFun _smooFunction; // smoothing function
415 _Curvature* _curvature;
416 // data for smoothing of _LayerEdge's based on the EDGE
417 _2NearEdges* _2neibors;
419 enum EFlags { TO_SMOOTH = 0x0000001,
420 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
421 SMOOTHED = 0x0000004, // set by _LayerEdge::Smooth()
422 DIFFICULT = 0x0000008, // near concave VERTEX
423 ON_CONCAVE_FACE = 0x0000010,
424 BLOCKED = 0x0000020, // not to inflate any more
425 INTERSECTED = 0x0000040, // close intersection with a face found
426 NORMAL_UPDATED = 0x0000080,
427 UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
428 MARKED = 0x0000200, // local usage
429 MULTI_NORMAL = 0x0000400, // a normal is invisible by some of surrounding faces
430 NEAR_BOUNDARY = 0x0000800, // is near FACE boundary forcing smooth
431 SMOOTHED_C1 = 0x0001000, // is on _eosC1
432 DISTORTED = 0x0002000, // was bad before smoothing
433 RISKY_SWOL = 0x0004000, // SWOL is parallel to a source FACE
434 SHRUNK = 0x0008000, // target node reached a tgt position while shrink()
435 UNUSED_FLAG = 0x0100000 // to add user flags after
437 bool Is ( int flag ) const { return _flags & flag; }
438 void Set ( int flag ) { _flags |= flag; }
439 void Unset( int flag ) { _flags &= ~flag; }
440 std::string DumpFlags() const; // debug
442 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
443 bool SetNewLength2d( Handle(Geom_Surface)& surface,
444 const TopoDS_Face& F,
446 SMESH_MesherHelper& helper );
447 void SetDataByNeighbors( const SMDS_MeshNode* n1,
448 const SMDS_MeshNode* n2,
449 const _EdgesOnShape& eos,
450 SMESH_MesherHelper& helper);
451 void Block( _SolidData& data );
452 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
453 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
454 const TNode2Edge& n2eMap);
455 void SmoothPos( const vector< double >& segLen, const double tol );
456 int GetSmoothedPos( const double tol );
457 int Smooth(const int step, const bool isConcaveFace, bool findBest);
458 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
459 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
460 void SmoothWoCheck();
461 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
462 const TopoDS_Face& F,
463 SMESH_MesherHelper& helper);
464 void MoveNearConcaVer( const _EdgesOnShape* eov,
465 const _EdgesOnShape* eos,
467 vector< _LayerEdge* > & badSmooEdges);
468 bool FindIntersection( SMESH_ElementSearcher& searcher,
470 const double& epsilon,
472 const SMDS_MeshElement** face = 0);
473 bool SegTriaInter( const gp_Ax1& lastSegment,
478 const double& epsilon) const;
479 bool SegTriaInter( const gp_Ax1& lastSegment,
480 const SMDS_MeshNode* n0,
481 const SMDS_MeshNode* n1,
482 const SMDS_MeshNode* n2,
484 const double& epsilon) const
485 { return SegTriaInter( lastSegment,
486 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
489 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
490 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
491 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
492 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
493 bool IsOnEdge() const { return _2neibors; }
494 bool IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
495 int BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
496 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
497 void SetCosin( double cosin );
498 void SetNormal( const gp_XYZ& n ) { _normal = n; }
499 void SetMaxLen( double l ) { _maxLen = l; }
500 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
501 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
502 void SetSmooLen( double len ) { // set _len at which smoothing is needed
503 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
505 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
507 gp_XYZ smoothLaplacian();
508 gp_XYZ smoothAngular();
509 gp_XYZ smoothLengthWeighted();
510 gp_XYZ smoothCentroidal();
511 gp_XYZ smoothNefPolygon();
513 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
514 static const int theNbSmooFuns = FUN_NB;
515 static PSmooFun _funs[theNbSmooFuns];
516 static const char* _funNames[theNbSmooFuns+1];
517 int smooFunID( PSmooFun fun=0) const;
519 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
520 &_LayerEdge::smoothLengthWeighted,
521 &_LayerEdge::smoothCentroidal,
522 &_LayerEdge::smoothNefPolygon,
523 &_LayerEdge::smoothAngular };
524 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
532 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
534 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
535 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
538 //--------------------------------------------------------------------------------
540 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
544 gp_XY _pos, _dir, _inNorm;
545 bool IsOut( const gp_XY p, const double tol ) const
547 return _inNorm * ( p - _pos ) < -tol;
549 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
551 //const double eps = 1e-10;
552 double D = _dir.Crossed( hp._dir );
553 if ( fabs(D) < std::numeric_limits<double>::min())
555 gp_XY vec21 = _pos - hp._pos;
556 double u = hp._dir.Crossed( vec21 ) / D;
557 intPnt = _pos + _dir * u;
561 //--------------------------------------------------------------------------------
563 * Structure used to smooth a _LayerEdge based on an EDGE.
567 double _wgt [2]; // weights of _nodes
568 _LayerEdge* _edges[2];
570 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
573 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
574 ~_2NearEdges(){ delete _plnNorm; }
575 const SMDS_MeshNode* tgtNode(bool is2nd) {
576 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
578 const SMDS_MeshNode* srcNode(bool is2nd) {
579 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
582 std::swap( _wgt [0], _wgt [1] );
583 std::swap( _edges[0], _edges[1] );
585 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
586 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
588 bool include( const _LayerEdge* e ) {
589 return ( _edges[0] == e || _edges[1] == e );
594 //--------------------------------------------------------------------------------
596 * \brief Layers parameters got by averaging several hypotheses
600 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
601 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
605 void Add( const StdMeshers_ViscousLayers* hyp )
610 _nbLayers = hyp->GetNumberLayers();
611 //_thickness += hyp->GetTotalThickness();
612 _thickness = Max( _thickness, hyp->GetTotalThickness() );
613 _stretchFactor += hyp->GetStretchFactor();
614 _method = hyp->GetMethod();
615 if ( _groupName.empty() )
616 _groupName = hyp->GetGroupName();
619 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621 int GetNumberLayers() const { return _nbLayers; }
622 int GetMethod() const { return _method; }
623 bool ToCreateGroup() const { return !_groupName.empty(); }
624 const std::string& GetGroupName() const { return _groupName; }
626 bool UseSurfaceNormal() const
627 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628 bool ToSmooth() const
629 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
630 bool IsOffsetMethod() const
631 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
633 bool operator==( const AverageHyp& other ) const
635 return ( _nbLayers == other._nbLayers &&
636 _method == other._method &&
637 Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
638 Equals( GetStretchFactor(), other.GetStretchFactor() ));
640 static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
643 int _nbLayers, _nbHyps, _method;
644 double _thickness, _stretchFactor;
645 std::string _groupName;
648 //--------------------------------------------------------------------------------
650 * \brief _LayerEdge's on a shape and other shape data
654 vector< _LayerEdge* > _edges;
658 SMESH_subMesh * _subMesh;
659 // face or edge w/o layer along or near which _edges are inflated
661 bool _isRegularSWOL; // w/o singularities
662 // averaged StdMeshers_ViscousLayers parameters
665 _Smoother1D* _edgeSmoother;
666 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
667 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
669 typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
670 TFace2NormMap _faceNormals; // if _shape is FACE
671 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
673 Handle(ShapeAnalysis_Surface) _offsetSurf;
674 _LayerEdge* _edgeForOffset;
676 _SolidData* _data; // parent SOLID
678 _LayerEdge* operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
679 size_t size() const { return _edges.size(); }
680 TopAbs_ShapeEnum ShapeType() const
681 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
682 TopAbs_ShapeEnum SWOLType() const
683 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
684 bool HasC1( const _EdgesOnShape* other ) const
685 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
686 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
687 _SolidData& GetData() const { return *_data; }
689 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
693 //--------------------------------------------------------------------------------
695 * \brief Convex FACE whose radius of curvature is less than the thickness of
696 * layers. It is used to detect distortion of prisms based on a convex
697 * FACE and to update normals to enable further increasing the thickness
703 // edges whose _simplices are used to detect prism distortion
704 vector< _LayerEdge* > _simplexTestEdges;
706 // map a sub-shape to _SolidData::_edgesOnShape
707 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
711 bool _normalsFixedOnBorders; // used in putOnOffsetSurface()
713 double GetMaxCurvature( _SolidData& data,
715 BRepLProp_SLProps& surfProp,
716 SMESH_MesherHelper& helper);
718 bool GetCenterOfCurvature( _LayerEdge* ledge,
719 BRepLProp_SLProps& surfProp,
720 SMESH_MesherHelper& helper,
721 gp_Pnt & center ) const;
722 bool CheckPrisms() const;
725 //--------------------------------------------------------------------------------
727 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
728 * at inflation up to the full thickness. A detected collision
729 * is fixed in updateNormals()
731 struct _CollisionEdges
734 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
735 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
736 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
739 //--------------------------------------------------------------------------------
741 * \brief Data of a SOLID
745 typedef const StdMeshers_ViscousLayers* THyp;
747 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
748 TGeomID _index; // SOLID id
749 _MeshOfSolid* _proxyMesh;
752 list< TopoDS_Shape > _hypShapes;
753 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
754 set< TGeomID > _reversedFaceIds;
755 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
757 double _stepSize, _stepSizeCoeff, _geomSize;
758 const SMDS_MeshNode* _stepSizeNodes[2];
760 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
762 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
763 map< TGeomID, TNode2Edge* > _s2neMap;
764 // _LayerEdge's with underlying shapes
765 vector< _EdgesOnShape > _edgesOnShape;
767 // key: an ID of shape (EDGE or VERTEX) shared by a FACE with
768 // layers and a FACE w/o layers
769 // value: the shape (FACE or EDGE) to shrink mesh on.
770 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
771 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
773 // Convex FACEs whose radius of curvature is less than the thickness of layers
774 map< TGeomID, _ConvexFace > _convexFaces;
776 // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
777 // the adjacent SOLID
778 set< TGeomID > _noShrinkShapes;
780 int _nbShapesToSmooth;
782 vector< _CollisionEdges > _collisionEdges;
783 set< TGeomID > _concaveFaces;
785 double _maxThickness; // of all _hyps
786 double _minThickness; // of all _hyps
788 double _epsilon; // precision for SegTriaInter()
790 SMESH_MesherHelper* _helper;
792 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
794 :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
795 ~_SolidData() { delete _helper; _helper = 0; }
797 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
798 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
800 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
801 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
802 return id2face == _convexFaces.end() ? 0 : & id2face->second;
804 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
805 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
806 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
807 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
809 SMESH_MesherHelper& GetHelper() const { return *_helper; }
811 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
812 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
813 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
814 _edgesOnShape[i]._edges[j]->Unset( flag );
816 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
817 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
819 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
821 //--------------------------------------------------------------------------------
823 * \brief Offset plane used in getNormalByOffset()
829 int _faceIndexNext[2];
830 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
833 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
835 void ComputeIntersectionLine( _OffsetPlane& pln,
836 const TopoDS_Edge& E,
837 const TopoDS_Vertex& V );
838 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
839 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
841 //--------------------------------------------------------------------------------
843 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
845 struct _CentralCurveOnEdge
848 vector< gp_Pnt > _curvaCenters;
849 vector< _LayerEdge* > _ledges;
850 vector< gp_XYZ > _normals; // new normal for each of _ledges
851 vector< double > _segLength2;
854 TopoDS_Face _adjFace;
855 bool _adjFaceToSmooth;
857 void Append( const gp_Pnt& center, _LayerEdge* ledge )
859 if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
861 if ( _curvaCenters.size() > 0 )
862 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
863 _curvaCenters.push_back( center );
864 _ledges.push_back( ledge );
865 _normals.push_back( ledge->_normal );
867 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
868 void SetShapes( const TopoDS_Edge& edge,
869 const _ConvexFace& convFace,
871 SMESH_MesherHelper& helper);
873 //--------------------------------------------------------------------------------
875 * \brief Data of node on a shrinked FACE
879 const SMDS_MeshNode* _node;
880 vector<_Simplex> _simplices; // for quality check
882 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
884 bool Smooth(int& badNb,
885 Handle(Geom_Surface)& surface,
886 SMESH_MesherHelper& helper,
887 const double refSign,
891 gp_XY computeAngularPos(vector<gp_XY>& uv,
892 const gp_XY& uvToFix,
893 const double refSign );
897 //--------------------------------------------------------------------------------
899 * \brief Builder of viscous layers
901 class _ViscousBuilder
906 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
907 const TopoDS_Shape& shape);
908 // check validity of hypotheses
909 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
910 const TopoDS_Shape& shape );
912 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
913 void RestoreListeners();
915 // computes SMESH_ProxyMesh::SubMesh::_n2n;
916 bool MakeN2NMap( _MeshOfSolid* pm );
920 bool findSolidsWithLayers(const bool checkFaceMesh=true);
921 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
922 bool findFacesWithLayers(const bool onlyWith=false);
923 void findPeriodicFaces();
924 void getIgnoreFaces(const TopoDS_Shape& solid,
925 const StdMeshers_ViscousLayers* hyp,
926 const TopoDS_Shape& hypShape,
927 set<TGeomID>& ignoreFaces);
928 void makeEdgesOnShape();
929 bool makeLayer(_SolidData& data);
930 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
931 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
932 SMESH_MesherHelper& helper, _SolidData& data);
933 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
934 const TopoDS_Face& face,
935 SMESH_MesherHelper& helper,
937 bool shiftInside=false);
938 bool getFaceNormalAtSingularity(const gp_XY& uv,
939 const TopoDS_Face& face,
940 SMESH_MesherHelper& helper,
942 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
943 gp_XYZ getNormalByOffset( _LayerEdge* edge,
944 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
946 bool lastNoOffset = false);
947 bool findNeiborsOnEdge(const _LayerEdge* edge,
948 const SMDS_MeshNode*& n1,
949 const SMDS_MeshNode*& n2,
952 void findSimplexTestEdges( _SolidData& data,
953 vector< vector<_LayerEdge*> >& edgesByGeom);
954 void computeGeomSize( _SolidData& data );
955 bool findShapesToSmooth( _SolidData& data);
956 void limitStepSizeByCurvature( _SolidData& data );
957 void limitStepSize( _SolidData& data,
958 const SMDS_MeshElement* face,
959 const _LayerEdge* maxCosinEdge );
960 void limitStepSize( _SolidData& data, const double minSize);
961 bool inflate(_SolidData& data);
962 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
963 int invalidateBadSmooth( _SolidData& data,
964 SMESH_MesherHelper& helper,
965 vector< _LayerEdge* >& badSmooEdges,
966 vector< _EdgesOnShape* >& eosC1,
968 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
969 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
970 vector< _EdgesOnShape* >& eosC1,
971 int smooStep=0, int moveAll=false );
972 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
973 void findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
975 SMESH_MesherHelper& helper );
976 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
977 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
978 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
979 const bool isSmoothable );
980 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
981 bool updateNormalsOfConvexFaces( _SolidData& data,
982 SMESH_MesherHelper& helper,
984 void updateNormalsOfC1Vertices( _SolidData& data );
985 bool updateNormalsOfSmoothed( _SolidData& data,
986 SMESH_MesherHelper& helper,
988 const double stepSize );
989 bool isNewNormalOk( _SolidData& data,
991 const gp_XYZ& newNormal);
992 bool refine(_SolidData& data);
993 bool shrink(_SolidData& data);
994 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
995 SMESH_MesherHelper& helper,
996 const SMESHDS_SubMesh* faceSubMesh );
997 void restoreNoShrink( _LayerEdge& edge ) const;
998 void fixBadFaces(const TopoDS_Face& F,
999 SMESH_MesherHelper& helper,
1002 set<const SMDS_MeshNode*> * involvedNodes=NULL);
1003 bool addBoundaryElements(_SolidData& data);
1005 bool error( const string& text, int solidID=-1 );
1006 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1009 void makeGroupOfLE();
1012 SMESH_ComputeErrorPtr _error;
1014 vector< _SolidData > _sdVec;
1015 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1016 TopTools_MapOfShape _shrunkFaces;
1017 std::unique_ptr<Periodicity> _periodicity;
1022 //--------------------------------------------------------------------------------
1024 * \brief Shrinker of nodes on the EDGE
1028 TopoDS_Edge _geomEdge;
1029 vector<double> _initU;
1030 vector<double> _normPar;
1031 vector<const SMDS_MeshNode*> _nodes;
1032 const _LayerEdge* _edges[2];
1035 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1036 void Compute(bool set3D, SMESH_MesherHelper& helper);
1037 void RestoreParams();
1038 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1039 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1040 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1041 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1042 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1043 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1045 //--------------------------------------------------------------------------------
1047 * \brief Smoother of _LayerEdge's on EDGE.
1051 struct OffPnt // point of the offsetted EDGE
1053 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1054 double _len; // length reached at previous inflation step
1055 double _param; // on EDGE
1056 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1057 gp_XYZ _edgeDir;// EDGE tangent at _param
1058 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1060 vector< OffPnt > _offPoints;
1061 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1062 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1063 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1064 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1065 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1066 _EdgesOnShape& _eos;
1067 double _curveLen; // length of the EDGE
1068 std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1070 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1072 SMESH_MesherHelper& helper);
1074 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1075 _EdgesOnShape& eos )
1076 : _anaCurve( curveForSmooth ), _eos( eos )
1079 bool Perform(_SolidData& data,
1080 Handle(ShapeAnalysis_Surface)& surface,
1081 const TopoDS_Face& F,
1082 SMESH_MesherHelper& helper );
1084 void prepare(_SolidData& data );
1086 void findEdgesToSmooth();
1088 bool isToSmooth( int iE );
1090 bool smoothAnalyticEdge( _SolidData& data,
1091 Handle(ShapeAnalysis_Surface)& surface,
1092 const TopoDS_Face& F,
1093 SMESH_MesherHelper& helper);
1094 bool smoothComplexEdge( _SolidData& data,
1095 Handle(ShapeAnalysis_Surface)& surface,
1096 const TopoDS_Face& F,
1097 SMESH_MesherHelper& helper);
1098 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1099 const gp_XYZ& edgeDir);
1100 _LayerEdge* getLEdgeOnV( bool is2nd )
1102 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1104 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1106 void offPointsToPython() const; // debug
1108 //--------------------------------------------------------------------------------
1110 * \brief Class of temporary mesh face.
1111 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1112 * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1114 struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1116 const SMDS_MeshElement* _srcFace;
1118 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1121 const SMDS_MeshElement* srcFace=0 ):
1122 SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1123 virtual SMDSAbs_EntityType GetEntityType() const
1124 { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1125 virtual SMDSAbs_GeometryType GetGeomType() const
1126 { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1128 //--------------------------------------------------------------------------------
1130 * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1132 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1134 _LayerEdge *_le1, *_le2;
1135 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1136 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1138 myNodes[0]=_le1->_nodes[0];
1139 myNodes[1]=_le1->_nodes.back();
1140 myNodes[2]=_le2->_nodes.back();
1141 myNodes[3]=_le2->_nodes[0];
1143 const SMDS_MeshNode* n( size_t i ) const
1145 return myNodes[ i ];
1147 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1149 SMESH_TNodeXYZ p0s( myNodes[0] );
1150 SMESH_TNodeXYZ p0t( myNodes[1] );
1151 SMESH_TNodeXYZ p1t( myNodes[2] );
1152 SMESH_TNodeXYZ p1s( myNodes[3] );
1153 gp_XYZ v0 = p0t - p0s;
1154 gp_XYZ v1 = p1t - p1s;
1155 gp_XYZ v01 = p1s - p0s;
1156 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1161 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1163 myNodes[0]=le1->_nodes[0];
1164 myNodes[1]=le1->_nodes.back();
1165 myNodes[2]=le2->_nodes.back();
1166 myNodes[3]=le2->_nodes[0];
1170 //--------------------------------------------------------------------------------
1172 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1173 * \warning Location of a surface is ignored
1175 struct _NodeCoordHelper
1177 SMESH_MesherHelper& _helper;
1178 const TopoDS_Face& _face;
1179 Handle(Geom_Surface) _surface;
1180 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1182 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1183 : _helper( helper ), _face( F )
1187 TopLoc_Location loc;
1188 _surface = BRep_Tool::Surface( _face, loc );
1190 if ( _surface.IsNull() )
1191 _fun = & _NodeCoordHelper::direct;
1193 _fun = & _NodeCoordHelper::byUV;
1195 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1198 gp_XYZ direct(const SMDS_MeshNode* n) const
1200 return SMESH_TNodeXYZ( n );
1202 gp_XYZ byUV (const SMDS_MeshNode* n) const
1204 gp_XY uv = _helper.GetNodeUV( _face, n );
1205 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1209 //================================================================================
1211 * \brief Check angle between vectors
1213 //================================================================================
1215 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1217 double dot = v1 * v2; // cos * |v1| * |v2|
1218 double l1 = v1.SquareMagnitude();
1219 double l2 = v2.SquareMagnitude();
1220 return (( dot * cos >= 0 ) &&
1221 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1226 ObjectPool< _LayerEdge > _edgePool;
1227 ObjectPool< _Curvature > _curvaturePool;
1228 ObjectPool< _2NearEdges > _nearEdgesPool;
1230 static _Factory* & me()
1232 static _Factory* theFactory = 0;
1237 _Factory() { me() = this; }
1238 ~_Factory() { me() = 0; }
1240 static _LayerEdge* NewLayerEdge() { return me()->_edgePool.getNew(); }
1241 static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1242 static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1245 } // namespace VISCOUS_3D
1249 //================================================================================
1250 // StdMeshers_ViscousLayers hypothesis
1252 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1253 :SMESH_Hypothesis(hypId, gen),
1254 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1255 _method( SURF_OFFSET_SMOOTH ),
1258 _name = StdMeshers_ViscousLayers::GetHypType();
1259 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1260 } // --------------------------------------------------------------------------------
1261 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1263 if ( faceIds != _shapeIds )
1264 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1265 if ( _isToIgnoreShapes != toIgnore )
1266 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1267 } // --------------------------------------------------------------------------------
1268 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1270 if ( thickness != _thickness )
1271 _thickness = thickness, NotifySubMeshesHypothesisModification();
1272 } // --------------------------------------------------------------------------------
1273 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1275 if ( _nbLayers != nb )
1276 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1277 } // --------------------------------------------------------------------------------
1278 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1280 if ( _stretchFactor != factor )
1281 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1282 } // --------------------------------------------------------------------------------
1283 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1285 if ( _method != method )
1286 _method = method, NotifySubMeshesHypothesisModification();
1287 } // --------------------------------------------------------------------------------
1288 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1290 if ( _groupName != name )
1293 if ( !_groupName.empty() )
1294 NotifySubMeshesHypothesisModification();
1296 } // --------------------------------------------------------------------------------
1297 SMESH_ProxyMesh::Ptr
1298 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1299 const TopoDS_Shape& theShape,
1300 const bool toMakeN2NMap) const
1302 using namespace VISCOUS_3D;
1303 _ViscousBuilder builder;
1304 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1305 if ( err && !err->IsOK() )
1306 return SMESH_ProxyMesh::Ptr();
1308 vector<SMESH_ProxyMesh::Ptr> components;
1309 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1310 for ( ; exp.More(); exp.Next() )
1312 if ( _MeshOfSolid* pm =
1313 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1315 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1316 if ( !builder.MakeN2NMap( pm ))
1317 return SMESH_ProxyMesh::Ptr();
1318 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1319 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1321 if ( pm->_warning && !pm->_warning->IsOK() )
1323 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1324 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1325 if ( !smError || smError->IsOK() )
1326 smError = pm->_warning;
1329 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1331 switch ( components.size() )
1335 case 1: return components[0];
1337 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1339 return SMESH_ProxyMesh::Ptr();
1340 } // --------------------------------------------------------------------------------
1341 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1343 save << " " << _nbLayers
1344 << " " << _thickness
1345 << " " << _stretchFactor
1346 << " " << _shapeIds.size();
1347 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1348 save << " " << _shapeIds[i];
1349 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1350 save << " " << _method;
1351 save << " " << _groupName.size();
1352 if ( !_groupName.empty() )
1353 save << " " << _groupName;
1355 } // --------------------------------------------------------------------------------
1356 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1358 int nbFaces, faceID, shapeToTreat, method;
1359 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1360 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1361 _shapeIds.push_back( faceID );
1362 if ( load >> shapeToTreat ) {
1363 _isToIgnoreShapes = !shapeToTreat;
1364 if ( load >> method )
1365 _method = (ExtrusionMethod) method;
1367 if ( load >> nameSize && nameSize > 0 )
1369 _groupName.resize( nameSize );
1370 load.get( _groupName[0] ); // remove a white-space
1371 load.getline( &_groupName[0], nameSize + 1 );
1375 _isToIgnoreShapes = true; // old behavior
1378 } // --------------------------------------------------------------------------------
1379 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1380 const TopoDS_Shape& theShape)
1384 } // --------------------------------------------------------------------------------
1385 SMESH_ComputeErrorPtr
1386 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1387 const TopoDS_Shape& theShape,
1388 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1390 VISCOUS_3D::_ViscousBuilder builder;
1391 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1392 if ( err && !err->IsOK() )
1393 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1395 theStatus = SMESH_Hypothesis::HYP_OK;
1399 // --------------------------------------------------------------------------------
1400 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1403 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1404 return IsToIgnoreShapes() ? !isIn : isIn;
1407 // --------------------------------------------------------------------------------
1408 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string& theName,
1409 SMESH_Mesh& theMesh,
1410 SMDSAbs_ElementType theType)
1412 SMESH_Group* group = 0;
1413 SMDS_MeshGroup* groupDS = 0;
1415 if ( theName.empty() )
1418 if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1419 while( grIt->more() && !group )
1421 group = grIt->next();
1423 group->GetGroupDS()->GetType() != theType ||
1424 group->GetName() != theName ||
1425 !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1429 group = theMesh.AddGroup( theType, theName.c_str() );
1431 groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1436 // END StdMeshers_ViscousLayers hypothesis
1437 //================================================================================
1439 namespace VISCOUS_3D
1441 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1445 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1446 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1447 gp_Pnt p = BRep_Tool::Pnt( fromV );
1448 double distF = p.SquareDistance( c->Value( f ));
1449 double distL = p.SquareDistance( c->Value( l ));
1450 c->D1(( distF < distL ? f : l), p, dir );
1451 if ( distL < distF ) dir.Reverse();
1454 //--------------------------------------------------------------------------------
1455 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1456 SMESH_MesherHelper& helper)
1459 double f,l; gp_Pnt p;
1460 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1461 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1462 double u = helper.GetNodeU( E, atNode );
1466 //--------------------------------------------------------------------------------
1467 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1468 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1470 //--------------------------------------------------------------------------------
1471 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1472 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1475 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1478 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1479 return getFaceDir( F, v, node, helper, ok );
1481 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1482 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1483 gp_Pnt p; gp_Vec du, dv, norm;
1484 surface->D1( uv.X(),uv.Y(), p, du,dv );
1487 double u = helper.GetNodeU( fromE, node, 0, &ok );
1489 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1490 if ( o == TopAbs_REVERSED )
1493 gp_Vec dir = norm ^ du;
1495 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1496 helper.IsClosedEdge( fromE ))
1498 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1499 else c->D1( f, p, dv );
1500 if ( o == TopAbs_REVERSED )
1502 gp_Vec dir2 = norm ^ dv;
1503 dir = dir.Normalized() + dir2.Normalized();
1507 //--------------------------------------------------------------------------------
1508 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1509 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1510 bool& ok, double* cosin)
1512 TopoDS_Face faceFrw = F;
1513 faceFrw.Orientation( TopAbs_FORWARD );
1514 //double f,l; TopLoc_Location loc;
1515 TopoDS_Edge edges[2]; // sharing a vertex
1518 TopoDS_Vertex VV[2];
1519 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1520 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1522 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1523 if ( SMESH_Algo::isDegenerated( e )) continue;
1524 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1525 if ( VV[1].IsSame( fromV )) {
1526 nbEdges += edges[ 0 ].IsNull();
1529 else if ( VV[0].IsSame( fromV )) {
1530 nbEdges += edges[ 1 ].IsNull();
1535 gp_XYZ dir(0,0,0), edgeDir[2];
1538 // get dirs of edges going fromV
1540 for ( size_t i = 0; i < nbEdges && ok; ++i )
1542 edgeDir[i] = getEdgeDir( edges[i], fromV );
1543 double size2 = edgeDir[i].SquareModulus();
1544 if (( ok = size2 > numeric_limits<double>::min() ))
1545 edgeDir[i] /= sqrt( size2 );
1547 if ( !ok ) return dir;
1549 // get angle between the 2 edges
1551 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1552 if ( Abs( angle ) < 5 * M_PI/180 )
1554 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1558 dir = edgeDir[0] + edgeDir[1];
1563 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1564 *cosin = Cos( angle );
1567 else if ( nbEdges == 1 )
1569 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1570 if ( cosin ) *cosin = 1.;
1580 //================================================================================
1582 * \brief Finds concave VERTEXes of a FACE
1584 //================================================================================
1586 bool getConcaveVertices( const TopoDS_Face& F,
1587 SMESH_MesherHelper& helper,
1588 set< TGeomID >* vertices = 0)
1590 // check angles at VERTEXes
1592 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1593 for ( size_t iW = 0; iW < wires.size(); ++iW )
1595 const int nbEdges = wires[iW]->NbEdges();
1596 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1598 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1600 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1601 int iE2 = ( iE1 + 1 ) % nbEdges;
1602 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1603 iE2 = ( iE2 + 1 ) % nbEdges;
1604 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1605 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1606 wires[iW]->Edge( iE2 ), F, V );
1607 if ( angle < -5. * M_PI / 180. )
1611 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1615 return vertices ? !vertices->empty() : false;
1618 //================================================================================
1620 * \brief Returns true if a FACE is bound by a concave EDGE
1622 //================================================================================
1624 bool isConcave( const TopoDS_Face& F,
1625 SMESH_MesherHelper& helper,
1626 set< TGeomID >* vertices = 0 )
1628 bool isConcv = false;
1629 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1631 gp_Vec2d drv1, drv2;
1633 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1634 for ( ; eExp.More(); eExp.Next() )
1636 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1637 if ( SMESH_Algo::isDegenerated( E )) continue;
1638 // check if 2D curve is concave
1639 BRepAdaptor_Curve2d curve( E, F );
1640 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1641 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1642 curve.Intervals( intervals, GeomAbs_C2 );
1643 bool isConvex = true;
1644 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1646 double u1 = intervals( i );
1647 double u2 = intervals( i+1 );
1648 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1649 double cross = drv1 ^ drv2;
1650 if ( E.Orientation() == TopAbs_REVERSED )
1652 isConvex = ( cross > -1e-9 ); // 0.1 );
1656 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1665 // check angles at VERTEXes
1666 if ( getConcaveVertices( F, helper, vertices ))
1672 //================================================================================
1674 * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1675 * \param [in] face - the mesh face to treat
1676 * \param [in] nodeOnEdge - a node on the EDGE
1677 * \param [out] faceSize - the computed distance
1678 * \return bool - true if faceSize computed
1680 //================================================================================
1682 bool getDistFromEdge( const SMDS_MeshElement* face,
1683 const SMDS_MeshNode* nodeOnEdge,
1686 faceSize = Precision::Infinite();
1689 int nbN = face->NbCornerNodes();
1690 int iOnE = face->GetNodeIndex( nodeOnEdge );
1691 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1692 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1693 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1694 face->GetNode( iNext[1] ) };
1695 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1696 double segLen = -1.;
1697 // look for two neighbor not in-FACE nodes of face
1698 for ( int i = 0; i < 2; ++i )
1700 if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1701 ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1703 // look for an in-FACE node
1704 for ( int iN = 0; iN < nbN; ++iN )
1706 if ( iN == iOnE || iN == iNext[i] )
1708 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1709 gp_XYZ v = pInFace - segEnd;
1712 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1713 segLen = segVec.Modulus();
1715 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1716 faceSize = Min( faceSize, distToSeg );
1724 //================================================================================
1726 * \brief Return direction of axis or revolution of a surface
1728 //================================================================================
1730 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1733 switch ( surface.GetType() ) {
1736 gp_Cone cone = surface.Cone();
1737 axis = cone.Axis().Direction();
1740 case GeomAbs_Sphere:
1742 gp_Sphere sphere = surface.Sphere();
1743 axis = sphere.Position().Direction();
1746 case GeomAbs_SurfaceOfRevolution:
1748 axis = surface.AxeOfRevolution().Direction();
1751 //case GeomAbs_SurfaceOfExtrusion:
1752 case GeomAbs_OffsetSurface:
1754 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1755 return getRovolutionAxis( base->Surface(), axis );
1757 default: return false;
1762 //--------------------------------------------------------------------------------
1763 // DEBUG. Dump intermediate node positions into a python script
1764 // HOWTO use: run python commands written in a console to see
1765 // construction steps of viscous layers
1771 PyDump(SMESH_Mesh& m) {
1772 int tag = 3 + m.GetId();
1773 const char* fname = "/tmp/viscous.py";
1774 cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1775 py = _pyStream = new ofstream(fname);
1776 *py << "import SMESH" << endl
1777 << "from salome.smesh import smeshBuilder" << endl
1778 << "smesh = smeshBuilder.New()" << endl
1779 << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1780 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1785 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1786 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1787 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1788 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1792 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1793 struct MyStream : public ostream
1795 template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1797 void Pause() { py = &_mystream; }
1798 void Resume() { py = _pyStream; }
1802 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1803 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1804 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1805 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1806 void _dumpFunction(const string& fun, int ln)
1807 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1808 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1809 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1810 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1811 void _dumpCmd(const string& txt, int ln)
1812 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1813 void dumpFunctionEnd()
1814 { if (py) *py<< " return"<< endl; }
1815 void dumpChangeNodes( const SMDS_MeshElement* f )
1816 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1817 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1818 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1819 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1823 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1824 #define dumpFunction(f) f
1826 #define dumpMoveComm(n,txt)
1827 #define dumpCmd(txt)
1828 #define dumpFunctionEnd()
1829 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1830 #define debugMsg( txt ) {}
1835 using namespace VISCOUS_3D;
1837 //================================================================================
1839 * \brief Constructor of _ViscousBuilder
1841 //================================================================================
1843 _ViscousBuilder::_ViscousBuilder()
1845 _error = SMESH_ComputeError::New(COMPERR_OK);
1849 //================================================================================
1851 * \brief Stores error description and returns false
1853 //================================================================================
1855 bool _ViscousBuilder::error(const string& text, int solidId )
1857 const string prefix = string("Viscous layers builder: ");
1858 _error->myName = COMPERR_ALGO_FAILED;
1859 _error->myComment = prefix + text;
1862 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1863 if ( !sm && !_sdVec.empty() )
1864 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1865 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1867 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1868 if ( smError && smError->myAlgo )
1869 _error->myAlgo = smError->myAlgo;
1871 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1873 // set KO to all solids
1874 for ( size_t i = 0; i < _sdVec.size(); ++i )
1876 if ( _sdVec[i]._index == solidId )
1878 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1879 if ( !sm->IsEmpty() )
1881 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1882 if ( !smError || smError->IsOK() )
1884 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1885 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1889 makeGroupOfLE(); // debug
1894 //================================================================================
1896 * \brief At study restoration, restore event listeners used to clear an inferior
1897 * dim sub-mesh modified by viscous layers
1899 //================================================================================
1901 void _ViscousBuilder::RestoreListeners()
1906 //================================================================================
1908 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1910 //================================================================================
1912 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1914 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1915 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1916 for ( ; fExp.More(); fExp.Next() )
1918 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1919 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1921 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1923 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1926 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1927 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1929 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1930 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1931 while( prxIt->more() )
1933 const SMDS_MeshElement* fSrc = srcIt->next();
1934 const SMDS_MeshElement* fPrx = prxIt->next();
1935 if ( fSrc->NbNodes() != fPrx->NbNodes())
1936 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1937 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1938 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1941 pm->_n2nMapComputed = true;
1945 //================================================================================
1947 * \brief Does its job
1949 //================================================================================
1951 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1952 const TopoDS_Shape& theShape)
1958 // check if proxy mesh already computed
1959 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1961 return error("No SOLID's in theShape"), _error;
1963 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1964 return SMESH_ComputeErrorPtr(); // everything already computed
1966 PyDump debugDump( theMesh );
1967 _pyDump = &debugDump;
1969 // TODO: ignore already computed SOLIDs
1970 if ( !findSolidsWithLayers())
1973 if ( !findFacesWithLayers() )
1976 // for ( size_t i = 0; i < _sdVec.size(); ++i )
1978 // if ( ! makeLayer( _sdVec[ i ])) // create _LayerEdge's
1984 findPeriodicFaces();
1986 for ( size_t i = 0; i < _sdVec.size(); ++i )
1989 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1990 if ( _sdVec[iSD]._before.IsEmpty() &&
1991 !_sdVec[iSD]._solid.IsNull() &&
1992 !_sdVec[iSD]._done )
1995 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1998 if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
2000 _sdVec[iSD]._solid.Nullify();
2004 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
2007 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
2010 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
2013 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2015 _sdVec[iSD]._done = true;
2017 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2018 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2019 _sdVec[iSD]._before.Remove( solid );
2022 makeGroupOfLE(); // debug
2028 //================================================================================
2030 * \brief Check validity of hypotheses
2032 //================================================================================
2034 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
2035 const TopoDS_Shape& shape )
2039 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2040 return SMESH_ComputeErrorPtr(); // everything already computed
2043 findSolidsWithLayers( /*checkFaceMesh=*/false );
2044 bool ok = findFacesWithLayers( true );
2046 // remove _MeshOfSolid's of _SolidData's
2047 for ( size_t i = 0; i < _sdVec.size(); ++i )
2048 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2053 return SMESH_ComputeErrorPtr();
2056 //================================================================================
2058 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2060 //================================================================================
2062 bool _ViscousBuilder::findSolidsWithLayers(const bool checkFaceMesh)
2065 TopTools_IndexedMapOfShape allSolids;
2066 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2067 _sdVec.reserve( allSolids.Extent());
2069 SMESH_HypoFilter filter;
2070 for ( int i = 1; i <= allSolids.Extent(); ++i )
2072 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2073 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2074 continue; // solid is already meshed
2075 // TODO: check if algo is hidden
2076 SMESH_Algo* algo = sm->GetAlgo();
2077 if ( !algo ) continue;
2078 // check if all FACEs are meshed, which can be false if Compute() a sub-shape
2079 if ( checkFaceMesh )
2081 bool facesMeshed = true;
2082 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,true);
2083 while ( smIt->more() && facesMeshed )
2085 SMESH_subMesh * faceSM = smIt->next();
2086 if ( faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2088 facesMeshed = faceSM->IsMeshComputed();
2093 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2094 const list <const SMESHDS_Hypothesis *> & allHyps =
2095 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2096 _SolidData* soData = 0;
2097 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2098 const StdMeshers_ViscousLayers* viscHyp = 0;
2099 for ( ; hyp != allHyps.end(); ++hyp )
2100 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2102 TopoDS_Shape hypShape;
2103 filter.Init( filter.Is( viscHyp ));
2104 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2108 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2111 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2112 soData = & _sdVec.back();
2113 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2114 soData->_helper = new SMESH_MesherHelper( *_mesh );
2115 soData->_helper->SetSubShape( allSolids(i) );
2116 _solids.Add( allSolids(i) );
2118 soData->_hyps.push_back( viscHyp );
2119 soData->_hypShapes.push_back( hypShape );
2122 if ( _sdVec.empty() )
2124 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2129 //================================================================================
2131 * \brief Set a _SolidData to be computed before another
2133 //================================================================================
2135 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2137 // check possibility to set this order; get all solids before solidBefore
2138 TopTools_IndexedMapOfShape allSolidsBefore;
2139 allSolidsBefore.Add( solidBefore._solid );
2140 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2142 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2145 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2146 for ( ; soIt.More(); soIt.Next() )
2147 allSolidsBefore.Add( soIt.Value() );
2150 if ( allSolidsBefore.Contains( solidAfter._solid ))
2153 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2154 solidAfter._before.Add( allSolidsBefore(i) );
2159 //================================================================================
2163 //================================================================================
2165 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2167 SMESH_MesherHelper helper( *_mesh );
2168 TopExp_Explorer exp;
2170 // collect all faces-to-ignore defined by hyp
2171 for ( size_t i = 0; i < _sdVec.size(); ++i )
2173 // get faces-to-ignore defined by each hyp
2174 typedef const StdMeshers_ViscousLayers* THyp;
2175 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2176 list< TFacesOfHyp > ignoreFacesOfHyps;
2177 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2178 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2179 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2181 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2182 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2185 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2186 const int nbHyps = _sdVec[i]._hyps.size();
2189 // check if two hypotheses define different parameters for the same FACE
2190 list< TFacesOfHyp >::iterator igFacesOfHyp;
2191 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2193 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2195 igFacesOfHyp = ignoreFacesOfHyps.begin();
2196 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2197 if ( ! igFacesOfHyp->first.count( faceID ))
2200 return error(SMESH_Comment("Several hypotheses define "
2201 "Viscous Layers on the face #") << faceID );
2202 hyp = igFacesOfHyp->second;
2205 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2207 _sdVec[i]._ignoreFaceIds.insert( faceID );
2210 // check if two hypotheses define different number of viscous layers for
2211 // adjacent faces of a solid
2212 set< int > nbLayersSet;
2213 igFacesOfHyp = ignoreFacesOfHyps.begin();
2214 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2216 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2218 if ( nbLayersSet.size() > 1 )
2220 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2222 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2223 THyp hyp1 = 0, hyp2 = 0;
2224 while( const TopoDS_Shape* face = fIt->next() )
2226 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2227 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2228 if ( f2h != _sdVec[i]._face2hyp.end() )
2230 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2233 if ( hyp1 && hyp2 &&
2234 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2236 return error("Two hypotheses define different number of "
2237 "viscous layers on adjacent faces");
2241 } // if ( nbHyps > 1 )
2244 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2248 if ( onlyWith ) // is called to check hypotheses compatibility only
2251 // fill _SolidData::_reversedFaceIds
2252 for ( size_t i = 0; i < _sdVec.size(); ++i )
2254 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2255 for ( ; exp.More(); exp.Next() )
2257 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2258 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2259 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2260 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2261 helper.IsReversedSubMesh( face ))
2263 _sdVec[i]._reversedFaceIds.insert( faceID );
2268 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2269 TopTools_IndexedMapOfShape shapes;
2270 std::string structAlgoName = "Hexa_3D";
2271 for ( size_t i = 0; i < _sdVec.size(); ++i )
2274 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2275 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2277 const TopoDS_Shape& edge = shapes(iE);
2278 // find 2 FACEs sharing an EDGE
2280 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2281 while ( fIt->more())
2283 const TopoDS_Shape* f = fIt->next();
2284 FF[ int( !FF[0].IsNull()) ] = *f;
2286 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2288 // check presence of layers on them
2290 for ( int j = 0; j < 2; ++j )
2291 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2292 if ( ignore[0] == ignore[1] )
2293 continue; // nothing interesting
2294 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2297 if ( !fWOL.IsNull())
2299 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2300 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2305 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2307 for ( size_t i = 0; i < _sdVec.size(); ++i )
2310 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2311 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2313 const TopoDS_Shape& vertex = shapes(iV);
2314 // find faces WOL sharing the vertex
2315 vector< TopoDS_Shape > facesWOL;
2316 size_t totalNbFaces = 0;
2317 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2318 while ( fIt->more())
2320 const TopoDS_Shape* f = fIt->next();
2322 const int fID = getMeshDS()->ShapeToIndex( *f );
2323 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2324 facesWOL.push_back( *f );
2326 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2327 continue; // no layers at this vertex or no WOL
2328 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2329 switch ( facesWOL.size() )
2333 helper.SetSubShape( facesWOL[0] );
2334 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2336 TopoDS_Shape seamEdge;
2337 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2338 while ( eIt->more() && seamEdge.IsNull() )
2340 const TopoDS_Shape* e = eIt->next();
2341 if ( helper.IsRealSeam( *e ) )
2344 if ( !seamEdge.IsNull() )
2346 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2350 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2355 // find an edge shared by 2 faces
2356 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2357 while ( eIt->more())
2359 const TopoDS_Shape* e = eIt->next();
2360 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2361 helper.IsSubShape( *e, facesWOL[1]))
2363 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2369 return error("Not yet supported case", _sdVec[i]._index);
2374 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2375 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2376 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2377 for ( size_t i = 0; i < _sdVec.size(); ++i )
2379 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2380 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2382 const TopoDS_Shape& fWOL = e2f->second;
2383 const TGeomID edgeID = e2f->first;
2384 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2385 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2386 if ( edge.ShapeType() != TopAbs_EDGE )
2387 continue; // shrink shape is VERTEX
2390 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2391 while ( soIt->more() && solid.IsNull() )
2393 const TopoDS_Shape* so = soIt->next();
2394 if ( !so->IsSame( _sdVec[i]._solid ))
2397 if ( solid.IsNull() )
2400 bool noShrinkE = false;
2401 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2402 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2403 size_t iSolid = _solids.FindIndex( solid ) - 1;
2404 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2406 // the adjacent SOLID has NO layers on fWOL;
2407 // shrink allowed if
2408 // - there are layers on the EDGE in the adjacent SOLID
2409 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2410 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2411 bool shrinkAllowed = (( hasWLAdj ) ||
2412 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2413 noShrinkE = !shrinkAllowed;
2415 else if ( iSolid < _sdVec.size() )
2417 // the adjacent SOLID has layers on fWOL;
2418 // check if SOLID's mesh is unstructured and then try to set it
2419 // to be computed after the i-th solid
2420 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2421 noShrinkE = true; // don't shrink fWOL
2425 // the adjacent SOLID has NO layers at all
2426 noShrinkE = isStructured;
2431 _sdVec[i]._noShrinkShapes.insert( edgeID );
2433 // check if there is a collision with to-shrink-from EDGEs in iSolid
2434 // if ( iSolid < _sdVec.size() )
2437 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2438 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2440 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2441 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2442 // if ( eID == edgeID ||
2443 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2444 // _sdVec[i]._noShrinkShapes.count( eID ))
2446 // for ( int is1st = 0; is1st < 2; ++is1st )
2448 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2449 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2451 // return error("No way to make a conformal mesh with "
2452 // "the given set of faces with layers", _sdVec[i]._index);
2459 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2460 // _shrinkShape2Shape is different in the adjacent SOLID
2461 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2463 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2464 bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2466 if ( iSolid < _sdVec.size() )
2468 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2470 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2471 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2472 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2473 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2474 noShrinkV = (( isStructured ) ||
2475 ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2477 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2481 noShrinkV = noShrinkE;
2486 // the adjacent SOLID has NO layers at all
2493 noShrinkV = noShrinkIfAdjMeshed =
2494 ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2498 if ( noShrinkV && noShrinkIfAdjMeshed )
2500 // noShrinkV if FACEs in the adjacent SOLID are meshed
2501 PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2502 *_mesh, TopAbs_FACE, &solid );
2503 while ( fIt->more() )
2505 const TopoDS_Shape* f = fIt->next();
2506 if ( !f->IsSame( fWOL ))
2508 noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2514 _sdVec[i]._noShrinkShapes.insert( vID );
2517 } // loop on _sdVec[i]._shrinkShape2Shape
2518 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2521 // add FACEs of other SOLIDs to _ignoreFaceIds
2522 for ( size_t i = 0; i < _sdVec.size(); ++i )
2525 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2527 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2529 if ( !shapes.Contains( exp.Current() ))
2530 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2537 //================================================================================
2539 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2541 //================================================================================
2543 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2544 const StdMeshers_ViscousLayers* hyp,
2545 const TopoDS_Shape& hypShape,
2546 set<TGeomID>& ignoreFaceIds)
2548 TopExp_Explorer exp;
2550 vector<TGeomID> ids = hyp->GetBndShapes();
2551 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2553 for ( size_t ii = 0; ii < ids.size(); ++ii )
2555 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2556 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2557 ignoreFaceIds.insert( ids[ii] );
2560 else // FACEs with layers are given
2562 exp.Init( solid, TopAbs_FACE );
2563 for ( ; exp.More(); exp.Next() )
2565 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2566 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2567 ignoreFaceIds.insert( faceInd );
2571 // ignore internal FACEs if inlets and outlets are specified
2572 if ( hyp->IsToIgnoreShapes() )
2574 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2575 TopExp::MapShapesAndAncestors( hypShape,
2576 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2578 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2580 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2581 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2584 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2586 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2591 //================================================================================
2593 * \brief Create the inner surface of the viscous layer and prepare data for infation
2595 //================================================================================
2597 bool _ViscousBuilder::makeLayer(_SolidData& data)
2599 // make a map to find new nodes on sub-shapes shared with other SOLID
2600 map< TGeomID, TNode2Edge* >::iterator s2ne;
2601 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2602 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2604 TGeomID shapeInd = s2s->first;
2605 for ( size_t i = 0; i < _sdVec.size(); ++i )
2607 if ( _sdVec[i]._index == data._index ) continue;
2608 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2609 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2610 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2612 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2618 // Create temporary faces and _LayerEdge's
2620 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2622 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2624 data._stepSize = Precision::Infinite();
2625 data._stepSizeNodes[0] = 0;
2627 SMESH_MesherHelper helper( *_mesh );
2628 helper.SetSubShape( data._solid );
2629 helper.SetElementsOnShape( true );
2631 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2632 TNode2Edge::iterator n2e2;
2634 // make _LayerEdge's
2635 for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2637 const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2638 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2639 const TGeomID id = sm->GetId();
2640 if ( edgesByGeom[ id ]._shape.IsNull() )
2641 continue; // no layers
2642 SMESH_ProxyMesh::SubMesh* proxySub =
2643 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2645 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2646 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2648 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2649 while ( eIt->more() )
2651 const SMDS_MeshElement* face = eIt->next();
2652 double faceMaxCosin = -1;
2653 _LayerEdge* maxCosinEdge = 0;
2654 int nbDegenNodes = 0;
2656 newNodes.resize( face->NbCornerNodes() );
2657 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2659 const SMDS_MeshNode* n = face->GetNode( i );
2660 const int shapeID = n->getshapeId();
2661 const bool onDegenShap = helper.IsDegenShape( shapeID );
2662 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2667 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2668 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2669 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2670 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2680 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2681 if ( !(*n2e).second )
2684 _LayerEdge* edge = _Factory::NewLayerEdge();
2685 edge->_nodes.push_back( n );
2687 edgesByGeom[ shapeID ]._edges.push_back( edge );
2688 const bool noShrink = data._noShrinkShapes.count( shapeID );
2690 SMESH_TNodeXYZ xyz( n );
2692 // set edge data or find already refined _LayerEdge and get data from it
2693 if (( !noShrink ) &&
2694 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2695 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2696 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2698 _LayerEdge* foundEdge = (*n2e2).second;
2699 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2700 foundEdge->_pos.push_back( lastPos );
2701 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2702 const_cast< SMDS_MeshNode* >
2703 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2709 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2711 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2714 if ( edge->_nodes.size() < 2 )
2715 edge->Block( data );
2716 //data._noShrinkShapes.insert( shapeID );
2718 dumpMove(edge->_nodes.back());
2720 if ( edge->_cosin > faceMaxCosin )
2722 faceMaxCosin = edge->_cosin;
2723 maxCosinEdge = edge;
2726 newNodes[ i ] = n2e->second->_nodes.back();
2729 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2731 if ( newNodes.size() - nbDegenNodes < 2 )
2734 // create a temporary face
2735 const SMDS_MeshElement* newFace =
2736 new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2737 proxySub->AddElement( newFace );
2739 // compute inflation step size by min size of element on a convex surface
2740 if ( faceMaxCosin > theMinSmoothCosin )
2741 limitStepSize( data, face, maxCosinEdge );
2743 } // loop on 2D elements on a FACE
2744 } // loop on FACEs of a SOLID to create _LayerEdge's
2747 // Set _LayerEdge::_neibors
2748 TNode2Edge::iterator n2e;
2749 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2751 _EdgesOnShape& eos = data._edgesOnShape[iS];
2752 for ( size_t i = 0; i < eos._edges.size(); ++i )
2754 _LayerEdge* edge = eos._edges[i];
2755 TIDSortedNodeSet nearNodes;
2756 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2757 while ( fIt->more() )
2759 const SMDS_MeshElement* f = fIt->next();
2760 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2761 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2763 nearNodes.erase( edge->_nodes[0] );
2764 edge->_neibors.reserve( nearNodes.size() );
2765 TIDSortedNodeSet::iterator node = nearNodes.begin();
2766 for ( ; node != nearNodes.end(); ++node )
2767 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2768 edge->_neibors.push_back( n2e->second );
2772 data._epsilon = 1e-7;
2773 if ( data._stepSize < 1. )
2774 data._epsilon *= data._stepSize;
2776 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2779 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2780 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2782 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2783 const SMDS_MeshNode* nn[2];
2784 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2786 _EdgesOnShape& eos = data._edgesOnShape[iS];
2787 for ( size_t i = 0; i < eos._edges.size(); ++i )
2789 _LayerEdge* edge = eos._edges[i];
2790 if ( edge->IsOnEdge() )
2792 // get neighbor nodes
2793 bool hasData = ( edge->_2neibors->_edges[0] );
2794 if ( hasData ) // _LayerEdge is a copy of another one
2796 nn[0] = edge->_2neibors->srcNode(0);
2797 nn[1] = edge->_2neibors->srcNode(1);
2799 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2803 // set neighbor _LayerEdge's
2804 for ( int j = 0; j < 2; ++j )
2806 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2807 return error("_LayerEdge not found by src node", data._index);
2808 edge->_2neibors->_edges[j] = n2e->second;
2811 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2814 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2816 _Simplex& s = edge->_simplices[j];
2817 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2818 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2821 // For an _LayerEdge on a degenerated EDGE, copy some data from
2822 // a corresponding _LayerEdge on a VERTEX
2823 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2824 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2826 // Generally we should not get here
2827 if ( eos.ShapeType() != TopAbs_EDGE )
2829 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2830 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2831 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2833 const _LayerEdge* vEdge = n2e->second;
2834 edge->_normal = vEdge->_normal;
2835 edge->_lenFactor = vEdge->_lenFactor;
2836 edge->_cosin = vEdge->_cosin;
2839 } // loop on data._edgesOnShape._edges
2840 } // loop on data._edgesOnShape
2842 // fix _LayerEdge::_2neibors on EDGEs to smooth
2843 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2844 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2845 // if ( !e2c->second.IsNull() )
2847 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2848 // data.Sort2NeiborsOnEdge( eos->_edges );
2855 //================================================================================
2857 * \brief Compute inflation step size by min size of element on a convex surface
2859 //================================================================================
2861 void _ViscousBuilder::limitStepSize( _SolidData& data,
2862 const SMDS_MeshElement* face,
2863 const _LayerEdge* maxCosinEdge )
2866 double minSize = 10 * data._stepSize;
2867 const int nbNodes = face->NbCornerNodes();
2868 for ( int i = 0; i < nbNodes; ++i )
2870 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2871 const SMDS_MeshNode* curN = face->GetNode( i );
2872 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2873 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2875 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2876 if ( dist < minSize )
2877 minSize = dist, iN = i;
2880 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2881 if ( newStep < data._stepSize )
2883 data._stepSize = newStep;
2884 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2885 data._stepSizeNodes[0] = face->GetNode( iN );
2886 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2890 //================================================================================
2892 * \brief Compute inflation step size by min size of element on a convex surface
2894 //================================================================================
2896 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2898 if ( minSize < data._stepSize )
2900 data._stepSize = minSize;
2901 if ( data._stepSizeNodes[0] )
2904 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2905 data._stepSizeCoeff = data._stepSize / dist;
2910 //================================================================================
2912 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2914 //================================================================================
2916 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2918 SMESH_MesherHelper helper( *_mesh );
2920 BRepLProp_SLProps surfProp( 2, 1e-6 );
2921 data._convexFaces.clear();
2923 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2925 _EdgesOnShape& eof = data._edgesOnShape[iS];
2926 if ( eof.ShapeType() != TopAbs_FACE ||
2927 data._ignoreFaceIds.count( eof._shapeID ))
2930 TopoDS_Face F = TopoDS::Face( eof._shape );
2931 const TGeomID faceID = eof._shapeID;
2933 BRepAdaptor_Surface surface( F, false );
2934 surfProp.SetSurface( surface );
2936 _ConvexFace cnvFace;
2938 cnvFace._normalsFixed = false;
2939 cnvFace._isTooCurved = false;
2941 double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2942 if ( maxCurvature > 0 )
2944 limitStepSize( data, 0.9 / maxCurvature );
2945 findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2947 if ( !cnvFace._isTooCurved ) continue;
2949 _ConvexFace & convFace =
2950 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2952 // skip a closed surface (data._convexFaces is useful anyway)
2953 bool isClosedF = false;
2954 helper.SetSubShape( F );
2955 if ( helper.HasRealSeam() )
2957 // in the closed surface there must be a closed EDGE
2958 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2959 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2963 // limit _LayerEdge::_maxLen on the FACE
2964 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2965 const double minCurvature =
2966 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2967 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2968 if ( id2eos != cnvFace._subIdToEOS.end() )
2970 _EdgesOnShape& eos = * id2eos->second;
2971 for ( size_t i = 0; i < eos._edges.size(); ++i )
2973 _LayerEdge* ledge = eos._edges[ i ];
2974 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2975 surfProp.SetParameters( uv.X(), uv.Y() );
2976 if ( surfProp.IsCurvatureDefined() )
2978 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2979 surfProp.MinCurvature() * oriFactor );
2980 if ( curvature > minCurvature )
2981 ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2988 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2989 // prism distortion.
2990 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2991 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2993 // there are _LayerEdge's on the FACE it-self;
2994 // select _LayerEdge's near EDGEs
2995 _EdgesOnShape& eos = * id2eos->second;
2996 for ( size_t i = 0; i < eos._edges.size(); ++i )
2998 _LayerEdge* ledge = eos._edges[ i ];
2999 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
3000 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
3002 // do not select _LayerEdge's neighboring sharp EDGEs
3003 bool sharpNbr = false;
3004 for ( size_t iN = 0; iN < ledge->_neibors.size() && !sharpNbr; ++iN )
3005 sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
3007 convFace._simplexTestEdges.push_back( ledge );
3014 // where there are no _LayerEdge's on a _ConvexFace,
3015 // as e.g. on a fillet surface with no internal nodes - issue 22580,
3016 // so that collision of viscous internal faces is not detected by check of
3017 // intersection of _LayerEdge's with the viscous internal faces.
3019 set< const SMDS_MeshNode* > usedNodes;
3021 // look for _LayerEdge's with null _sWOL
3022 id2eos = convFace._subIdToEOS.begin();
3023 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3025 _EdgesOnShape& eos = * id2eos->second;
3026 if ( !eos._sWOL.IsNull() )
3028 for ( size_t i = 0; i < eos._edges.size(); ++i )
3030 _LayerEdge* ledge = eos._edges[ i ];
3031 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3032 if ( !usedNodes.insert( srcNode ).second ) continue;
3034 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3036 usedNodes.insert( ledge->_simplices[i]._nPrev );
3037 usedNodes.insert( ledge->_simplices[i]._nNext );
3039 convFace._simplexTestEdges.push_back( ledge );
3043 } // loop on FACEs of data._solid
3046 //================================================================================
3048 * \brief Detect shapes (and _LayerEdge's on them) to smooth
3050 //================================================================================
3052 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3054 // define allowed thickness
3055 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3058 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3059 // boundary inclined to the shape at a sharp angle
3061 TopTools_MapOfShape edgesOfSmooFaces;
3062 SMESH_MesherHelper helper( *_mesh );
3065 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3066 data._nbShapesToSmooth = 0;
3068 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3070 _EdgesOnShape& eos = edgesByGeom[iS];
3071 eos._toSmooth = false;
3072 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3075 double tgtThick = eos._hyp.GetTotalThickness();
3076 SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3077 while ( subIt->more() && !eos._toSmooth )
3079 TGeomID iSub = subIt->next()->GetId();
3080 const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3081 if ( eSub.empty() ) continue;
3084 for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3085 if ( eSub[i]->_cosin > theMinSmoothCosin )
3087 SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3088 while ( fIt->more() && !eos._toSmooth )
3090 const SMDS_MeshElement* face = fIt->next();
3091 if ( face->getshapeId() == eos._shapeID &&
3092 getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3094 eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3095 tgtThick * eSub[i]->_lenFactor,
3101 if ( eos._toSmooth )
3103 for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3104 edgesOfSmooFaces.Add( eExp.Current() );
3106 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3108 data._nbShapesToSmooth += eos._toSmooth;
3112 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3114 _EdgesOnShape& eos = edgesByGeom[iS];
3115 eos._edgeSmoother = NULL;
3116 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3117 if ( !eos._hyp.ToSmooth() ) continue;
3119 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3120 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3123 double tgtThick = eos._hyp.GetTotalThickness();
3124 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3126 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3127 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3128 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3129 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3130 double angle = eDir.Angle( eV[0]->_normal );
3131 double cosin = Cos( angle );
3132 double cosinAbs = Abs( cosin );
3133 if ( cosinAbs > theMinSmoothCosin )
3135 // always smooth analytic EDGEs
3136 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3137 eos._toSmooth = ! curve.IsNull();
3139 // compare tgtThick with the length of an end segment
3140 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3141 while ( eIt->more() && !eos._toSmooth )
3143 const SMDS_MeshElement* endSeg = eIt->next();
3144 if ( endSeg->getshapeId() == (int) iS )
3147 SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3148 eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3151 if ( eos._toSmooth )
3153 eos._edgeSmoother = new _Smoother1D( curve, eos );
3155 // for ( size_t i = 0; i < eos._edges.size(); ++i )
3156 // eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3160 data._nbShapesToSmooth += eos._toSmooth;
3164 // Reset _cosin if no smooth is allowed by the user
3165 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3167 _EdgesOnShape& eos = edgesByGeom[iS];
3168 if ( eos._edges.empty() ) continue;
3170 if ( !eos._hyp.ToSmooth() )
3171 for ( size_t i = 0; i < eos._edges.size(); ++i )
3172 //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3173 eos._edges[i]->_lenFactor = 1;
3177 // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3179 TopTools_MapOfShape c1VV;
3181 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3183 _EdgesOnShape& eos = edgesByGeom[iS];
3184 if ( eos._edges.empty() ||
3185 eos.ShapeType() != TopAbs_FACE ||
3189 // check EDGEs of a FACE
3190 TopTools_MapOfShape checkedEE, allVV;
3191 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3192 while ( !smQueue.empty() )
3194 SMESH_subMesh* sm = smQueue.front();
3195 smQueue.pop_front();
3196 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3197 while ( smIt->more() )
3200 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3201 allVV.Add( sm->GetSubShape() );
3202 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3203 !checkedEE.Add( sm->GetSubShape() ))
3206 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3207 vector<_LayerEdge*>& eE = eoe->_edges;
3208 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3211 bool isC1 = true; // check continuity along an EDGE
3212 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3213 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3217 // check that mesh faces are C1 as well
3219 gp_XYZ norm1, norm2;
3220 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3221 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3222 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3224 while ( fIt->more() && isC1 )
3225 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3226 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3231 // add the EDGE and an adjacent FACE to _eosC1
3232 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3233 while ( const TopoDS_Shape* face = fIt->next() )
3235 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3236 if ( !eof ) continue; // other solid
3237 if ( eos._shapeID == eof->_shapeID ) continue;
3238 if ( !eos.HasC1( eof ))
3241 eos._eosC1.push_back( eof );
3242 eof->_toSmooth = false;
3243 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3244 smQueue.push_back( eof->_subMesh );
3246 if ( !eos.HasC1( eoe ))
3248 eos._eosC1.push_back( eoe );
3249 eoe->_toSmooth = false;
3250 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3255 if ( eos._eosC1.empty() )
3258 // check VERTEXes of C1 FACEs
3259 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3260 for ( ; vIt.More(); vIt.Next() )
3262 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3263 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3266 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3267 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3268 while ( const TopoDS_Shape* face = fIt->next() )
3270 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3271 if ( !eof ) continue; // other solid
3272 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3278 eos._eosC1.push_back( eov );
3279 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3280 c1VV.Add( eov->_shape );
3284 } // fill _eosC1 of FACEs
3289 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3291 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3293 _EdgesOnShape& eov = edgesByGeom[iS];
3294 if ( eov._edges.empty() ||
3295 eov.ShapeType() != TopAbs_VERTEX ||
3296 c1VV.Contains( eov._shape ))
3298 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3300 // get directions of surrounding EDGEs
3302 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3303 while ( const TopoDS_Shape* e = fIt->next() )
3305 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3306 if ( !eoe ) continue; // other solid
3307 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3308 if ( !Precision::IsInfinite( eDir.X() ))
3309 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3312 // find EDGEs with C1 directions
3313 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3314 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3315 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3317 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3318 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3321 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3322 for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3324 size_t k = isJ ? j : i;
3325 const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3326 double eLen = SMESH_Algo::EdgeLength( e );
3327 if ( eLen < maxEdgeLen )
3329 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3330 if ( oppV.IsSame( V ))
3331 oppV = SMESH_MesherHelper::IthVertex( 1, e );
3332 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3333 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3334 eov._eosC1.push_back( dirOfEdges[k].first );
3336 dirOfEdges[k].first = 0;
3340 } // fill _eosC1 of VERTEXes
3347 //================================================================================
3349 * \brief Set up _SolidData::_edgesOnShape
3351 //================================================================================
3353 void _ViscousBuilder::makeEdgesOnShape()
3355 const int nbShapes = getMeshDS()->MaxShapeIndex();
3357 for ( size_t i = 0; i < _sdVec.size(); ++i )
3359 _SolidData& data = _sdVec[ i ];
3360 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3361 edgesByGeom.resize( nbShapes+1 );
3363 // set data of _EdgesOnShape's
3364 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3366 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3367 while ( smIt->more() )
3370 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3371 data._ignoreFaceIds.count( sm->GetId() ))
3374 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3380 //================================================================================
3382 * \brief initialize data of _EdgesOnShape
3384 //================================================================================
3386 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3390 if ( !eos._shape.IsNull() ||
3391 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3394 SMESH_MesherHelper helper( *_mesh );
3397 eos._shapeID = sm->GetId();
3398 eos._shape = sm->GetSubShape();
3399 if ( eos.ShapeType() == TopAbs_FACE )
3400 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3401 eos._toSmooth = false;
3405 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3406 data._shrinkShape2Shape.find( eos._shapeID );
3407 if ( s2s != data._shrinkShape2Shape.end() )
3408 eos._sWOL = s2s->second;
3410 eos._isRegularSWOL = true;
3411 if ( eos.SWOLType() == TopAbs_FACE )
3413 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3414 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3415 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3419 if ( data._hyps.size() == 1 )
3421 eos._hyp = data._hyps.back();
3425 // compute average StdMeshers_ViscousLayers parameters
3426 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3427 if ( eos.ShapeType() == TopAbs_FACE )
3429 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3430 eos._hyp = f2hyp->second;
3434 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3435 while ( const TopoDS_Shape* face = fIt->next() )
3437 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3438 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3439 eos._hyp.Add( f2hyp->second );
3445 if ( ! eos._hyp.UseSurfaceNormal() )
3447 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3449 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3450 if ( !smDS ) return;
3451 eos._faceNormals.reserve( smDS->NbElements() );
3453 double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3454 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3455 for ( ; eIt->more(); )
3457 const SMDS_MeshElement* face = eIt->next();
3458 gp_XYZ& norm = eos._faceNormals[face];
3459 if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3460 norm.SetCoord( 0,0,0 );
3464 else // find EOS of adjacent FACEs
3466 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3467 while ( const TopoDS_Shape* face = fIt->next() )
3469 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3470 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3471 if ( eos._faceEOS.back()->_shape.IsNull() )
3472 // avoid using uninitialised _shapeID in GetNormal()
3473 eos._faceEOS.back()->_shapeID = faceID;
3479 //================================================================================
3481 * \brief Returns normal of a face
3483 //================================================================================
3485 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3488 _EdgesOnShape* eos = 0;
3490 if ( face->getshapeId() == _shapeID )
3496 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3497 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3498 eos = _faceEOS[ iF ];
3502 ( ok = ( eos->_faceNormals.count( face ) )))
3504 norm = eos->_faceNormals[ face ];
3508 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3509 << " on _shape #" << _shapeID );
3514 //================================================================================
3516 * \brief EdgesOnShape destructor
3518 //================================================================================
3520 _EdgesOnShape::~_EdgesOnShape()
3522 delete _edgeSmoother;
3525 //================================================================================
3527 * \brief Set data of _LayerEdge needed for smoothing
3529 //================================================================================
3531 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3533 SMESH_MesherHelper& helper,
3536 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3539 edge._maxLen = Precision::Infinite();
3542 edge._curvature = 0;
3544 edge._smooFunction = 0;
3546 // --------------------------
3547 // Compute _normal and _cosin
3548 // --------------------------
3551 edge._lenFactor = 1.;
3552 edge._normal.SetCoord(0,0,0);
3553 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3555 int totalNbFaces = 0;
3557 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3561 const bool onShrinkShape = !eos._sWOL.IsNull();
3562 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3563 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3565 // get geom FACEs the node lies on
3566 //if ( useGeometry )
3568 set<TGeomID> faceIds;
3569 if ( eos.ShapeType() == TopAbs_FACE )
3571 faceIds.insert( eos._shapeID );
3575 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3576 while ( fIt->more() )
3577 faceIds.insert( fIt->next()->getshapeId() );
3579 set<TGeomID>::iterator id = faceIds.begin();
3580 for ( ; id != faceIds.end(); ++id )
3582 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3583 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3585 F = TopoDS::Face( s );
3586 face2Norm[ totalNbFaces ].first = F;
3592 bool fromVonF = false;
3595 fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3596 eos.SWOLType() == TopAbs_FACE &&
3599 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3601 if ( eos.SWOLType() == TopAbs_EDGE )
3603 // inflate from VERTEX along EDGE
3604 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3606 else if ( eos.ShapeType() == TopAbs_VERTEX )
3608 // inflate from VERTEX along FACE
3609 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3610 node, helper, normOK, &edge._cosin);
3614 // inflate from EDGE along FACE
3615 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3616 node, helper, normOK);
3619 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3622 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3625 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3627 F = face2Norm[ iF ].first;
3628 geomNorm = getFaceNormal( node, F, helper, normOK );
3629 if ( !normOK ) continue;
3632 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3634 face2Norm[ iF ].second = geomNorm.XYZ();
3635 edge._normal += geomNorm.XYZ();
3637 if ( nbOkNorms == 0 )
3638 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3640 if ( totalNbFaces >= 3 )
3642 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3645 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3647 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3648 edge._normal.SetCoord( 0,0,0 );
3649 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3651 const TopoDS_Face& F = face2Norm[iF].first;
3652 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3653 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3656 face2Norm[ iF ].second = geomNorm.XYZ();
3657 edge._normal += face2Norm[ iF ].second;
3662 else // !useGeometry - get _normal using surrounding mesh faces
3664 edge._normal = getWeigthedNormal( &edge );
3666 // set<TGeomID> faceIds;
3668 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3669 // while ( fIt->more() )
3671 // const SMDS_MeshElement* face = fIt->next();
3672 // if ( eos.GetNormal( face, geomNorm ))
3674 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3675 // continue; // use only one mesh face on FACE
3676 // edge._normal += geomNorm.XYZ();
3683 //if ( eos._hyp.UseSurfaceNormal() )
3685 switch ( eos.ShapeType() )
3692 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3693 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3694 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3695 edge._cosin = Cos( angle );
3698 case TopAbs_VERTEX: {
3701 getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3702 node, helper, normOK, &edge._cosin );
3704 else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3706 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3707 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3708 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3709 edge._cosin = Cos( angle );
3710 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3711 for ( int iF = 1; iF < totalNbFaces; ++iF )
3713 F = face2Norm[ iF ].first;
3714 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3716 double angle = inFaceDir.Angle( edge._normal );
3717 double cosin = Cos( angle );
3718 if ( Abs( cosin ) > Abs( edge._cosin ))
3719 edge._cosin = cosin;
3726 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3730 double normSize = edge._normal.SquareModulus();
3731 if ( normSize < numeric_limits<double>::min() )
3732 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3734 edge._normal /= sqrt( normSize );
3736 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3738 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3739 edge._nodes.resize( 1 );
3740 edge._normal.SetCoord( 0,0,0 );
3741 edge.SetMaxLen( 0 );
3744 // Set the rest data
3745 // --------------------
3747 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3749 if ( onShrinkShape )
3751 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3752 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3753 sm->RemoveNode( tgtNode );
3755 // set initial position which is parameters on _sWOL in this case
3756 if ( eos.SWOLType() == TopAbs_EDGE )
3758 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3759 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3760 if ( edge._nodes.size() > 1 )
3761 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3763 else // eos.SWOLType() == TopAbs_FACE
3765 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3766 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3767 if ( edge._nodes.size() > 1 )
3768 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3771 if ( edge._nodes.size() > 1 )
3773 // check if an angle between a FACE with layers and SWOL is sharp,
3774 // else the edge should not inflate
3776 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3777 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3778 F = face2Norm[iF].first;
3781 geomNorm = getFaceNormal( node, F, helper, normOK );
3782 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3783 geomNorm.Reverse(); // inside the SOLID
3784 if ( geomNorm * edge._normal < -0.001 )
3786 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3787 edge._nodes.resize( 1 );
3789 else if ( edge._lenFactor > 3 )
3791 edge._lenFactor = 2;
3792 edge.Set( _LayerEdge::RISKY_SWOL );
3799 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3801 if ( eos.ShapeType() == TopAbs_FACE )
3804 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3806 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3807 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3812 // Set neighbor nodes for a _LayerEdge based on EDGE
3814 if ( eos.ShapeType() == TopAbs_EDGE /*||
3815 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3817 edge._2neibors = _Factory::NewNearEdges();
3818 // target nodes instead of source ones will be set later
3824 //================================================================================
3826 * \brief Return normal to a FACE at a node
3827 * \param [in] n - node
3828 * \param [in] face - FACE
3829 * \param [in] helper - helper
3830 * \param [out] isOK - true or false
3831 * \param [in] shiftInside - to find normal at a position shifted inside the face
3832 * \return gp_XYZ - normal
3834 //================================================================================
3836 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3837 const TopoDS_Face& face,
3838 SMESH_MesherHelper& helper,
3845 // get a shifted position
3846 gp_Pnt p = SMESH_TNodeXYZ( node );
3847 gp_XYZ shift( 0,0,0 );
3848 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3849 switch ( S.ShapeType() ) {
3852 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3857 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3865 p.Translate( shift * 1e-5 );
3867 TopLoc_Location loc;
3868 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3870 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3872 projector.Perform( p );
3873 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3879 projector.LowerDistanceParameters(U,V);
3884 uv = helper.GetNodeUV( face, node, 0, &isOK );
3890 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3892 if ( !shiftInside &&
3893 helper.IsDegenShape( node->getshapeId() ) &&
3894 getFaceNormalAtSingularity( uv, face, helper, normal ))
3897 return normal.XYZ();
3900 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3901 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3903 if ( pointKind == IMPOSSIBLE &&
3904 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3906 // probably NormEstim() failed due to a too high tolerance
3907 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3908 isOK = ( pointKind < IMPOSSIBLE );
3910 if ( pointKind < IMPOSSIBLE )
3912 if ( pointKind != REGULAR &&
3914 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3916 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3917 if ( normShift * normal.XYZ() < 0. )
3923 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3925 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3927 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3928 while ( fIt->more() )
3930 const SMDS_MeshElement* f = fIt->next();
3931 if ( f->getshapeId() == faceID )
3933 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3936 TopoDS_Face ff = face;
3937 ff.Orientation( TopAbs_FORWARD );
3938 if ( helper.IsReversedSubMesh( ff ))
3945 return normal.XYZ();
3948 //================================================================================
3950 * \brief Try to get normal at a singularity of a surface basing on it's nature
3952 //================================================================================
3954 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3955 const TopoDS_Face& face,
3956 SMESH_MesherHelper& helper,
3959 BRepAdaptor_Surface surface( face );
3961 if ( !getRovolutionAxis( surface, axis ))
3964 double f,l, d, du, dv;
3965 f = surface.FirstUParameter();
3966 l = surface.LastUParameter();
3967 d = ( uv.X() - f ) / ( l - f );
3968 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3969 f = surface.FirstVParameter();
3970 l = surface.LastVParameter();
3971 d = ( uv.Y() - f ) / ( l - f );
3972 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3975 gp_Pnt2d testUV = uv;
3976 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3978 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3979 for ( int iLoop = 0; true ; ++iLoop )
3981 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3982 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3989 if ( axis * refDir < 0. )
3997 //================================================================================
3999 * \brief Return a normal at a node weighted with angles taken by faces
4001 //================================================================================
4003 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
4005 const SMDS_MeshNode* n = edge->_nodes[0];
4007 gp_XYZ resNorm(0,0,0);
4008 SMESH_TNodeXYZ p0( n ), pP, pN;
4009 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4011 pP.Set( edge->_simplices[i]._nPrev );
4012 pN.Set( edge->_simplices[i]._nNext );
4013 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
4014 double l0P = v0P.SquareMagnitude();
4015 double l0N = v0N.SquareMagnitude();
4016 double lPN = vPN.SquareMagnitude();
4017 if ( l0P < std::numeric_limits<double>::min() ||
4018 l0N < std::numeric_limits<double>::min() ||
4019 lPN < std::numeric_limits<double>::min() )
4021 double lNorm = norm.SquareMagnitude();
4022 double sin2 = lNorm / l0P / l0N;
4023 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4025 double weight = sin2 * angle / lPN;
4026 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4032 //================================================================================
4034 * \brief Return a normal at a node by getting a common point of offset planes
4035 * defined by the FACE normals
4037 //================================================================================
4039 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
4040 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4044 SMESH_TNodeXYZ p0 = edge->_nodes[0];
4046 gp_XYZ resNorm(0,0,0);
4047 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4048 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4050 for ( int i = 0; i < nbFaces; ++i )
4051 resNorm += f2Normal[i].second;
4055 // prepare _OffsetPlane's
4056 vector< _OffsetPlane > pln( nbFaces );
4057 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4059 pln[i]._faceIndex = i;
4060 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4064 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4065 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4068 // intersect neighboring OffsetPlane's
4069 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4070 while ( const TopoDS_Shape* edge = edgeIt->next() )
4072 int f1 = -1, f2 = -1;
4073 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
4074 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4075 (( f1 < 0 ) ? f1 : f2 ) = i;
4078 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4081 // get a common point
4082 gp_XYZ commonPnt( 0, 0, 0 );
4085 for ( int i = 0; i < nbFaces; ++i )
4087 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4088 nbPoints += isPointFound;
4090 gp_XYZ wgtNorm = getWeigthedNormal( edge );
4091 if ( nbPoints == 0 )
4094 commonPnt /= nbPoints;
4095 resNorm = commonPnt - p0;
4099 // choose the best among resNorm and wgtNorm
4100 resNorm.Normalize();
4101 wgtNorm.Normalize();
4102 double resMinDot = std::numeric_limits<double>::max();
4103 double wgtMinDot = std::numeric_limits<double>::max();
4104 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4106 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4107 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4110 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4112 edge->Set( _LayerEdge::MULTI_NORMAL );
4115 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4118 //================================================================================
4120 * \brief Compute line of intersection of 2 planes
4122 //================================================================================
4124 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
4125 const TopoDS_Edge& E,
4126 const TopoDS_Vertex& V )
4128 int iNext = bool( _faceIndexNext[0] >= 0 );
4129 _faceIndexNext[ iNext ] = pln._faceIndex;
4131 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4132 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4134 gp_XYZ lineDir = n1 ^ n2;
4136 double x = Abs( lineDir.X() );
4137 double y = Abs( lineDir.Y() );
4138 double z = Abs( lineDir.Z() );
4140 int cooMax; // max coordinate
4142 if (x > z) cooMax = 1;
4146 if (y > z) cooMax = 2;
4151 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4153 // parallel planes - intersection is an offset of the common EDGE
4154 gp_Pnt p = BRep_Tool::Pnt( V );
4155 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4156 lineDir = getEdgeDir( E, V );
4160 // the constants in the 2 plane equations
4161 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
4162 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4167 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4168 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4171 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4173 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4176 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4177 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4181 gp_Lin& line = _lines[ iNext ];
4182 line.SetDirection( lineDir );
4183 line.SetLocation ( linePos );
4185 _isLineOK[ iNext ] = true;
4188 iNext = bool( pln._faceIndexNext[0] >= 0 );
4189 pln._lines [ iNext ] = line;
4190 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4191 pln._isLineOK [ iNext ] = true;
4194 //================================================================================
4196 * \brief Computes intersection point of two _lines
4198 //================================================================================
4200 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4201 const TopoDS_Vertex & V) const
4206 if ( NbLines() == 2 )
4208 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4209 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4210 if ( Abs( dot01 ) > 0.05 )
4212 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4213 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4214 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4219 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4220 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4221 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4222 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4223 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4231 //================================================================================
4233 * \brief Find 2 neighbor nodes of a node on EDGE
4235 //================================================================================
4237 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4238 const SMDS_MeshNode*& n1,
4239 const SMDS_MeshNode*& n2,
4243 const SMDS_MeshNode* node = edge->_nodes[0];
4244 const int shapeInd = eos._shapeID;
4245 SMESHDS_SubMesh* edgeSM = 0;
4246 if ( eos.ShapeType() == TopAbs_EDGE )
4248 edgeSM = eos._subMesh->GetSubMeshDS();
4249 if ( !edgeSM || edgeSM->NbElements() == 0 )
4250 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4254 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4255 while ( eIt->more() && !n2 )
4257 const SMDS_MeshElement* e = eIt->next();
4258 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4259 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4262 if (!edgeSM->Contains(e)) continue;
4266 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4267 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4269 ( iN++ ? n2 : n1 ) = nNeibor;
4272 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4276 //================================================================================
4278 * \brief Create _Curvature
4280 //================================================================================
4282 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4284 // double _r; // radius
4285 // double _k; // factor to correct node smoothed position
4286 // double _h2lenRatio; // avgNormProj / (2*avgDist)
4287 // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4290 if ( fabs( avgNormProj / avgDist ) > 1./200 )
4292 c = _Factory::NewCurvature();
4293 c->_r = avgDist * avgDist / avgNormProj;
4294 c->_k = avgDist * avgDist / c->_r / c->_r;
4295 //c->_k = avgNormProj / c->_r;
4296 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4297 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4299 c->_uv.SetCoord( 0., 0. );
4304 //================================================================================
4306 * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4308 //================================================================================
4310 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4311 const SMDS_MeshNode* n2,
4312 const _EdgesOnShape& eos,
4313 SMESH_MesherHelper& helper)
4315 if ( eos.ShapeType() != TopAbs_EDGE )
4317 if ( _curvature && Is( SMOOTHED_C1 ))
4320 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4321 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4322 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4326 double sumLen = vec1.Modulus() + vec2.Modulus();
4327 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4328 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4329 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4330 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4331 _curvature = _Curvature::New( avgNormProj, avgLen );
4332 // if ( _curvature )
4333 // debugMsg( _nodes[0]->GetID()
4334 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4335 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4336 // << _curvature->lenDelta(0) );
4340 if ( eos._sWOL.IsNull() )
4342 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4343 // if ( SMESH_Algo::isDegenerated( E ))
4345 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4346 gp_XYZ plnNorm = dirE ^ _normal;
4347 double proj0 = plnNorm * vec1;
4348 double proj1 = plnNorm * vec2;
4349 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4351 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4352 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4357 //================================================================================
4359 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4360 * this and the other _LayerEdge are inflated along a FACE or an EDGE
4362 //================================================================================
4364 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4366 SMESH_MesherHelper& helper )
4368 _nodes = other._nodes;
4369 _normal = other._normal;
4371 _lenFactor = other._lenFactor;
4372 _cosin = other._cosin;
4373 _2neibors = other._2neibors;
4374 _curvature = other._curvature;
4375 _2neibors = other._2neibors;
4376 _maxLen = Precision::Infinite();//other._maxLen;
4380 gp_XYZ lastPos( 0,0,0 );
4381 if ( eos.SWOLType() == TopAbs_EDGE )
4383 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4384 _pos.push_back( gp_XYZ( u, 0, 0));
4386 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4391 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4392 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4394 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4395 lastPos.SetX( uv.X() );
4396 lastPos.SetY( uv.Y() );
4401 //================================================================================
4403 * \brief Set _cosin and _lenFactor
4405 //================================================================================
4407 void _LayerEdge::SetCosin( double cosin )
4410 cosin = Abs( _cosin );
4411 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4412 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4415 //================================================================================
4417 * \brief Check if another _LayerEdge is a neighbor on EDGE
4419 //================================================================================
4421 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4423 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4424 ( edge->_2neibors && edge->_2neibors->include( this )));
4427 //================================================================================
4429 * \brief Fills a vector<_Simplex >
4431 //================================================================================
4433 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4434 vector<_Simplex>& simplices,
4435 const set<TGeomID>& ingnoreShapes,
4436 const _SolidData* dataToCheckOri,
4440 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4441 while ( fIt->more() )
4443 const SMDS_MeshElement* f = fIt->next();
4444 const TGeomID shapeInd = f->getshapeId();
4445 if ( ingnoreShapes.count( shapeInd )) continue;
4446 const int nbNodes = f->NbCornerNodes();
4447 const int srcInd = f->GetNodeIndex( node );
4448 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4449 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4450 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4451 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4452 std::swap( nPrev, nNext );
4453 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4457 SortSimplices( simplices );
4460 //================================================================================
4462 * \brief Set neighbor simplices side by side
4464 //================================================================================
4466 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4468 vector<_Simplex> sortedSimplices( simplices.size() );
4469 sortedSimplices[0] = simplices[0];
4471 for ( size_t i = 1; i < simplices.size(); ++i )
4473 for ( size_t j = 1; j < simplices.size(); ++j )
4474 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4476 sortedSimplices[i] = simplices[j];
4481 if ( nbFound == simplices.size() - 1 )
4482 simplices.swap( sortedSimplices );
4485 //================================================================================
4487 * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4489 //================================================================================
4491 void _ViscousBuilder::makeGroupOfLE()
4494 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4496 if ( _sdVec[i]._n2eMap.empty() ) continue;
4498 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4499 TNode2Edge::iterator n2e;
4500 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4502 _LayerEdge* le = n2e->second;
4503 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4504 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4505 // << ", " << le->_nodes[iN]->GetID() <<"])");
4507 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4508 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4513 dumpFunction( SMESH_Comment("makeNormals") << i );
4514 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4516 _LayerEdge* edge = n2e->second;
4517 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4518 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4519 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4520 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4524 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4525 dumpCmd( "faceId1 = mesh.NbElements()" );
4526 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4527 for ( ; fExp.More(); fExp.Next() )
4529 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4531 if ( sm->NbElements() == 0 ) continue;
4532 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4533 while ( fIt->more())
4535 const SMDS_MeshElement* e = fIt->next();
4536 SMESH_Comment cmd("mesh.AddFace([");
4537 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4538 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4543 dumpCmd( "faceId2 = mesh.NbElements()" );
4544 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4545 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4546 << "'%s-%s' % (faceId1+1, faceId2))");
4552 //================================================================================
4554 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4556 //================================================================================
4558 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4560 data._geomSize = Precision::Infinite();
4561 double intersecDist;
4562 const SMDS_MeshElement* face;
4563 SMESH_MesherHelper helper( *_mesh );
4565 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4566 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4567 data._proxyMesh->GetFaces( data._solid )));
4569 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4571 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4572 if ( eos._edges.empty() )
4574 // get neighbor faces, intersection with which should not be considered since
4575 // collisions are avoided by means of smoothing
4576 set< TGeomID > neighborFaces;
4577 if ( eos._hyp.ToSmooth() )
4579 SMESH_subMeshIteratorPtr subIt =
4580 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4581 while ( subIt->more() )
4583 SMESH_subMesh* sm = subIt->next();
4584 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4585 while ( const TopoDS_Shape* face = fIt->next() )
4586 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4589 // find intersections
4590 double thinkness = eos._hyp.GetTotalThickness();
4591 for ( size_t i = 0; i < eos._edges.size(); ++i )
4593 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4594 eos._edges[i]->SetMaxLen( thinkness );
4595 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4596 if ( intersecDist > 0 && face )
4598 data._geomSize = Min( data._geomSize, intersecDist );
4599 if ( !neighborFaces.count( face->getshapeId() ))
4600 eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4605 data._maxThickness = 0;
4606 data._minThickness = 1e100;
4607 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4608 for ( ; hyp != data._hyps.end(); ++hyp )
4610 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4611 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4614 // Limit inflation step size by geometry size found by intersecting
4615 // normals of _LayerEdge's with mesh faces
4616 if ( data._stepSize > 0.3 * data._geomSize )
4617 limitStepSize( data, 0.3 * data._geomSize );
4619 if ( data._stepSize > data._minThickness )
4620 limitStepSize( data, data._minThickness );
4623 // -------------------------------------------------------------------------
4624 // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4625 // so no need in detecting intersection at each inflation step
4626 // -------------------------------------------------------------------------
4628 int nbSteps = data._maxThickness / data._stepSize;
4629 if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4632 vector< const SMDS_MeshElement* > closeFaces;
4635 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4637 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4638 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4641 for ( size_t i = 0; i < eos.size(); ++i )
4643 SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4644 double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4646 searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4648 bool toIgnore = true;
4649 for ( size_t iF = 0; iF < closeFaces.size() && toIgnore; ++iF )
4650 if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4651 data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4653 // check if a _LayerEdge will inflate in a direction opposite to a direction
4654 // toward a close face
4655 bool allBehind = true;
4656 for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes() && allBehind; ++iN )
4658 SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4659 allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4661 toIgnore = allBehind;
4665 if ( toIgnore ) // no need to detect intersection
4667 eos[i]->Set( _LayerEdge::INTERSECTED );
4673 debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4678 //================================================================================
4680 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4682 //================================================================================
4684 bool _ViscousBuilder::inflate(_SolidData& data)
4686 SMESH_MesherHelper helper( *_mesh );
4688 const double tgtThick = data._maxThickness;
4690 if ( data._stepSize < 1. )
4691 data._epsilon = data._stepSize * 1e-7;
4693 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4696 findCollisionEdges( data, helper );
4698 limitMaxLenByCurvature( data, helper );
4702 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4703 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4704 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4705 data._edgesOnShape[i]._edges.size() > 0 &&
4706 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4708 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4709 data._edgesOnShape[i]._edges[0]->Block( data );
4712 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4714 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4715 int nbSteps = 0, nbRepeats = 0;
4716 while ( avgThick < 0.99 )
4718 // new target length
4719 double prevThick = curThick;
4720 curThick += data._stepSize;
4721 if ( curThick > tgtThick )
4723 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4727 double stepSize = curThick - prevThick;
4728 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4730 // Elongate _LayerEdge's
4731 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4732 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4734 _EdgesOnShape& eos = data._edgesOnShape[iS];
4735 if ( eos._edges.empty() ) continue;
4737 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4738 for ( size_t i = 0; i < eos._edges.size(); ++i )
4740 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4745 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4748 // Improve and check quality
4749 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4753 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4754 debugMsg("NOT INVALIDATED STEP!");
4755 return error("Smoothing failed", data._index);
4757 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4758 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4760 _EdgesOnShape& eos = data._edgesOnShape[iS];
4761 for ( size_t i = 0; i < eos._edges.size(); ++i )
4762 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4766 break; // no more inflating possible
4770 // Evaluate achieved thickness
4772 int nbActiveEdges = 0;
4773 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4775 _EdgesOnShape& eos = data._edgesOnShape[iS];
4776 if ( eos._edges.empty() ) continue;
4778 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4779 for ( size_t i = 0; i < eos._edges.size(); ++i )
4781 if ( eos._edges[i]->_nodes.size() > 1 )
4782 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4784 avgThick += shapeTgtThick;
4785 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4788 avgThick /= data._n2eMap.size();
4789 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4791 #ifdef BLOCK_INFLATION
4792 if ( nbActiveEdges == 0 )
4794 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4798 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4800 debugMsg( "-- Stop inflation since "
4801 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4802 << tgtThick * avgThick << " ) * " << safeFactor );
4808 limitStepSize( data, 0.25 * distToIntersection );
4809 if ( data._stepSizeNodes[0] )
4810 data._stepSize = data._stepSizeCoeff *
4811 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4813 } // while ( avgThick < 0.99 )
4816 return error("failed at the very first inflation step", data._index);
4818 if ( avgThick < 0.99 )
4820 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4822 data._proxyMesh->_warning.reset
4823 ( new SMESH_ComputeError (COMPERR_WARNING,
4824 SMESH_Comment("Thickness ") << tgtThick <<
4825 " of viscous layers not reached,"
4826 " average reached thickness is " << avgThick*tgtThick));
4830 // Restore position of src nodes moved by inflation on _noShrinkShapes
4831 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4832 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4834 _EdgesOnShape& eos = data._edgesOnShape[iS];
4835 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4836 for ( size_t i = 0; i < eos._edges.size(); ++i )
4838 restoreNoShrink( *eos._edges[ i ] );
4843 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4846 //================================================================================
4848 * \brief Improve quality of layer inner surface and check intersection
4850 //================================================================================
4852 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4854 double & distToIntersection)
4856 if ( data._nbShapesToSmooth == 0 )
4857 return true; // no shapes needing smoothing
4859 bool moved, improved;
4861 vector< _LayerEdge* > movedEdges, badEdges;
4862 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4863 vector< bool > isConcaveFace;
4865 SMESH_MesherHelper helper(*_mesh);
4866 Handle(ShapeAnalysis_Surface) surface;
4869 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4871 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4873 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4875 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4876 if ( !eos._toSmooth ||
4877 eos.ShapeType() != shapeType ||
4878 eos._edges.empty() )
4881 // already smoothed?
4882 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4883 // if ( !toSmooth ) continue;
4885 if ( !eos._hyp.ToSmooth() )
4887 // smooth disabled by the user; check validy only
4888 if ( !isFace ) continue;
4890 for ( size_t i = 0; i < eos._edges.size(); ++i )
4892 _LayerEdge* edge = eos._edges[i];
4893 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4894 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4896 // debugMsg( "-- Stop inflation. Bad simplex ("
4897 // << " "<< edge->_nodes[0]->GetID()
4898 // << " "<< edge->_nodes.back()->GetID()
4899 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4900 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4902 badEdges.push_back( edge );
4905 if ( !badEdges.empty() )
4909 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4913 continue; // goto the next EDGE or FACE
4917 if ( eos.SWOLType() == TopAbs_FACE )
4919 if ( !F.IsSame( eos._sWOL )) {
4920 F = TopoDS::Face( eos._sWOL );
4921 helper.SetSubShape( F );
4922 surface = helper.GetSurface( F );
4927 F.Nullify(); surface.Nullify();
4929 const TGeomID sInd = eos._shapeID;
4931 // perform smoothing
4933 if ( eos.ShapeType() == TopAbs_EDGE )
4935 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4937 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4939 // smooth on EDGE's (normally we should not get here)
4943 for ( size_t i = 0; i < eos._edges.size(); ++i )
4945 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4947 dumpCmd( SMESH_Comment("# end step ")<<step);
4949 while ( moved && step++ < 5 );
4954 else // smooth on FACE
4957 eosC1.push_back( & eos );
4958 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4961 isConcaveFace.resize( eosC1.size() );
4962 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4964 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4965 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4966 for ( size_t i = 0; i < edges.size(); ++i )
4967 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4968 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4969 movedEdges.push_back( edges[i] );
4971 makeOffsetSurface( *eosC1[ iEOS ], helper );
4974 int step = 0, stepLimit = 5, nbBad = 0;
4975 while (( ++step <= stepLimit ) || improved )
4977 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4978 <<"_InfStep"<<infStep<<"_"<<step); // debug
4979 int oldBadNb = nbBad;
4982 #ifdef INCREMENTAL_SMOOTH
4983 bool findBest = false; // ( step == stepLimit );
4984 for ( size_t i = 0; i < movedEdges.size(); ++i )
4986 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4987 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4988 badEdges.push_back( movedEdges[i] );
4991 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4992 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4994 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4995 for ( size_t i = 0; i < edges.size(); ++i )
4997 edges[i]->Unset( _LayerEdge::SMOOTHED );
4998 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4999 badEdges.push_back( eos._edges[i] );
5003 nbBad = badEdges.size();
5006 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5008 if ( !badEdges.empty() && step >= stepLimit / 2 )
5010 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
5013 // resolve hard smoothing situation around concave VERTEXes
5014 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5016 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5017 for ( size_t i = 0; i < eosCoVe.size(); ++i )
5018 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5021 // look for the best smooth of _LayerEdge's neighboring badEdges
5023 for ( size_t i = 0; i < badEdges.size(); ++i )
5025 _LayerEdge* ledge = badEdges[i];
5026 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5028 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5029 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5031 ledge->Unset( _LayerEdge::SMOOTHED );
5032 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5034 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5037 if ( nbBad == oldBadNb &&
5039 step < stepLimit ) // smooth w/o check of validity
5042 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5043 <<"_InfStep"<<infStep<<"_"<<step); // debug
5044 for ( size_t i = 0; i < movedEdges.size(); ++i )
5046 movedEdges[i]->SmoothWoCheck();
5048 if ( stepLimit < 9 )
5052 improved = ( nbBad < oldBadNb );
5056 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5057 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5059 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5062 } // smoothing steps
5064 // project -- to prevent intersections or fix bad simplices
5065 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5067 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5068 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
5071 //if ( !badEdges.empty() )
5074 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5076 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5078 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5080 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5081 edge->CheckNeiborsOnBoundary( & badEdges );
5082 if (( nbBad > 0 ) ||
5083 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5085 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5086 gp_XYZ prevXYZ = edge->PrevCheckPos();
5087 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5088 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5090 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5091 << " "<< tgtXYZ._node->GetID()
5092 << " "<< edge->_simplices[j]._nPrev->GetID()
5093 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5094 badEdges.push_back( edge );
5101 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5102 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5108 } // // smooth on FACE's
5110 } // smooth on [ EDGEs, FACEs ]
5112 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5114 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5116 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5117 if ( eos.ShapeType() == TopAbs_FACE ||
5118 eos._edges.empty() ||
5119 !eos._sWOL.IsNull() )
5123 for ( size_t i = 0; i < eos._edges.size(); ++i )
5125 _LayerEdge* edge = eos._edges[i];
5126 if ( edge->_nodes.size() < 2 ) continue;
5127 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5128 //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5129 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
5130 //const gp_XYZ& prevXYZ = edge->PrevPos();
5131 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5132 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5134 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5135 << " "<< tgtXYZ._node->GetID()
5136 << " "<< edge->_simplices[j]._nPrev->GetID()
5137 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5138 badEdges.push_back( edge );
5143 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5145 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5151 // Check if the last segments of _LayerEdge intersects 2D elements;
5152 // checked elements are either temporary faces or faces on surfaces w/o the layers
5154 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5155 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5156 data._proxyMesh->GetFaces( data._solid )) );
5158 #ifdef BLOCK_INFLATION
5159 const bool toBlockInfaltion = true;
5161 const bool toBlockInfaltion = false;
5163 distToIntersection = Precision::Infinite();
5165 const SMDS_MeshElement* intFace = 0;
5166 const SMDS_MeshElement* closestFace = 0;
5168 bool is1stBlocked = true; // dbg
5169 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5171 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5172 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5174 for ( size_t i = 0; i < eos._edges.size(); ++i )
5176 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5177 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5179 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5182 // commented due to "Illegal hash-positionPosition" error in NETGEN
5183 // on Debian60 on viscous_layers_01/B2 case
5184 // Collision; try to deflate _LayerEdge's causing it
5185 // badEdges.clear();
5186 // badEdges.push_back( eos._edges[i] );
5187 // eosC1[0] = & eos;
5188 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5192 // badEdges.clear();
5193 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5195 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5197 // const SMDS_MeshElement* srcFace =
5198 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5199 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5200 // while ( nIt->more() )
5202 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5203 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5204 // if ( n2e != data._n2eMap.end() )
5205 // badEdges.push_back( n2e->second );
5208 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5213 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5220 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5225 const bool isShorterDist = ( distToIntersection > dist );
5226 if ( toBlockInfaltion || isShorterDist )
5228 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5229 // lying on this _ConvexFace
5230 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5231 if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5234 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5235 // ( avoid limiting the thickness on the case of issue 22576)
5236 if ( intFace->getshapeId() == eos._shapeID )
5239 // ignore intersection with intFace of an adjacent FACE
5240 if ( dist > 0.1 * eos._edges[i]->_len )
5242 bool toIgnore = false;
5243 if ( eos._toSmooth )
5245 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5246 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5248 TopExp_Explorer sub( eos._shape,
5249 eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5250 for ( ; !toIgnore && sub.More(); sub.Next() )
5251 // is adjacent - has a common EDGE or VERTEX
5252 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5254 if ( toIgnore ) // check angle between normals
5257 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5258 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
5262 if ( !toIgnore ) // check if the edge is a neighbor of intFace
5264 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
5266 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5267 toIgnore = ( nInd >= 0 );
5274 // intersection not ignored
5276 if ( toBlockInfaltion &&
5277 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5279 if ( is1stBlocked ) { is1stBlocked = false; // debug
5280 dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5282 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5283 eos._edges[i]->Block( data ); // not to inflate
5285 //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5287 // block _LayerEdge's, on top of which intFace is
5288 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5290 const SMDS_MeshElement* srcFace = f->_srcFace;
5291 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5292 while ( nIt->more() )
5294 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5295 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5296 if ( n2e != data._n2eMap.end() )
5297 n2e->second->Block( data );
5303 if ( isShorterDist )
5305 distToIntersection = dist;
5307 closestFace = intFace;
5310 } // if ( toBlockInfaltion || isShorterDist )
5311 } // loop on eos._edges
5312 } // loop on data._edgesOnShape
5314 if ( !is1stBlocked )
5317 if ( closestFace && le )
5320 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5321 cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5322 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5323 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5324 << ") distance = " << distToIntersection<< endl;
5331 //================================================================================
5333 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5334 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5335 * \return int - resulting nb of bad _LayerEdge's
5337 //================================================================================
5339 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5340 SMESH_MesherHelper& helper,
5341 vector< _LayerEdge* >& badSmooEdges,
5342 vector< _EdgesOnShape* >& eosC1,
5345 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5347 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5350 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5351 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5352 ADDED = _LayerEdge::UNUSED_FLAG * 4
5354 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5357 bool haveInvalidated = true;
5358 while ( haveInvalidated )
5360 haveInvalidated = false;
5361 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5363 _LayerEdge* edge = badSmooEdges[i];
5364 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5366 bool invalidated = false;
5367 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5369 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5370 edge->Block( data );
5371 edge->Set( INVALIDATED );
5372 edge->Unset( TO_INVALIDATE );
5374 haveInvalidated = true;
5377 // look for _LayerEdge's of bad _simplices
5379 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5380 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5381 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5382 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5384 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5385 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5389 _LayerEdge* ee[2] = { 0,0 };
5390 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5391 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5392 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5394 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5395 while ( maxNbSteps > edge->NbSteps() && isBad )
5398 for ( int iE = 0; iE < 2; ++iE )
5400 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5401 ee[ iE ]->NbSteps() > 1 )
5403 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5404 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5405 ee[ iE ]->Block( data );
5406 ee[ iE ]->Set( INVALIDATED );
5407 haveInvalidated = true;
5410 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5411 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5415 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5416 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5417 ee[0]->Set( ADDED );
5418 ee[1]->Set( ADDED );
5421 ee[0]->Set( TO_INVALIDATE );
5422 ee[1]->Set( TO_INVALIDATE );
5426 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5428 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5429 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5430 edge->Block( data );
5431 edge->Set( INVALIDATED );
5432 edge->Unset( TO_INVALIDATE );
5433 haveInvalidated = true;
5435 } // loop on badSmooEdges
5436 } // while ( haveInvalidated )
5438 // re-smooth on analytical EDGEs
5439 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5441 _LayerEdge* edge = badSmooEdges[i];
5442 if ( !edge->Is( INVALIDATED )) continue;
5444 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5445 if ( eos->ShapeType() == TopAbs_VERTEX )
5447 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5448 while ( const TopoDS_Shape* e = eIt->next() )
5449 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5450 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5452 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5453 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5454 // F = TopoDS::Face( eoe->_sWOL );
5455 // surface = helper.GetSurface( F );
5457 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5458 eoe->_edgeSmoother->_anaCurve.Nullify();
5464 // check result of invalidation
5467 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5469 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5471 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5472 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5473 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5474 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5475 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5476 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5479 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5480 << " "<< tgtXYZ._node->GetID()
5481 << " "<< edge->_simplices[j]._nPrev->GetID()
5482 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5491 //================================================================================
5493 * \brief Create an offset surface
5495 //================================================================================
5497 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5499 if ( eos._offsetSurf.IsNull() ||
5500 eos._edgeForOffset == 0 ||
5501 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5504 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5507 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5508 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5509 double offset = baseSurface->Gap();
5511 eos._offsetSurf.Nullify();
5515 BRepOffsetAPI_MakeOffsetShape offsetMaker;
5516 offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5517 if ( !offsetMaker.IsDone() ) return;
5519 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5520 if ( !fExp.More() ) return;
5522 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5523 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5524 if ( surf.IsNull() ) return;
5526 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5528 catch ( Standard_Failure )
5533 //================================================================================
5535 * \brief Put nodes of a curved FACE to its offset surface
5537 //================================================================================
5539 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5541 vector< _EdgesOnShape* >& eosC1,
5545 _EdgesOnShape * eof = & eos;
5546 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5549 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5551 if ( eosC1[i]->_offsetSurf.IsNull() ||
5552 eosC1[i]->ShapeType() != TopAbs_FACE ||
5553 eosC1[i]->_edgeForOffset == 0 ||
5554 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5556 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5561 eof->_offsetSurf.IsNull() ||
5562 eof->ShapeType() != TopAbs_FACE ||
5563 eof->_edgeForOffset == 0 ||
5564 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5567 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5568 for ( size_t i = 0; i < eos._edges.size(); ++i )
5570 _LayerEdge* edge = eos._edges[i];
5571 edge->Unset( _LayerEdge::MARKED );
5572 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5574 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5576 if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5579 else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5582 int nbBlockedAround = 0;
5583 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5584 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5585 if ( nbBlockedAround > 1 )
5588 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5589 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5590 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5591 edge->_curvature->_uv = uv;
5592 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5594 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5595 gp_XYZ prevP = edge->PrevCheckPos();
5598 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5600 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5604 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5605 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5606 edge->_pos.back() = newP;
5608 edge->Set( _LayerEdge::MARKED );
5609 if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5611 edge->_normal = ( newP - prevP ).Normalized();
5619 // dumpMove() for debug
5621 for ( ; i < eos._edges.size(); ++i )
5622 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5624 if ( i < eos._edges.size() )
5626 dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5627 << "_InfStep" << infStep << "_" << smooStep );
5628 for ( ; i < eos._edges.size(); ++i )
5630 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5631 dumpMove( eos._edges[i]->_nodes.back() );
5637 _ConvexFace* cnvFace;
5638 if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5639 eos.ShapeType() == TopAbs_FACE &&
5640 (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5641 !cnvFace->_normalsFixedOnBorders )
5643 // put on the surface nodes built on FACE boundaries
5644 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5645 while ( smIt->more() )
5647 SMESH_subMesh* sm = smIt->next();
5648 _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5649 if ( !subEOS->_sWOL.IsNull() ) continue;
5650 if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5652 putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5654 cnvFace->_normalsFixedOnBorders = true;
5658 //================================================================================
5660 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5661 * _LayerEdge's to be in a consequent order
5663 //================================================================================
5665 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5667 SMESH_MesherHelper& helper)
5669 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5671 TopLoc_Location loc; double f,l;
5673 Handle(Geom_Line) line;
5674 Handle(Geom_Circle) circle;
5675 bool isLine, isCirc;
5676 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5678 // check if the EDGE is a line
5679 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5680 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5681 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5683 line = Handle(Geom_Line)::DownCast( curve );
5684 circle = Handle(Geom_Circle)::DownCast( curve );
5685 isLine = (!line.IsNull());
5686 isCirc = (!circle.IsNull());
5688 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5690 isLine = SMESH_Algo::IsStraight( E );
5693 line = new Geom_Line( gp::OX() ); // only type does matter
5695 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5700 else //////////////////////////////////////////////////////////////////////// 2D case
5702 if ( !eos._isRegularSWOL ) // 23190
5705 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5707 // check if the EDGE is a line
5708 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5709 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5710 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5712 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5713 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5714 isLine = (!line2d.IsNull());
5715 isCirc = (!circle2d.IsNull());
5717 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5720 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5721 while ( nIt->more() )
5722 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5723 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5725 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5726 for ( int i = 0; i < 2 && !isLine; ++i )
5727 isLine = ( size.Coord( i+1 ) <= lineTol );
5729 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5735 line = new Geom_Line( gp::OX() ); // only type does matter
5739 gp_Pnt2d p = circle2d->Location();
5740 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5741 circle = new Geom_Circle( ax, 1.); // only center position does matter
5750 return Handle(Geom_Curve)();
5753 //================================================================================
5755 * \brief Smooth edges on EDGE
5757 //================================================================================
5759 bool _Smoother1D::Perform(_SolidData& data,
5760 Handle(ShapeAnalysis_Surface)& surface,
5761 const TopoDS_Face& F,
5762 SMESH_MesherHelper& helper )
5764 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5767 findEdgesToSmooth();
5769 return smoothAnalyticEdge( data, surface, F, helper );
5771 return smoothComplexEdge ( data, surface, F, helper );
5774 //================================================================================
5776 * \brief Find edges to smooth
5778 //================================================================================
5780 void _Smoother1D::findEdgesToSmooth()
5782 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5783 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5784 if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5785 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5787 _eToSmooth[0].first = _eToSmooth[0].second = 0;
5789 for ( size_t i = 0; i < _eos.size(); ++i )
5791 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5793 if ( needSmoothing( _leOnV[0]._cosin,
5794 _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5797 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5801 _eToSmooth[0].second = i+1;
5804 _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5806 for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5808 if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5810 if ( needSmoothing( _leOnV[1]._cosin,
5811 _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5813 _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5817 _eToSmooth[1].first = i;
5821 //================================================================================
5823 * \brief Check if iE-th _LayerEdge needs smoothing
5825 //================================================================================
5827 bool _Smoother1D::isToSmooth( int iE )
5829 SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5830 SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5831 SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5832 gp_XYZ seg0 = pi - p0;
5833 gp_XYZ seg1 = p1 - pi;
5834 gp_XYZ tangent = seg0 + seg1;
5835 double tangentLen = tangent.Modulus();
5836 double segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5837 if ( tangentLen < std::numeric_limits<double>::min() )
5839 tangent /= tangentLen;
5841 for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5843 _LayerEdge* ne = _eos[iE]->_neibors[i];
5844 if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5845 ne->_nodes.size() < 2 ||
5846 ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5848 gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5849 double proj = edgeVec * tangent;
5850 if ( needSmoothing( 1., proj, segMinLen ))
5856 //================================================================================
5858 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5860 //================================================================================
5862 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5863 Handle(ShapeAnalysis_Surface)& surface,
5864 const TopoDS_Face& F,
5865 SMESH_MesherHelper& helper)
5867 if ( !isAnalytic() ) return false;
5869 size_t iFrom = 0, iTo = _eos._edges.size();
5871 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5873 if ( F.IsNull() ) // 3D
5875 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5876 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5877 //const gp_XYZ lineDir = pSrc1 - pSrc0;
5878 //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5879 //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5880 // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5881 // vLE0->Is( _LayerEdge::BLOCKED ) ||
5882 // vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5883 // vLE1->Is( _LayerEdge::BLOCKED ));
5884 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5886 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5887 if ( iFrom >= iTo ) continue;
5888 SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5889 SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5890 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5891 double param1 = _leParams[ iTo ];
5892 for ( size_t i = iFrom; i < iTo; ++i )
5894 _LayerEdge* edge = _eos[i];
5895 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5896 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5897 gp_XYZ newPos = p0 * ( 1. - param ) + p1 * param;
5899 // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5901 // gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5902 // double shift = ( lineDir * ( newPos - pSrc0 ) -
5903 // lineDir * ( curPos - pSrc0 ));
5904 // newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5906 if ( edge->Is( _LayerEdge::BLOCKED ))
5908 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5909 double curThick = pSrc.SquareDistance( tgtNode );
5910 double newThink = ( pSrc - newPos ).SquareModulus();
5911 if ( newThink > curThick )
5914 edge->_pos.back() = newPos;
5915 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5916 dumpMove( tgtNode );
5922 _LayerEdge* eV0 = getLEdgeOnV( 0 );
5923 _LayerEdge* eV1 = getLEdgeOnV( 1 );
5924 gp_XY uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5925 gp_XY uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5926 if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5928 int iPeriodic = helper.GetPeriodicIndex();
5929 if ( iPeriodic == 1 || iPeriodic == 2 )
5931 uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5932 if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5933 std::swap( uvV0, uvV1 );
5936 for ( int iEnd = 0; iEnd < 2; ++iEnd )
5938 iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5939 if ( iFrom >= iTo ) continue;
5940 _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5941 _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5942 gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5943 gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5944 double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5945 double param1 = _leParams[ iTo ];
5946 gp_XY rangeUV = uv1 - uv0;
5947 for ( size_t i = iFrom; i < iTo; ++i )
5949 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5950 double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5951 gp_XY newUV = uv0 + param * rangeUV;
5953 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5954 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5955 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5956 dumpMove( tgtNode );
5958 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5959 pos->SetUParameter( newUV.X() );
5960 pos->SetVParameter( newUV.Y() );
5962 gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5964 if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5966 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5967 if ( _eos[i]->_pos.size() > 2 )
5969 // modify previous positions to make _LayerEdge less sharply bent
5970 vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5971 const gp_XYZ uvShift = newUV0 - uvVec.back();
5972 const double len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5973 int iPrev = uvVec.size() - 2;
5976 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5977 uvVec[ iPrev ] += uvShift * r;
5982 _eos[i]->_pos.back() = newUV0;
5989 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5991 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5992 gp_Pnt center3D = circle->Location();
5994 if ( F.IsNull() ) // 3D
5996 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5997 return true; // closed EDGE - nothing to do
5999 // circle is a real curve of EDGE
6000 gp_Circ circ = circle->Circ();
6002 // new center is shifted along its axis
6003 const gp_Dir& axis = circ.Axis().Direction();
6004 _LayerEdge* e0 = getLEdgeOnV(0);
6005 _LayerEdge* e1 = getLEdgeOnV(1);
6006 SMESH_TNodeXYZ p0 = e0->_nodes.back();
6007 SMESH_TNodeXYZ p1 = e1->_nodes.back();
6008 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
6009 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
6010 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
6012 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
6014 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6015 gp_Circ newCirc( newAxis, newRadius );
6016 gp_Vec vecC1 ( newCenter, p1 );
6018 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6022 for ( size_t i = 0; i < _eos.size(); ++i )
6024 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6025 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6026 double u = uLast * _leParams[i];
6027 gp_Pnt p = ElCLib::Value( u, newCirc );
6028 _eos._edges[i]->_pos.back() = p.XYZ();
6030 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6031 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6032 dumpMove( tgtNode );
6038 const gp_XY center( center3D.X(), center3D.Y() );
6040 _LayerEdge* e0 = getLEdgeOnV(0);
6041 _LayerEdge* eM = _eos._edges[ 0 ];
6042 _LayerEdge* e1 = getLEdgeOnV(1);
6043 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6044 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6045 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6046 gp_Vec2d vec0( center, uv0 );
6047 gp_Vec2d vecM( center, uvM );
6048 gp_Vec2d vec1( center, uv1 );
6049 double uLast = vec0.Angle( vec1 ); // -PI - +PI
6050 double uMidl = vec0.Angle( vecM );
6051 if ( uLast * uMidl <= 0. )
6052 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6053 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6055 gp_Ax2d axis( center, vec0 );
6056 gp_Circ2d circ( axis, radius );
6057 for ( size_t i = 0; i < _eos.size(); ++i )
6059 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6060 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6061 double newU = uLast * _leParams[i];
6062 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6063 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6065 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6066 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6067 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6068 dumpMove( tgtNode );
6070 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
6071 pos->SetUParameter( newUV.X() );
6072 pos->SetVParameter( newUV.Y() );
6074 _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6083 //================================================================================
6085 * \brief smooth _LayerEdge's on a an EDGE
6087 //================================================================================
6089 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
6090 Handle(ShapeAnalysis_Surface)& surface,
6091 const TopoDS_Face& F,
6092 SMESH_MesherHelper& helper)
6094 if ( _offPoints.empty() )
6097 // ----------------------------------------------
6098 // move _offPoints along normals of _LayerEdge's
6099 // ----------------------------------------------
6101 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6102 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6103 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6104 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
6105 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6106 _leOnV[0]._len = e[0]->_len;
6107 _leOnV[1]._len = e[1]->_len;
6108 for ( size_t i = 0; i < _offPoints.size(); i++ )
6110 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6111 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6112 const double w0 = _offPoints[i]._2edges._wgt[0];
6113 const double w1 = _offPoints[i]._2edges._wgt[1];
6114 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
6115 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6116 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6117 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6118 e1->Is( _LayerEdge::NORMAL_UPDATED ))
6119 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6121 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6122 _offPoints[i]._len = avgLen;
6126 if ( !surface.IsNull() ) // project _offPoints to the FACE
6128 fTol = 100 * BRep_Tool::Tolerance( F );
6129 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6131 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6132 //if ( surface->Gap() < 0.5 * segLen )
6133 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6135 for ( size_t i = 1; i < _offPoints.size(); ++i )
6137 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6138 //if ( surface->Gap() < 0.5 * segLen )
6139 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6143 // -----------------------------------------------------------------
6144 // project tgt nodes of extreme _LayerEdge's to the offset segments
6145 // -----------------------------------------------------------------
6147 const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6148 if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6149 if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6151 gp_Pnt pExtreme[2], pProj[2];
6152 bool isProjected[2];
6153 for ( int is2nd = 0; is2nd < 2; ++is2nd )
6155 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6156 int i = _iSeg[ is2nd ];
6157 int di = is2nd ? -1 : +1;
6158 bool & projected = isProjected[ is2nd ];
6160 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6163 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
6164 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6165 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
6166 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6167 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6168 if ( dist < distMin || projected )
6171 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6174 else if ( dist > distPrev )
6176 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6182 while ( !projected &&
6183 i >= 0 && i+1 < (int)_offPoints.size() );
6187 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6190 _iSeg[1] = _offPoints.size()-2;
6191 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6196 if ( _iSeg[0] > _iSeg[1] )
6198 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6202 // adjust length of extreme LE (test viscous_layers_01/B7)
6203 gp_Vec vDiv0( pExtreme[0], pProj[0] );
6204 gp_Vec vDiv1( pExtreme[1], pProj[1] );
6205 double d0 = vDiv0.Magnitude();
6206 double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6207 if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6208 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6209 else e[0]->_len -= d0;
6211 if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6212 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6213 else e[1]->_len -= d1;
6216 // ---------------------------------------------------------------------------------
6217 // compute normalized length of the offset segments located between the projections
6218 // ---------------------------------------------------------------------------------
6220 // temporary replace extreme _offPoints by pExtreme
6221 gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0] ]._xyz,
6222 _offPoints[ _iSeg[1]+1 ]._xyz };
6223 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
6224 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6226 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6227 vector< double > len( nbSeg + 1 );
6229 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6230 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6232 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6234 // if ( isProjected[ 1 ])
6235 // len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6237 // len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6239 double fullLen = len.back() - d0 - d1;
6240 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6241 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6243 // -------------------------------------------------------------
6244 // distribute tgt nodes of _LayerEdge's between the projections
6245 // -------------------------------------------------------------
6248 for ( size_t i = 0; i < _eos.size(); ++i )
6250 if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6251 //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6252 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6254 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6255 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
6256 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6258 if ( surface.IsNull() )
6260 _eos[i]->_pos.back() = p;
6262 else // project a new node position to a FACE
6264 gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6265 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6267 p = surface->Value( uv2 ).XYZ();
6268 _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6270 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6271 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6272 dumpMove( tgtNode );
6275 _offPoints[ _iSeg[0] ]._xyz = opXYZ[0];
6276 _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6281 //================================================================================
6283 * \brief Prepare for smoothing
6285 //================================================================================
6287 void _Smoother1D::prepare(_SolidData& data)
6289 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6290 _curveLen = SMESH_Algo::EdgeLength( E );
6292 // sort _LayerEdge's by position on the EDGE
6293 data.SortOnEdge( E, _eos._edges );
6295 // compute normalized param of _eos._edges on EDGE
6296 _leParams.resize( _eos._edges.size() + 1 );
6299 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6301 for ( size_t i = 0; i < _eos._edges.size(); ++i )
6303 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6304 curLen = p.Distance( pPrev );
6305 _leParams[i+1] = _leParams[i] + curLen;
6308 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6309 for ( size_t i = 0; i < _leParams.size()-1; ++i )
6310 _leParams[i] = _leParams[i+1] / fullLen;
6311 _leParams.back() = 1.;
6314 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6316 // get cosin to use in findEdgesToSmooth()
6317 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6318 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6319 _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6320 _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6321 if ( _eos._sWOL.IsNull() ) // 3D
6322 for ( int iEnd = 0; iEnd < 2; ++iEnd )
6323 _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6328 // divide E to have offset segments with low deflection
6329 BRepAdaptor_Curve c3dAdaptor( E );
6330 const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6331 const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6332 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6333 if ( discret.NbPoints() <= 2 )
6335 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6339 const double u0 = c3dAdaptor.FirstParameter();
6340 gp_Pnt p; gp_Vec tangent;
6341 if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6343 _offPoints.resize( discret.NbPoints() );
6344 for ( size_t i = 0; i < _offPoints.size(); i++ )
6346 double u = discret.Parameter( i+1 );
6347 c3dAdaptor.D1( u, p, tangent );
6348 _offPoints[i]._xyz = p.XYZ();
6349 _offPoints[i]._edgeDir = tangent.XYZ();
6350 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6355 std::vector< double > params( _eos.size() + 2 );
6357 params[0] = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6358 params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6359 for ( size_t i = 0; i < _eos.size(); i++ )
6360 params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6362 if ( params[1] > params[ _eos.size() ] )
6363 std::reverse( params.begin() + 1, params.end() - 1 );
6365 _offPoints.resize( _eos.size() + 2 );
6366 for ( size_t i = 0; i < _offPoints.size(); i++ )
6368 const double u = params[i];
6369 c3dAdaptor.D1( u, p, tangent );
6370 _offPoints[i]._xyz = p.XYZ();
6371 _offPoints[i]._edgeDir = tangent.XYZ();
6372 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6377 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6378 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6379 _2NearEdges tmp2edges;
6380 tmp2edges._edges[1] = _eos._edges[0];
6381 _leOnV[0]._2neibors = & tmp2edges;
6382 _leOnV[0]._nodes = leOnV[0]->_nodes;
6383 _leOnV[1]._nodes = leOnV[1]->_nodes;
6384 _LayerEdge* eNext, *ePrev = & _leOnV[0];
6385 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6387 // find _LayerEdge's located before and after an offset point
6388 // (_eos._edges[ iLE ] is next after ePrev)
6389 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6390 ePrev = _eos._edges[ iLE++ ];
6391 eNext = ePrev->_2neibors->_edges[1];
6393 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6394 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6395 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6396 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6399 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6400 for ( size_t i = 0; i < _offPoints.size(); i++ )
6401 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6402 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6404 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6405 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6406 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6409 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6411 int iLBO = _offPoints.size() - 2; // last but one
6413 if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6414 _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6416 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6417 if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6418 _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6420 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6421 _leOnV[ 0 ]._len = 0;
6422 _leOnV[ 1 ]._len = 0;
6423 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
6424 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6427 _iSeg[1] = _offPoints.size()-2;
6429 // initialize OffPnt::_len
6430 for ( size_t i = 0; i < _offPoints.size(); ++i )
6431 _offPoints[i]._len = 0;
6433 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6435 _leOnV[0]._len = leOnV[0]->_len;
6436 _leOnV[1]._len = leOnV[1]->_len;
6437 for ( size_t i = 0; i < _offPoints.size(); i++ )
6439 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
6440 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
6441 const double w0 = _offPoints[i]._2edges._wgt[0];
6442 const double w1 = _offPoints[i]._2edges._wgt[1];
6443 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
6444 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6445 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6446 _offPoints[i]._xyz = avgXYZ;
6447 _offPoints[i]._len = avgLen;
6452 //================================================================================
6454 * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6456 //================================================================================
6458 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6459 const gp_XYZ& edgeDir)
6461 gp_XYZ cross = normal ^ edgeDir;
6462 gp_XYZ norm = edgeDir ^ cross;
6463 double size = norm.Modulus();
6465 // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6466 // return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6471 //================================================================================
6473 * \brief Writes a script creating a mesh composed of _offPoints
6475 //================================================================================
6477 void _Smoother1D::offPointsToPython() const
6479 const char* fname = "/tmp/offPoints.py";
6480 cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6482 py << "import SMESH" << endl
6483 << "from salome.smesh import smeshBuilder" << endl
6484 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
6485 << "mesh = smesh.Mesh( 'offPoints' )"<<endl;
6486 for ( size_t i = 0; i < _offPoints.size(); i++ )
6488 py << "mesh.AddNode( "
6489 << _offPoints[i]._xyz.X() << ", "
6490 << _offPoints[i]._xyz.Y() << ", "
6491 << _offPoints[i]._xyz.Z() << " )" << endl;
6495 //================================================================================
6497 * \brief Sort _LayerEdge's by a parameter on a given EDGE
6499 //================================================================================
6501 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
6502 vector< _LayerEdge* >& edges)
6504 map< double, _LayerEdge* > u2edge;
6505 for ( size_t i = 0; i < edges.size(); ++i )
6506 u2edge.insert( u2edge.end(),
6507 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6509 ASSERT( u2edge.size() == edges.size() );
6510 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6511 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6512 edges[i] = u2e->second;
6514 Sort2NeiborsOnEdge( edges );
6517 //================================================================================
6519 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6521 //================================================================================
6523 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6525 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6527 for ( size_t i = 0; i < edges.size()-1; ++i )
6528 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6529 edges[i]->_2neibors->reverse();
6531 const size_t iLast = edges.size() - 1;
6532 if ( edges.size() > 1 &&
6533 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6534 edges[iLast]->_2neibors->reverse();
6537 //================================================================================
6539 * \brief Return _EdgesOnShape* corresponding to the shape
6541 //================================================================================
6543 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6545 if ( shapeID < (int)_edgesOnShape.size() &&
6546 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6547 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6549 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6550 if ( _edgesOnShape[i]._shapeID == shapeID )
6551 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6556 //================================================================================
6558 * \brief Return _EdgesOnShape* corresponding to the shape
6560 //================================================================================
6562 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6564 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6565 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6568 //================================================================================
6570 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6572 //================================================================================
6574 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6576 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6578 set< TGeomID > vertices;
6580 if ( eos->ShapeType() == TopAbs_FACE )
6582 // check FACE concavity and get concave VERTEXes
6583 F = TopoDS::Face( eos->_shape );
6584 if ( isConcave( F, helper, &vertices ))
6585 _concaveFaces.insert( eos->_shapeID );
6587 // set eos._eosConcaVer
6588 eos->_eosConcaVer.clear();
6589 eos->_eosConcaVer.reserve( vertices.size() );
6590 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6592 _EdgesOnShape* eov = GetShapeEdges( *v );
6593 if ( eov && eov->_edges.size() == 1 )
6595 eos->_eosConcaVer.push_back( eov );
6596 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6597 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6601 // SetSmooLen() to _LayerEdge's on FACE
6602 // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6604 // eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6606 // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6607 // while ( smIt->more() ) // loop on sub-shapes of the FACE
6609 // _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6610 // if ( !eoe ) continue;
6612 // vector<_LayerEdge*>& eE = eoe->_edges;
6613 // for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6615 // if ( eE[iE]->_cosin <= theMinSmoothCosin )
6618 // SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6619 // while ( segIt->more() )
6621 // const SMDS_MeshElement* seg = segIt->next();
6622 // if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6624 // if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6625 // continue; // not to check a seg twice
6626 // for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6628 // _LayerEdge* eN = eE[iE]->_neibors[iN];
6629 // if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6631 // double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6632 // double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6633 // eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6634 // eN->Set( _LayerEdge::NEAR_BOUNDARY );
6639 } // if ( eos->ShapeType() == TopAbs_FACE )
6641 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6643 eos->_edges[i]->_smooFunction = 0;
6644 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6646 bool isCurved = false;
6647 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6649 _LayerEdge* edge = eos->_edges[i];
6651 // get simplices sorted
6652 _Simplex::SortSimplices( edge->_simplices );
6654 // smoothing function
6655 edge->ChooseSmooFunction( vertices, _n2eMap );
6658 double avgNormProj = 0, avgLen = 0;
6659 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6661 _Simplex& s = edge->_simplices[iS];
6663 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6664 avgNormProj += edge->_normal * vec;
6665 avgLen += vec.Modulus();
6666 if ( substituteSrcNodes )
6668 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6669 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6672 avgNormProj /= edge->_simplices.size();
6673 avgLen /= edge->_simplices.size();
6674 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6676 edge->Set( _LayerEdge::SMOOTHED_C1 );
6678 SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6680 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6681 fPos = edge->_simplices[iS]._nPrev->GetPosition();
6683 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6687 // prepare for putOnOffsetSurface()
6688 if (( eos->ShapeType() == TopAbs_FACE ) &&
6689 ( isCurved || !eos->_eosConcaVer.empty() ))
6691 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6692 eos->_edgeForOffset = 0;
6694 double maxCosin = -1;
6695 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6697 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6698 if ( !eoe || eoe->_edges.empty() ) continue;
6700 vector<_LayerEdge*>& eE = eoe->_edges;
6701 _LayerEdge* e = eE[ eE.size() / 2 ];
6702 if ( e->_cosin > maxCosin )
6704 eos->_edgeForOffset = e;
6705 maxCosin = e->_cosin;
6711 //================================================================================
6713 * \brief Add faces for smoothing
6715 //================================================================================
6717 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6718 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6720 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6721 for ( ; eos != eosToSmooth.end(); ++eos )
6723 if ( !*eos || (*eos)->_toSmooth ) continue;
6725 (*eos)->_toSmooth = true;
6727 if ( (*eos)->ShapeType() == TopAbs_FACE )
6729 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6730 (*eos)->_toSmooth = true;
6734 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6735 if ( edgesNoAnaSmooth )
6736 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6738 if ( (*eos)->_edgeSmoother )
6739 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6743 //================================================================================
6745 * \brief Limit _LayerEdge::_maxLen according to local curvature
6747 //================================================================================
6749 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6751 // find intersection of neighbor _LayerEdge's to limit _maxLen
6752 // according to local curvature (IPAL52648)
6754 // This method must be called after findCollisionEdges() where _LayerEdge's
6755 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6757 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6759 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6760 if ( eosI._edges.empty() ) continue;
6761 if ( !eosI._hyp.ToSmooth() )
6763 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6765 _LayerEdge* eI = eosI._edges[i];
6766 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6768 _LayerEdge* eN = eI->_neibors[iN];
6769 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6771 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6772 limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6777 else if ( eosI.ShapeType() == TopAbs_EDGE )
6779 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6780 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6782 _LayerEdge* e0 = eosI._edges[0];
6783 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6785 _LayerEdge* eI = eosI._edges[i];
6786 limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6793 //================================================================================
6795 * \brief Limit _LayerEdge::_maxLen according to local curvature
6797 //================================================================================
6799 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6801 _EdgesOnShape& eos1,
6802 _EdgesOnShape& eos2,
6803 const bool isSmoothable )
6805 if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6806 e2->_nodes[0]->GetPosition()->GetDim() ) &&
6807 ( e1->_cosin < 0.75 ))
6808 return; // angle > 90 deg at e1
6810 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6811 double norSize = plnNorm.SquareModulus();
6812 if ( norSize < std::numeric_limits<double>::min() )
6813 return; // parallel normals
6815 // find closest points of skew _LayerEdge's
6816 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6817 gp_XYZ dir12 = src2 - src1;
6818 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6819 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6820 double dot1 = perp2 * e1->_normal;
6821 double dot2 = perp1 * e2->_normal;
6822 double u1 = ( perp2 * dir12 ) / dot1;
6823 double u2 = - ( perp1 * dir12 ) / dot2;
6824 if ( u1 > 0 && u2 > 0 )
6826 double ovl = ( u1 * e1->_normal * dir12 -
6827 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6828 if ( ovl > theSmoothThickToElemSizeRatio )
6830 const double coef = 0.75;
6831 e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6832 e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6837 //================================================================================
6839 * \brief Fill data._collisionEdges
6841 //================================================================================
6843 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6845 data._collisionEdges.clear();
6847 // set the full thickness of the layers to LEs
6848 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6850 _EdgesOnShape& eos = data._edgesOnShape[iS];
6851 if ( eos._edges.empty() ) continue;
6852 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6853 if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6855 for ( size_t i = 0; i < eos._edges.size(); ++i )
6857 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6858 double maxLen = eos._edges[i]->_maxLen;
6859 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6860 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6861 eos._edges[i]->_maxLen = maxLen;
6865 // make temporary quadrangles got by extrusion of
6866 // mesh edges along _LayerEdge._normal's
6868 vector< const SMDS_MeshElement* > tmpFaces;
6870 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6872 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6873 if ( eos.ShapeType() != TopAbs_EDGE )
6875 if ( eos._edges.empty() )
6877 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6878 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6879 while ( smIt->more() )
6880 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6881 if ( eov->_edges.size() == 1 )
6882 edge[ bool( edge[0]) ] = eov->_edges[0];
6886 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6887 tmpFaces.push_back( f );
6890 for ( size_t i = 0; i < eos._edges.size(); ++i )
6892 _LayerEdge* edge = eos._edges[i];
6893 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6895 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6896 if ( src2->GetPosition()->GetDim() > 0 &&
6897 src2->GetID() < edge->_nodes[0]->GetID() )
6898 continue; // avoid using same segment twice
6900 // a _LayerEdge containing tgt2
6901 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6903 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6904 tmpFaces.push_back( f );
6909 // Find _LayerEdge's intersecting tmpFaces.
6911 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6913 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6914 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6916 double dist1, dist2, segLen, eps = 0.5;
6917 _CollisionEdges collEdges;
6918 vector< const SMDS_MeshElement* > suspectFaces;
6919 const double angle45 = Cos( 45. * M_PI / 180. );
6921 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6923 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6924 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6926 // find sub-shapes whose VL can influence VL on eos
6927 set< TGeomID > neighborShapes;
6928 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6929 while ( const TopoDS_Shape* face = fIt->next() )
6931 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6932 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6934 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6935 while ( subIt->more() )
6936 neighborShapes.insert( subIt->next()->GetId() );
6939 if ( eos.ShapeType() == TopAbs_VERTEX )
6941 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6942 while ( const TopoDS_Shape* edge = eIt->next() )
6943 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6945 // find intersecting _LayerEdge's
6946 for ( size_t i = 0; i < eos._edges.size(); ++i )
6948 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6949 _LayerEdge* edge = eos._edges[i];
6950 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6953 gp_Vec eSegDir0, eSegDir1;
6954 if ( edge->IsOnEdge() )
6956 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6957 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6958 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6960 suspectFaces.clear();
6961 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6962 SMDSAbs_Face, suspectFaces );
6963 collEdges._intEdges.clear();
6964 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6966 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6967 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6968 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6969 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6970 if ( edge->IsOnEdge() ) {
6971 if ( edge->_2neibors->include( f->_le1 ) ||
6972 edge->_2neibors->include( f->_le2 )) continue;
6975 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6976 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6978 dist1 = dist2 = Precision::Infinite();
6979 if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6980 dist1 = Precision::Infinite();
6981 if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6982 dist2 = Precision::Infinite();
6983 if (( dist1 > segLen ) && ( dist2 > segLen ))
6986 if ( edge->IsOnEdge() )
6988 // skip perpendicular EDGEs
6989 gp_Vec fSegDir = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6990 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6991 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6992 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6993 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6998 // either limit inflation of edges or remember them for updating _normal
6999 // double dot = edge->_normal * f->GetDir();
7002 collEdges._intEdges.push_back( f->_le1 );
7003 collEdges._intEdges.push_back( f->_le2 );
7007 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
7008 // edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
7012 if ( !collEdges._intEdges.empty() )
7014 collEdges._edge = edge;
7015 data._collisionEdges.push_back( collEdges );
7020 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7023 // restore the zero thickness
7024 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7026 _EdgesOnShape& eos = data._edgesOnShape[iS];
7027 if ( eos._edges.empty() ) continue;
7028 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7030 for ( size_t i = 0; i < eos._edges.size(); ++i )
7032 eos._edges[i]->InvalidateStep( 1, eos );
7033 eos._edges[i]->_len = 0;
7038 //================================================================================
7040 * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7041 * will be updated at each inflation step
7043 //================================================================================
7045 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace & convFace,
7047 SMESH_MesherHelper& helper )
7049 const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7050 const double preci = BRep_Tool::Tolerance( convFace._face );
7051 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7053 bool edgesToUpdateFound = false;
7055 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7056 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7058 _EdgesOnShape& eos = * id2eos->second;
7059 if ( !eos._sWOL.IsNull() ) continue;
7060 if ( !eos._hyp.ToSmooth() ) continue;
7061 for ( size_t i = 0; i < eos._edges.size(); ++i )
7063 _LayerEdge* ledge = eos._edges[ i ];
7064 if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7065 if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7067 gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7068 ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7070 // the normal must be updated if distance from tgtPos to surface is less than
7073 // find an initial UV for search of a projection of tgtPos to surface
7074 const SMDS_MeshNode* nodeInFace = 0;
7075 SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7076 while ( fIt->more() && !nodeInFace )
7078 const SMDS_MeshElement* f = fIt->next();
7079 if ( convFaceID != f->getshapeId() ) continue;
7081 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7082 while ( nIt->more() && !nodeInFace )
7084 const SMDS_MeshElement* n = nIt->next();
7085 if ( n->getshapeId() == convFaceID )
7086 nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7091 gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7094 surface->NextValueOfUV( uv, tgtPos, preci );
7095 double dist = surface->Gap();
7096 if ( dist < 0.95 * ledge->_maxLen )
7098 ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7099 if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7100 ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7101 edgesToUpdateFound = true;
7106 if ( !convFace._isTooCurved && edgesToUpdateFound )
7108 data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7112 //================================================================================
7114 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7115 * _LayerEdge's on neighbor EDGE's
7117 //================================================================================
7119 bool _ViscousBuilder::updateNormals( _SolidData& data,
7120 SMESH_MesherHelper& helper,
7124 updateNormalsOfC1Vertices( data );
7126 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7129 // map to store new _normal and _cosin for each intersected edge
7130 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
7131 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7132 _LayerEdge zeroEdge;
7133 zeroEdge._normal.SetCoord( 0,0,0 );
7134 zeroEdge._maxLen = Precision::Infinite();
7135 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7137 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7139 double segLen, dist1, dist2, dist;
7140 vector< pair< _LayerEdge*, double > > intEdgesDist;
7141 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7143 for ( int iter = 0; iter < 5; ++iter )
7145 edge2newEdge.clear();
7147 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7149 _CollisionEdges& ce = data._collisionEdges[iE];
7150 _LayerEdge* edge1 = ce._edge;
7151 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7152 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7153 if ( !eos1 ) continue;
7155 // detect intersections
7156 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7157 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7159 intEdgesDist.clear();
7160 double minIntDist = Precision::Infinite();
7161 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7163 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7164 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
7165 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7167 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7168 double fact = ( 1.1 + dot * dot );
7169 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7170 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7171 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7172 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7173 dist1 = dist2 = Precision::Infinite();
7174 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
7175 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7178 if ( dist > testLen || dist <= 0 )
7181 if ( dist > testLen || dist <= 0 )
7184 // choose a closest edge
7185 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7186 double d1 = intP.SquareDistance( pSrc0 );
7187 double d2 = intP.SquareDistance( pSrc1 );
7188 int iClose = i + ( d2 < d1 );
7189 _LayerEdge* edge2 = ce._intEdges[iClose];
7190 edge2->Unset( _LayerEdge::MARKED );
7192 // choose a closest edge among neighbors
7193 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7194 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7195 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7197 _LayerEdge * edgeJ = intEdgesDist[j].first;
7198 if ( edge2->IsNeiborOnEdge( edgeJ ))
7200 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7201 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7204 intEdgesDist.push_back( make_pair( edge2, dist ));
7205 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7207 // iClose = i + !( d2 < d1 );
7208 // intEdges.push_back( ce._intEdges[iClose] );
7209 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7211 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7216 // compute new _normals
7217 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7219 _LayerEdge* edge2 = intEdgesDist[i].first;
7220 double distWgt = edge1->_len / intEdgesDist[i].second;
7221 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7222 // edge2->Is( _LayerEdge::BLOCKED )) continue;
7223 if ( edge2->Is( _LayerEdge::MARKED )) continue;
7224 edge2->Set( _LayerEdge::MARKED );
7227 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7229 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7230 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7231 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7232 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7233 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7234 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7235 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7236 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7237 newNormal.Normalize();
7241 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7242 if ( cos1 < theMinSmoothCosin )
7244 newCos = cos2 * sgn1;
7246 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7248 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7252 newCos = edge1->_cosin;
7255 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7256 e2neIt->second._normal += distWgt * newNormal;
7257 e2neIt->second._cosin = newCos;
7258 e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7259 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7260 e2neIt->second._normal += dir2;
7262 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7263 e2neIt->second._normal += distWgt * newNormal;
7264 if ( Precision::IsInfinite( zeroEdge._maxLen ))
7266 e2neIt->second._cosin = edge2->_cosin;
7267 e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7269 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7270 e2neIt->second._normal += dir1;
7274 if ( edge2newEdge.empty() )
7275 break; //return true;
7277 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7279 // Update data of edges depending on a new _normal
7282 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7284 _LayerEdge* edge = e2neIt->first;
7285 _LayerEdge& newEdge = e2neIt->second;
7286 _EdgesOnShape* eos = data.GetShapeEdges( edge );
7287 if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7290 // Check if a new _normal is OK:
7291 newEdge._normal.Normalize();
7292 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7294 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7296 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7297 edge->SetMaxLen( newEdge._maxLen );
7298 edge->SetNewLength( newEdge._maxLen, *eos, helper );
7300 continue; // the new _normal is bad
7302 // the new _normal is OK
7304 // find shapes that need smoothing due to change of _normal
7305 if ( edge->_cosin < theMinSmoothCosin &&
7306 newEdge._cosin > theMinSmoothCosin )
7308 if ( eos->_sWOL.IsNull() )
7310 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7311 while ( fIt->more() )
7312 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7314 else // edge inflates along a FACE
7316 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7317 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7318 while ( const TopoDS_Shape* E = eIt->next() )
7320 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7321 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7322 if ( angle < M_PI / 2 )
7323 shapesToSmooth.insert( data.GetShapeEdges( *E ));
7328 double len = edge->_len;
7329 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7330 edge->SetNormal( newEdge._normal );
7331 edge->SetCosin( newEdge._cosin );
7332 edge->SetNewLength( len, *eos, helper );
7333 edge->Set( _LayerEdge::MARKED );
7334 edge->Set( _LayerEdge::NORMAL_UPDATED );
7335 edgesNoAnaSmooth.insert( eos );
7338 // Update normals and other dependent data of not intersecting _LayerEdge's
7339 // neighboring the intersecting ones
7341 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7343 _LayerEdge* edge1 = e2neIt->first;
7344 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7345 if ( !edge1->Is( _LayerEdge::MARKED ))
7348 if ( edge1->IsOnEdge() )
7350 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7351 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7352 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7355 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7357 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7359 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7360 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7361 continue; // j-th neighbor is also intersected
7362 _LayerEdge* prevEdge = edge1;
7363 const int nbSteps = 10;
7364 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7366 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7367 neighbor->Is( _LayerEdge::MARKED ))
7369 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7370 if ( !eos ) continue;
7371 _LayerEdge* nextEdge = neighbor;
7372 if ( neighbor->_2neibors )
7375 nextEdge = neighbor->_2neibors->_edges[iNext];
7376 if ( nextEdge == prevEdge )
7377 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7379 double r = double(step-1)/nbSteps/(iter+1);
7380 if ( !nextEdge->_2neibors )
7383 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7384 newNorm.Normalize();
7385 if ( !isNewNormalOk( data, *neighbor, newNorm ))
7388 double len = neighbor->_len;
7389 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
7390 neighbor->SetNormal( newNorm );
7391 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7392 if ( neighbor->_2neibors )
7393 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7394 neighbor->SetNewLength( len, *eos, helper );
7395 neighbor->Set( _LayerEdge::MARKED );
7396 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7397 edgesNoAnaSmooth.insert( eos );
7399 if ( !neighbor->_2neibors )
7400 break; // neighbor is on VERTEX
7402 // goto the next neighbor
7403 prevEdge = neighbor;
7404 neighbor = nextEdge;
7411 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7416 //================================================================================
7418 * \brief Check if a new normal is OK
7420 //================================================================================
7422 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
7424 const gp_XYZ& newNormal)
7426 // check a min angle between the newNormal and surrounding faces
7427 vector<_Simplex> simplices;
7428 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7429 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7430 double newMinDot = 1, curMinDot = 1;
7431 for ( size_t i = 0; i < simplices.size(); ++i )
7433 n1.Set( simplices[i]._nPrev );
7434 n2.Set( simplices[i]._nNext );
7435 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7436 double normLen2 = normFace.SquareModulus();
7437 if ( normLen2 < std::numeric_limits<double>::min() )
7439 normFace /= Sqrt( normLen2 );
7440 newMinDot = Min( newNormal * normFace, newMinDot );
7441 curMinDot = Min( edge._normal * normFace, curMinDot );
7444 if ( newMinDot < 0.5 )
7446 ok = ( newMinDot >= curMinDot * 0.9 );
7447 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7448 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7449 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7455 //================================================================================
7457 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7459 //================================================================================
7461 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
7462 SMESH_MesherHelper& helper,
7464 const double stepSize )
7466 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7467 return true; // no shapes needing smoothing
7469 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7471 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7472 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
7473 !eos._hyp.ToSmooth() ||
7474 eos.ShapeType() != TopAbs_FACE ||
7475 eos._edges.empty() )
7478 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7479 if ( !toSmooth ) continue;
7481 for ( size_t i = 0; i < eos._edges.size(); ++i )
7483 _LayerEdge* edge = eos._edges[i];
7484 if ( !edge->Is( _LayerEdge::SMOOTHED ))
7486 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7489 const gp_XYZ& pPrev = edge->PrevPos();
7490 const gp_XYZ& pLast = edge->_pos.back();
7491 gp_XYZ stepVec = pLast - pPrev;
7492 double realStepSize = stepVec.Modulus();
7493 if ( realStepSize < numeric_limits<double>::min() )
7496 edge->_lenFactor = realStepSize / stepSize;
7497 edge->_normal = stepVec / realStepSize;
7498 edge->Set( _LayerEdge::NORMAL_UPDATED );
7505 //================================================================================
7507 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7509 //================================================================================
7511 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7513 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7515 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7516 if ( eov._eosC1.empty() ||
7517 eov.ShapeType() != TopAbs_VERTEX ||
7518 eov._edges.empty() )
7521 gp_XYZ newNorm = eov._edges[0]->_normal;
7522 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7523 bool normChanged = false;
7525 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7527 _EdgesOnShape* eoe = eov._eosC1[i];
7528 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7529 const double eLen = SMESH_Algo::EdgeLength( e );
7530 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
7531 if ( oppV.IsSame( eov._shape ))
7532 oppV = SMESH_MesherHelper::IthVertex( 1, e );
7533 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7534 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7535 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7537 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7538 if ( curThickOpp + curThick < eLen )
7541 double wgt = 2. * curThick / eLen;
7542 newNorm += wgt * eovOpp->_edges[0]->_normal;
7547 eov._edges[0]->SetNormal( newNorm.Normalized() );
7548 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7553 //================================================================================
7555 * \brief Modify normals of _LayerEdge's on _ConvexFace's
7557 //================================================================================
7559 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
7560 SMESH_MesherHelper& helper,
7563 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7566 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7567 for ( ; id2face != data._convexFaces.end(); ++id2face )
7569 _ConvexFace & convFace = (*id2face).second;
7570 convFace._normalsFixedOnBorders = false; // to update at each inflation step
7572 if ( convFace._normalsFixed )
7573 continue; // already fixed
7574 if ( convFace.CheckPrisms() )
7575 continue; // nothing to fix
7577 convFace._normalsFixed = true;
7579 BRepAdaptor_Surface surface ( convFace._face, false );
7580 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
7582 // check if the convex FACE is of spherical shape
7584 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7588 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7589 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7591 _EdgesOnShape& eos = *(id2eos->second);
7592 if ( eos.ShapeType() == TopAbs_VERTEX )
7594 _LayerEdge* ledge = eos._edges[ 0 ];
7595 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7596 centersBox.Add( center );
7598 for ( size_t i = 0; i < eos._edges.size(); ++i )
7599 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7601 if ( centersBox.IsVoid() )
7603 debugMsg( "Error: centersBox.IsVoid()" );
7606 const bool isSpherical =
7607 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7609 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7610 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7614 // set _LayerEdge::_normal as average of all normals
7616 // WARNING: different density of nodes on EDGEs is not taken into account that
7617 // can lead to an improper new normal
7619 gp_XYZ avgNormal( 0,0,0 );
7621 id2eos = convFace._subIdToEOS.begin();
7622 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7624 _EdgesOnShape& eos = *(id2eos->second);
7625 // set data of _CentralCurveOnEdge
7626 if ( eos.ShapeType() == TopAbs_EDGE )
7628 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7629 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7630 if ( !eos._sWOL.IsNull() )
7631 ceCurve._adjFace.Nullify();
7633 ceCurve._ledges.insert( ceCurve._ledges.end(),
7634 eos._edges.begin(), eos._edges.end());
7636 // summarize normals
7637 for ( size_t i = 0; i < eos._edges.size(); ++i )
7638 avgNormal += eos._edges[ i ]->_normal;
7640 double normSize = avgNormal.SquareModulus();
7641 if ( normSize < 1e-200 )
7643 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7646 avgNormal /= Sqrt( normSize );
7648 // compute new _LayerEdge::_cosin on EDGEs
7649 double avgCosin = 0;
7652 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7654 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7655 if ( ceCurve._adjFace.IsNull() )
7657 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7659 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7660 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7663 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7664 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7665 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7671 avgCosin /= nbCosin;
7673 // set _LayerEdge::_normal = avgNormal
7674 id2eos = convFace._subIdToEOS.begin();
7675 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7677 _EdgesOnShape& eos = *(id2eos->second);
7678 if ( eos.ShapeType() != TopAbs_EDGE )
7679 for ( size_t i = 0; i < eos._edges.size(); ++i )
7680 eos._edges[ i ]->_cosin = avgCosin;
7682 for ( size_t i = 0; i < eos._edges.size(); ++i )
7684 eos._edges[ i ]->SetNormal( avgNormal );
7685 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7689 else // if ( isSpherical )
7691 // We suppose that centers of curvature at all points of the FACE
7692 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7693 // having a common center of curvature we define the same new normal
7694 // as a sum of normals of _LayerEdge's on EDGEs among them.
7696 // get all centers of curvature for each EDGE
7698 helper.SetSubShape( convFace._face );
7699 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7701 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7702 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7704 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7706 // set adjacent FACE
7707 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7709 // get _LayerEdge's of the EDGE
7710 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7711 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7712 if ( !eos || eos->_edges.empty() )
7714 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7715 for ( int iV = 0; iV < 2; ++iV )
7717 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7718 TGeomID vID = meshDS->ShapeToIndex( v );
7719 eos = data.GetShapeEdges( vID );
7720 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7722 edgeLEdge = &vertexLEdges[0];
7723 edgeLEdgeEnd = edgeLEdge + 2;
7725 centerCurves[ iE ]._adjFace.Nullify();
7729 if ( ! eos->_toSmooth )
7730 data.SortOnEdge( edge, eos->_edges );
7731 edgeLEdge = &eos->_edges[ 0 ];
7732 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7733 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7734 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7736 if ( ! eos->_sWOL.IsNull() )
7737 centerCurves[ iE ]._adjFace.Nullify();
7740 // Get curvature centers
7744 if ( edgeLEdge[0]->IsOnEdge() &&
7745 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7747 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7748 centersBox.Add( center );
7750 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7751 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7752 { // EDGE or VERTEXes
7753 centerCurves[ iE ].Append( center, *edgeLEdge );
7754 centersBox.Add( center );
7756 if ( edgeLEdge[-1]->IsOnEdge() &&
7757 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7759 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7760 centersBox.Add( center );
7762 centerCurves[ iE ]._isDegenerated =
7763 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7765 } // loop on EDGES of convFace._face to set up data of centerCurves
7767 // Compute new normals for _LayerEdge's on EDGEs
7769 double avgCosin = 0;
7772 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7774 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7775 if ( ceCurve._isDegenerated )
7777 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7778 vector< gp_XYZ > & newNormals = ceCurve._normals;
7779 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7782 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7785 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7787 if ( isOK && !ceCurve._adjFace.IsNull() )
7789 // compute new _LayerEdge::_cosin
7790 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7791 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7794 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7795 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7796 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7802 // set new normals to _LayerEdge's of NOT degenerated central curves
7803 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7805 if ( centerCurves[ iE ]._isDegenerated )
7807 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7809 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7810 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7813 // set new normals to _LayerEdge's of degenerated central curves
7814 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7816 if ( !centerCurves[ iE ]._isDegenerated ||
7817 centerCurves[ iE ]._ledges.size() < 3 )
7819 // new normal is an average of new normals at VERTEXes that
7820 // was computed on non-degenerated _CentralCurveOnEdge's
7821 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7822 centerCurves[ iE ]._ledges.back ()->_normal );
7823 double sz = newNorm.Modulus();
7827 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7828 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7829 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7831 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7832 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7833 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7837 // Find new normals for _LayerEdge's based on FACE
7840 avgCosin /= nbCosin;
7841 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7842 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7843 if ( id2eos != convFace._subIdToEOS.end() )
7847 _EdgesOnShape& eos = * ( id2eos->second );
7848 for ( size_t i = 0; i < eos._edges.size(); ++i )
7850 _LayerEdge* ledge = eos._edges[ i ];
7851 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7853 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7855 iE = iE % centerCurves.size();
7856 if ( centerCurves[ iE ]._isDegenerated )
7858 newNorm.SetCoord( 0,0,0 );
7859 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7861 ledge->SetNormal( newNorm );
7862 ledge->_cosin = avgCosin;
7863 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7870 } // not a quasi-spherical FACE
7872 // Update _LayerEdge's data according to a new normal
7874 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7875 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7877 id2eos = convFace._subIdToEOS.begin();
7878 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7880 _EdgesOnShape& eos = * ( id2eos->second );
7881 for ( size_t i = 0; i < eos._edges.size(); ++i )
7883 _LayerEdge* & ledge = eos._edges[ i ];
7884 double len = ledge->_len;
7885 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7886 ledge->SetCosin( ledge->_cosin );
7887 ledge->SetNewLength( len, eos, helper );
7889 if ( eos.ShapeType() != TopAbs_FACE )
7890 for ( size_t i = 0; i < eos._edges.size(); ++i )
7892 _LayerEdge* ledge = eos._edges[ i ];
7893 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7895 _LayerEdge* neibor = ledge->_neibors[iN];
7896 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7898 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7899 neibor->Set( _LayerEdge::MOVED );
7900 neibor->SetSmooLen( neibor->_len );
7904 } // loop on sub-shapes of convFace._face
7906 // Find FACEs adjacent to convFace._face that got necessity to smooth
7907 // as a result of normals modification
7909 set< _EdgesOnShape* > adjFacesToSmooth;
7910 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7912 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7913 centerCurves[ iE ]._adjFaceToSmooth )
7915 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7917 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7919 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7924 data.AddShapesToSmooth( adjFacesToSmooth );
7929 } // loop on data._convexFaces
7934 //================================================================================
7936 * \brief Return max curvature of a FACE
7938 //================================================================================
7940 double _ConvexFace::GetMaxCurvature( _SolidData& data,
7942 BRepLProp_SLProps& surfProp,
7943 SMESH_MesherHelper& helper)
7945 double maxCurvature = 0;
7947 TopoDS_Face F = TopoDS::Face( eof._shape );
7949 const int nbTestPnt = 5;
7950 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7951 SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7952 while ( smIt->more() )
7954 SMESH_subMesh* sm = smIt->next();
7955 const TGeomID subID = sm->GetId();
7957 // find _LayerEdge's of a sub-shape
7959 if (( eos = data.GetShapeEdges( subID )))
7960 this->_subIdToEOS.insert( make_pair( subID, eos ));
7964 // check concavity and curvature and limit data._stepSize
7965 const double minCurvature =
7966 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7967 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7968 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7970 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7971 surfProp.SetParameters( uv.X(), uv.Y() );
7972 if ( surfProp.IsCurvatureDefined() )
7974 double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7975 surfProp.MinCurvature() * oriFactor );
7976 maxCurvature = Max( maxCurvature, curvature );
7978 if ( curvature > minCurvature )
7979 this->_isTooCurved = true;
7982 } // loop on sub-shapes of the FACE
7984 return maxCurvature;
7987 //================================================================================
7989 * \brief Finds a center of curvature of a surface at a _LayerEdge
7991 //================================================================================
7993 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7994 BRepLProp_SLProps& surfProp,
7995 SMESH_MesherHelper& helper,
7996 gp_Pnt & center ) const
7998 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7999 surfProp.SetParameters( uv.X(), uv.Y() );
8000 if ( !surfProp.IsCurvatureDefined() )
8003 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8004 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
8005 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
8006 if ( surfCurvatureMin > surfCurvatureMax )
8007 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
8009 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
8014 //================================================================================
8016 * \brief Check that prisms are not distorted
8018 //================================================================================
8020 bool _ConvexFace::CheckPrisms() const
8023 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8025 const _LayerEdge* edge = _simplexTestEdges[i];
8026 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8027 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8028 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8030 debugMsg( "Bad simplex of _simplexTestEdges ("
8031 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8032 << " "<< edge->_simplices[j]._nPrev->GetID()
8033 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8040 //================================================================================
8042 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8043 * stored in this _CentralCurveOnEdge.
8044 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8045 * \param [in,out] newNormal - current normal at this point, to be redefined
8046 * \return bool - true if succeeded.
8048 //================================================================================
8050 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8052 if ( this->_isDegenerated )
8055 // find two centers the given one lies between
8057 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
8059 double sl2 = 1.001 * _segLength2[ i ];
8061 double d1 = center.SquareDistance( _curvaCenters[ i ]);
8065 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8066 if ( d2 > sl2 || d2 + d1 < 1e-100 )
8071 double r = d1 / ( d1 + d2 );
8072 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
8073 ( r ) * _ledges[ i+1 ]->_normal );
8077 double sz = newNormal.Modulus();
8086 //================================================================================
8088 * \brief Set shape members
8090 //================================================================================
8092 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
8093 const _ConvexFace& convFace,
8095 SMESH_MesherHelper& helper)
8099 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8100 while ( const TopoDS_Shape* F = fIt->next())
8101 if ( !convFace._face.IsSame( *F ))
8103 _adjFace = TopoDS::Face( *F );
8104 _adjFaceToSmooth = false;
8105 // _adjFace already in a smoothing queue ?
8106 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8107 _adjFaceToSmooth = eos->_toSmooth;
8112 //================================================================================
8114 * \brief Looks for intersection of it's last segment with faces
8115 * \param distance - returns shortest distance from the last node to intersection
8117 //================================================================================
8119 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
8121 const double& epsilon,
8123 const SMDS_MeshElement** intFace)
8125 vector< const SMDS_MeshElement* > suspectFaces;
8127 gp_Ax1 lastSegment = LastSegment( segLen, eos );
8128 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8130 bool segmentIntersected = false;
8131 distance = Precision::Infinite();
8132 int iFace = -1; // intersected face
8133 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8135 const SMDS_MeshElement* face = suspectFaces[j];
8136 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8137 face->GetNodeIndex( _nodes[0] ) >= 0 )
8138 continue; // face sharing _LayerEdge node
8139 const int nbNodes = face->NbCornerNodes();
8140 bool intFound = false;
8142 SMDS_MeshElement::iterator nIt = face->begin_nodes();
8145 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8149 const SMDS_MeshNode* tria[3];
8152 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8155 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8161 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8162 segmentIntersected = true;
8163 if ( distance > dist )
8164 distance = dist, iFace = j;
8167 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8171 if ( segmentIntersected )
8174 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8175 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8176 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8177 << ", intersection with face ("
8178 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8179 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8180 << ") distance = " << distance << endl;
8184 return segmentIntersected;
8187 //================================================================================
8189 * \brief Returns a point used to check orientation of _simplices
8191 //================================================================================
8193 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8195 size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8197 if ( !eos || eos->_sWOL.IsNull() )
8200 if ( eos->SWOLType() == TopAbs_EDGE )
8202 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8204 //else // TopAbs_FACE
8206 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8209 //================================================================================
8211 * \brief Returns size and direction of the last segment
8213 //================================================================================
8215 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8217 // find two non-coincident positions
8218 gp_XYZ orig = _pos.back();
8220 int iPrev = _pos.size() - 2;
8221 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8222 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8223 while ( iPrev >= 0 )
8225 vec = orig - _pos[iPrev];
8226 if ( vec.SquareModulus() > tol*tol )
8236 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8237 segDir.SetDirection( _normal );
8242 gp_Pnt pPrev = _pos[ iPrev ];
8243 if ( !eos._sWOL.IsNull() )
8245 TopLoc_Location loc;
8246 if ( eos.SWOLType() == TopAbs_EDGE )
8249 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8250 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8254 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8255 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8257 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8259 segDir.SetLocation( pPrev );
8260 segDir.SetDirection( vec );
8261 segLen = vec.Modulus();
8267 //================================================================================
8269 * \brief Return the last (or \a which) position of the target node on a FACE.
8270 * \param [in] F - the FACE this _LayerEdge is inflated along
8271 * \param [in] which - index of position
8272 * \return gp_XY - result UV
8274 //================================================================================
8276 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8278 if ( F.IsSame( eos._sWOL )) // F is my FACE
8279 return gp_XY( _pos.back().X(), _pos.back().Y() );
8281 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8282 return gp_XY( 1e100, 1e100 );
8284 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8285 double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8286 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8287 if ( !C2d.IsNull() && f <= u && u <= l )
8288 return C2d->Value( u ).XY();
8290 return gp_XY( 1e100, 1e100 );
8293 //================================================================================
8295 * \brief Test intersection of the last segment with a given triangle
8296 * using Moller-Trumbore algorithm
8297 * Intersection is detected if distance to intersection is less than _LayerEdge._len
8299 //================================================================================
8301 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8302 const gp_XYZ& vert0,
8303 const gp_XYZ& vert1,
8304 const gp_XYZ& vert2,
8306 const double& EPSILON) const
8308 const gp_Pnt& orig = lastSegment.Location();
8309 const gp_Dir& dir = lastSegment.Direction();
8311 /* calculate distance from vert0 to ray origin */
8312 //gp_XYZ tvec = orig.XYZ() - vert0;
8314 //if ( tvec * dir > EPSILON )
8315 // intersected face is at back side of the temporary face this _LayerEdge belongs to
8318 gp_XYZ edge1 = vert1 - vert0;
8319 gp_XYZ edge2 = vert2 - vert0;
8321 /* begin calculating determinant - also used to calculate U parameter */
8322 gp_XYZ pvec = dir.XYZ() ^ edge2;
8324 /* if determinant is near zero, ray lies in plane of triangle */
8325 double det = edge1 * pvec;
8327 const double ANGL_EPSILON = 1e-12;
8328 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8331 /* calculate distance from vert0 to ray origin */
8332 gp_XYZ tvec = orig.XYZ() - vert0;
8334 /* calculate U parameter and test bounds */
8335 double u = ( tvec * pvec ) / det;
8336 //if (u < 0.0 || u > 1.0)
8337 if ( u < -EPSILON || u > 1.0 + EPSILON )
8340 /* prepare to test V parameter */
8341 gp_XYZ qvec = tvec ^ edge1;
8343 /* calculate V parameter and test bounds */
8344 double v = (dir.XYZ() * qvec) / det;
8345 //if ( v < 0.0 || u + v > 1.0 )
8346 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8349 /* calculate t, ray intersects triangle */
8350 t = (edge2 * qvec) / det;
8356 //================================================================================
8358 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8359 * neighbor _LayerEdge's by it's own inflation vector.
8360 * \param [in] eov - EOS of the VERTEX
8361 * \param [in] eos - EOS of the FACE
8362 * \param [in] step - inflation step
8363 * \param [in,out] badSmooEdges - tangled _LayerEdge's
8365 //================================================================================
8367 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
8368 const _EdgesOnShape* eos,
8370 vector< _LayerEdge* > & badSmooEdges )
8372 // check if any of _neibors is in badSmooEdges
8373 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8374 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8377 // get all edges to move
8379 set< _LayerEdge* > edges;
8381 // find a distance between _LayerEdge on VERTEX and its neighbors
8382 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
8384 for ( size_t i = 0; i < _neibors.size(); ++i )
8386 _LayerEdge* nEdge = _neibors[i];
8387 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8389 edges.insert( nEdge );
8390 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8393 // add _LayerEdge's close to curPosV
8397 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8399 _LayerEdge* edgeF = *e;
8400 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8402 _LayerEdge* nEdge = edgeF->_neibors[i];
8403 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8404 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8405 edges.insert( nEdge );
8409 while ( nbE < edges.size() );
8411 // move the target node of the got edges
8413 gp_XYZ prevPosV = PrevPos();
8414 if ( eov->SWOLType() == TopAbs_EDGE )
8416 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8417 prevPosV = curve.Value( prevPosV.X() ).XYZ();
8419 else if ( eov->SWOLType() == TopAbs_FACE )
8421 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8422 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8425 SMDS_FacePositionPtr fPos;
8426 //double r = 1. - Min( 0.9, step / 10. );
8427 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8429 _LayerEdge* edgeF = *e;
8430 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
8431 const gp_XYZ newPosF = curPosV + prevVF;
8432 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8433 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8434 edgeF->_pos.back() = newPosF;
8435 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8437 // set _curvature to make edgeF updated by putOnOffsetSurface()
8438 if ( !edgeF->_curvature )
8439 if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8441 edgeF->_curvature = _Factory::NewCurvature();
8442 edgeF->_curvature->_r = 0;
8443 edgeF->_curvature->_k = 0;
8444 edgeF->_curvature->_h2lenRatio = 0;
8445 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8448 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8449 // SMESH_TNodeXYZ( _nodes[0] ));
8450 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8452 // _LayerEdge* edgeF = *e;
8453 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8454 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8455 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8456 // edgeF->_pos.back() = newPosF;
8457 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8460 // smooth _LayerEdge's around moved nodes
8461 //size_t nbBadBefore = badSmooEdges.size();
8462 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8464 _LayerEdge* edgeF = *e;
8465 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8466 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8467 //&& !edges.count( edgeF->_neibors[j] ))
8469 _LayerEdge* edgeFN = edgeF->_neibors[j];
8470 edgeFN->Unset( SMOOTHED );
8471 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8474 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8475 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8476 // int nbBadAfter = edgeFN->_simplices.size();
8478 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8480 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8482 // if ( nbBadAfter <= nbBad )
8484 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8485 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8486 // edgeF->_pos.back() = newPosF;
8487 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8488 // nbBad = nbBadAfter;
8492 badSmooEdges.push_back( edgeFN );
8495 // move a bit not smoothed around moved nodes
8496 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8498 // _LayerEdge* edgeF = badSmooEdges[i];
8499 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8500 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8501 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8502 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8503 // edgeF->_pos.back() = newPosF;
8504 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8508 //================================================================================
8510 * \brief Perform smooth of _LayerEdge's based on EDGE's
8511 * \retval bool - true if node has been moved
8513 //================================================================================
8515 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8516 const TopoDS_Face& F,
8517 SMESH_MesherHelper& helper)
8519 ASSERT( IsOnEdge() );
8521 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8522 SMESH_TNodeXYZ oldPos( tgtNode );
8523 double dist01, distNewOld;
8525 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8526 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8527 dist01 = p0.Distance( _2neibors->tgtNode(1) );
8529 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8530 double lenDelta = 0;
8533 //lenDelta = _curvature->lenDelta( _len );
8534 lenDelta = _curvature->lenDeltaByDist( dist01 );
8535 newPos.ChangeCoord() += _normal * lenDelta;
8538 distNewOld = newPos.Distance( oldPos );
8542 if ( _2neibors->_plnNorm )
8544 // put newPos on the plane defined by source node and _plnNorm
8545 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8546 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8547 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8549 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8550 _pos.back() = newPos.XYZ();
8554 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8555 gp_XY uv( Precision::Infinite(), 0 );
8556 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8557 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8559 newPos = surface->Value( uv );
8560 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8563 // commented for IPAL0052478
8564 // if ( _curvature && lenDelta < 0 )
8566 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8567 // _len -= prevPos.Distance( oldPos );
8568 // _len += prevPos.Distance( newPos );
8570 bool moved = distNewOld > dist01/50;
8572 dumpMove( tgtNode ); // debug
8577 //================================================================================
8579 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8581 //================================================================================
8583 void _LayerEdge::SmoothWoCheck()
8585 if ( Is( DIFFICULT ))
8588 bool moved = Is( SMOOTHED );
8589 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
8590 moved = _neibors[i]->Is( SMOOTHED );
8594 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8596 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8597 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8598 _pos.back() = newPos;
8600 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8603 //================================================================================
8605 * \brief Checks validity of _neibors on EDGEs and VERTEXes
8607 //================================================================================
8609 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8611 if ( ! Is( NEAR_BOUNDARY ))
8616 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8618 _LayerEdge* eN = _neibors[iN];
8619 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8622 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8623 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8624 eN->_pos.size() != _pos.size() );
8626 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8627 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8628 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8629 if ( eN->_nodes.size() > 1 &&
8630 eN->_simplices[i].Includes( _nodes.back() ) &&
8631 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8636 badNeibors->push_back( eN );
8637 debugMsg("Bad boundary simplex ( "
8638 << " "<< eN->_nodes[0]->GetID()
8639 << " "<< eN->_nodes.back()->GetID()
8640 << " "<< eN->_simplices[i]._nPrev->GetID()
8641 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8652 //================================================================================
8654 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8655 * \retval int - nb of bad simplices around this _LayerEdge
8657 //================================================================================
8659 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8661 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8662 return 0; // shape of simplices not changed
8663 if ( _simplices.size() < 2 )
8664 return 0; // _LayerEdge inflated along EDGE or FACE
8666 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8669 const gp_XYZ& curPos = _pos.back();
8670 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8672 // quality metrics (orientation) of tetras around _tgtNode
8674 double vol, minVolBefore = 1e100;
8675 for ( size_t i = 0; i < _simplices.size(); ++i )
8677 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8678 minVolBefore = Min( minVolBefore, vol );
8680 int nbBad = _simplices.size() - nbOkBefore;
8682 bool bndNeedSmooth = false;
8684 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8688 // evaluate min angle
8689 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8691 size_t nbGoodAngles = _simplices.size();
8693 for ( size_t i = 0; i < _simplices.size(); ++i )
8695 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8698 if ( nbGoodAngles == _simplices.size() )
8704 if ( Is( ON_CONCAVE_FACE ))
8707 if ( step % 2 == 0 )
8710 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8712 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8713 _smooFunction = _funs[ FUN_CENTROIDAL ];
8715 _smooFunction = _funs[ FUN_LAPLACIAN ];
8718 // compute new position for the last _pos using different _funs
8721 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8724 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8725 else if ( _funs[ iFun ] == _smooFunction )
8726 continue; // _smooFunction again
8727 else if ( step > 1 )
8728 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8730 break; // let "easy" functions improve elements around distorted ones
8734 double delta = _curvature->lenDelta( _len );
8736 newPos += _normal * delta;
8739 double segLen = _normal * ( newPos - prevPos );
8740 if ( segLen + delta > 0 )
8741 newPos += _normal * delta;
8743 // double segLenChange = _normal * ( curPos - newPos );
8744 // newPos += 0.5 * _normal * segLenChange;
8748 double minVolAfter = 1e100;
8749 for ( size_t i = 0; i < _simplices.size(); ++i )
8751 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8752 minVolAfter = Min( minVolAfter, vol );
8755 if ( nbOkAfter < nbOkBefore )
8759 ( nbOkAfter == nbOkBefore ) &&
8760 ( minVolAfter <= minVolBefore ))
8763 nbBad = _simplices.size() - nbOkAfter;
8764 minVolBefore = minVolAfter;
8765 nbOkBefore = nbOkAfter;
8768 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8769 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8770 _pos.back() = newPos;
8772 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8773 << (nbBad ? " --BAD" : ""));
8777 continue; // look for a better function
8783 } // loop on smoothing functions
8785 if ( moved ) // notify _neibors
8788 for ( size_t i = 0; i < _neibors.size(); ++i )
8789 if ( !_neibors[i]->Is( MOVED ))
8791 _neibors[i]->Set( MOVED );
8792 toSmooth.push_back( _neibors[i] );
8799 //================================================================================
8801 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8802 * \retval int - nb of bad simplices around this _LayerEdge
8804 //================================================================================
8806 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8808 if ( !_smooFunction )
8809 return 0; // _LayerEdge inflated along EDGE or FACE
8811 return 0; // not inflated
8813 const gp_XYZ& curPos = _pos.back();
8814 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8816 // quality metrics (orientation) of tetras around _tgtNode
8818 double vol, minVolBefore = 1e100;
8819 for ( size_t i = 0; i < _simplices.size(); ++i )
8821 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8822 minVolBefore = Min( minVolBefore, vol );
8824 int nbBad = _simplices.size() - nbOkBefore;
8826 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8828 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8829 _smooFunction = _funs[ FUN_LAPLACIAN ];
8830 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8831 _smooFunction = _funs[ FUN_CENTROIDAL ];
8834 // compute new position for the last _pos using different _funs
8836 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8839 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8840 else if ( _funs[ iFun ] == _smooFunction )
8841 continue; // _smooFunction again
8842 else if ( step > 1 )
8843 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8845 break; // let "easy" functions improve elements around distorted ones
8849 double delta = _curvature->lenDelta( _len );
8851 newPos += _normal * delta;
8854 double segLen = _normal * ( newPos - prevPos );
8855 if ( segLen + delta > 0 )
8856 newPos += _normal * delta;
8858 // double segLenChange = _normal * ( curPos - newPos );
8859 // newPos += 0.5 * _normal * segLenChange;
8863 double minVolAfter = 1e100;
8864 for ( size_t i = 0; i < _simplices.size(); ++i )
8866 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8867 minVolAfter = Min( minVolAfter, vol );
8870 if ( nbOkAfter < nbOkBefore )
8872 if (( isConcaveFace || findBest ) &&
8873 ( nbOkAfter == nbOkBefore ) &&
8874 ( minVolAfter <= minVolBefore )
8878 nbBad = _simplices.size() - nbOkAfter;
8879 minVolBefore = minVolAfter;
8880 nbOkBefore = nbOkAfter;
8882 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8883 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8884 _pos.back() = newPos;
8886 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8887 << ( nbBad ? "--BAD" : ""));
8889 // commented for IPAL0052478
8890 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8891 // _len += prevPos.Distance(newPos);
8893 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8895 //_smooFunction = _funs[ iFun ];
8896 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8897 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8898 // << " minVol: " << minVolAfter
8899 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8901 continue; // look for a better function
8907 } // loop on smoothing functions
8912 //================================================================================
8914 * \brief Chooses a smoothing technique giving a position most close to an initial one.
8915 * For a correct result, _simplices must contain nodes lying on geometry.
8917 //================================================================================
8919 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8920 const TNode2Edge& n2eMap)
8922 if ( _smooFunction ) return;
8924 // use smoothNefPolygon() near concaveVertices
8925 if ( !concaveVertices.empty() )
8927 _smooFunction = _funs[ FUN_CENTROIDAL ];
8929 Set( ON_CONCAVE_FACE );
8931 for ( size_t i = 0; i < _simplices.size(); ++i )
8933 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8935 _smooFunction = _funs[ FUN_NEFPOLY ];
8937 // set FUN_CENTROIDAL to neighbor edges
8938 for ( i = 0; i < _neibors.size(); ++i )
8940 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8942 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8949 // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8950 // // where the nodes are smoothed too far along a sphere thus creating
8951 // // inverted _simplices
8952 // double dist[theNbSmooFuns];
8953 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8954 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8956 // double minDist = Precision::Infinite();
8957 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8958 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8960 // gp_Pnt newP = (this->*_funs[i])();
8961 // dist[i] = p.SquareDistance( newP );
8962 // if ( dist[i]*coef[i] < minDist )
8964 // _smooFunction = _funs[i];
8965 // minDist = dist[i]*coef[i];
8971 _smooFunction = _funs[ FUN_LAPLACIAN ];
8974 // for ( size_t i = 0; i < _simplices.size(); ++i )
8975 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8976 // if ( minDim == 0 )
8977 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8978 // else if ( minDim == 1 )
8979 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8983 // for ( int i = 0; i < FUN_NB; ++i )
8985 // //cout << dist[i] << " ";
8986 // if ( _smooFunction == _funs[i] ) {
8988 // //debugMsg( fNames[i] );
8992 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8995 //================================================================================
8997 * \brief Returns a name of _SmooFunction
8999 //================================================================================
9001 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
9004 fun = _smooFunction;
9005 for ( int i = 0; i < theNbSmooFuns; ++i )
9006 if ( fun == _funs[i] )
9009 return theNbSmooFuns;
9012 //================================================================================
9014 * \brief Computes a new node position using Laplacian smoothing
9016 //================================================================================
9018 gp_XYZ _LayerEdge::smoothLaplacian()
9020 gp_XYZ newPos (0,0,0);
9021 for ( size_t i = 0; i < _simplices.size(); ++i )
9022 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9023 newPos /= _simplices.size();
9028 //================================================================================
9030 * \brief Computes a new node position using angular-based smoothing
9032 //================================================================================
9034 gp_XYZ _LayerEdge::smoothAngular()
9036 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
9037 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
9038 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
9040 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9042 for ( size_t i = 0; i < _simplices.size(); ++i )
9044 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9045 edgeDir.push_back( p - pPrev );
9046 edgeSize.push_back( edgeDir.back().Magnitude() );
9047 if ( edgeSize.back() < numeric_limits<double>::min() )
9050 edgeSize.pop_back();
9054 edgeDir.back() /= edgeSize.back();
9055 points.push_back( p );
9060 edgeDir.push_back ( edgeDir[0] );
9061 edgeSize.push_back( edgeSize[0] );
9062 pN /= points.size();
9064 gp_XYZ newPos(0,0,0);
9066 for ( size_t i = 0; i < points.size(); ++i )
9068 gp_Vec toN = pN - points[i];
9069 double toNLen = toN.Magnitude();
9070 if ( toNLen < numeric_limits<double>::min() )
9075 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
9076 double bisecLen = bisec.SquareMagnitude();
9077 if ( bisecLen < numeric_limits<double>::min() )
9079 gp_Vec norm = edgeDir[i] ^ toN;
9080 bisec = norm ^ edgeDir[i];
9081 bisecLen = bisec.SquareMagnitude();
9083 bisecLen = Sqrt( bisecLen );
9087 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9088 sumSize += bisecLen;
9090 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9091 sumSize += ( edgeSize[i] + edgeSize[i+1] );
9097 // project newPos to an average plane
9099 gp_XYZ norm(0,0,0); // plane normal
9100 points.push_back( points[0] );
9101 for ( size_t i = 1; i < points.size(); ++i )
9103 gp_XYZ vec1 = points[ i-1 ] - pN;
9104 gp_XYZ vec2 = points[ i ] - pN;
9105 gp_XYZ cross = vec1 ^ vec2;
9108 if ( cross * norm < numeric_limits<double>::min() )
9109 norm += cross.Reversed();
9113 catch (Standard_Failure) { // if |cross| == 0.
9116 gp_XYZ vec = newPos - pN;
9117 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
9118 newPos = newPos - r * norm;
9123 //================================================================================
9125 * \brief Computes a new node position using weighted node positions
9127 //================================================================================
9129 gp_XYZ _LayerEdge::smoothLengthWeighted()
9131 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9132 vector< gp_XYZ > points; points. reserve( _simplices.size() );
9134 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9135 for ( size_t i = 0; i < _simplices.size(); ++i )
9137 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9138 edgeSize.push_back( ( p - pPrev ).Modulus() );
9139 if ( edgeSize.back() < numeric_limits<double>::min() )
9141 edgeSize.pop_back();
9145 points.push_back( p );
9149 edgeSize.push_back( edgeSize[0] );
9151 gp_XYZ newPos(0,0,0);
9153 for ( size_t i = 0; i < points.size(); ++i )
9155 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9156 sumSize += edgeSize[i] + edgeSize[i+1];
9162 //================================================================================
9164 * \brief Computes a new node position using angular-based smoothing
9166 //================================================================================
9168 gp_XYZ _LayerEdge::smoothCentroidal()
9170 gp_XYZ newPos(0,0,0);
9171 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9173 for ( size_t i = 0; i < _simplices.size(); ++i )
9175 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9176 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9177 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9178 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9181 newPos += gc * size;
9188 //================================================================================
9190 * \brief Computes a new node position located inside a Nef polygon
9192 //================================================================================
9194 gp_XYZ _LayerEdge::smoothNefPolygon()
9195 #ifdef OLD_NEF_POLYGON
9197 gp_XYZ newPos(0,0,0);
9199 // get a plane to search a solution on
9201 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9203 const double tol = numeric_limits<double>::min();
9204 gp_XYZ center(0,0,0);
9205 for ( i = 0; i < _simplices.size(); ++i )
9207 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9208 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9209 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9211 vecs.back() = vecs[0];
9212 center /= _simplices.size();
9214 gp_XYZ zAxis(0,0,0);
9215 for ( i = 0; i < _simplices.size(); ++i )
9216 zAxis += vecs[i] ^ vecs[i+1];
9219 for ( i = 0; i < _simplices.size(); ++i )
9222 if ( yAxis.SquareModulus() > tol )
9225 gp_XYZ xAxis = yAxis ^ zAxis;
9226 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9227 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9228 // p0.Distance( _simplices[2]._nPrev ));
9229 // gp_XYZ center = smoothLaplacian();
9230 // gp_XYZ xAxis, yAxis, zAxis;
9231 // for ( i = 0; i < _simplices.size(); ++i )
9233 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9234 // if ( xAxis.SquareModulus() > tol*tol )
9237 // for ( i = 1; i < _simplices.size(); ++i )
9239 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9240 // zAxis = xAxis ^ yAxis;
9241 // if ( zAxis.SquareModulus() > tol*tol )
9244 // if ( i == _simplices.size() ) return newPos;
9246 yAxis = zAxis ^ xAxis;
9247 xAxis /= xAxis.Modulus();
9248 yAxis /= yAxis.Modulus();
9250 // get half-planes of _simplices
9252 vector< _halfPlane > halfPlns( _simplices.size() );
9254 for ( size_t i = 0; i < _simplices.size(); ++i )
9256 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9257 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9258 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9259 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9260 gp_XY vec12 = p2 - p1;
9261 double dist12 = vec12.Modulus();
9265 halfPlns[ nbHP ]._pos = p1;
9266 halfPlns[ nbHP ]._dir = vec12;
9267 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9271 // intersect boundaries of half-planes, define state of intersection points
9272 // in relation to all half-planes and calculate internal point of a 2D polygon
9275 gp_XY newPos2D (0,0);
9277 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9278 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9279 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9281 vector< vector< TIntPntState > > allIntPnts( nbHP );
9282 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9284 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9285 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9287 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9288 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9291 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9293 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9295 if ( iHP1 == iHP2 ) continue;
9297 TIntPntState & ips1 = intPnts1[ iHP2 ];
9298 if ( ips1.second == UNDEF )
9300 // find an intersection point of boundaries of iHP1 and iHP2
9302 if ( iHP2 == iPrev ) // intersection with neighbors is known
9303 ips1.first = halfPlns[ iHP1 ]._pos;
9304 else if ( iHP2 == iNext )
9305 ips1.first = halfPlns[ iHP2 ]._pos;
9306 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9307 ips1.second = NO_INT;
9309 // classify the found intersection point
9310 if ( ips1.second != NO_INT )
9312 ips1.second = NOT_OUT;
9313 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9314 if ( i != iHP1 && i != iHP2 &&
9315 halfPlns[ i ].IsOut( ips1.first, tol ))
9316 ips1.second = IS_OUT;
9318 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9319 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9320 TIntPntState & ips2 = intPnts2[ iHP1 ];
9323 if ( ips1.second == NOT_OUT )
9326 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9330 // find a NOT_OUT segment of boundary which is located between
9331 // two NOT_OUT int points
9334 continue; // no such a segment
9338 // sort points along the boundary
9339 map< double, TIntPntState* > ipsByParam;
9340 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9342 TIntPntState & ips1 = intPnts1[ iHP2 ];
9343 if ( ips1.second != NO_INT )
9345 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9346 double param = op * halfPlns[ iHP1 ]._dir;
9347 ipsByParam.insert( make_pair( param, & ips1 ));
9350 // look for two neighboring NOT_OUT points
9352 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9353 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9355 TIntPntState & ips1 = *(u2ips->second);
9356 if ( ips1.second == NOT_OUT )
9357 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9358 else if ( nbNotOut >= 2 )
9365 if ( nbNotOut >= 2 )
9367 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9370 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9377 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9386 #else // OLD_NEF_POLYGON
9387 { ////////////////////////////////// NEW
9388 gp_XYZ newPos(0,0,0);
9390 // get a plane to search a solution on
9393 gp_XYZ center(0,0,0);
9394 for ( i = 0; i < _simplices.size(); ++i )
9395 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9396 center /= _simplices.size();
9398 vector< gp_XYZ > vecs( _simplices.size() + 1 );
9399 for ( i = 0; i < _simplices.size(); ++i )
9400 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9401 vecs.back() = vecs[0];
9403 const double tol = numeric_limits<double>::min();
9404 gp_XYZ zAxis(0,0,0);
9405 for ( i = 0; i < _simplices.size(); ++i )
9407 gp_XYZ cross = vecs[i] ^ vecs[i+1];
9410 if ( cross * zAxis < tol )
9411 zAxis += cross.Reversed();
9415 catch (Standard_Failure) { // if |cross| == 0.
9420 for ( i = 0; i < _simplices.size(); ++i )
9423 if ( yAxis.SquareModulus() > tol )
9426 gp_XYZ xAxis = yAxis ^ zAxis;
9427 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9428 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9429 // p0.Distance( _simplices[2]._nPrev ));
9430 // gp_XYZ center = smoothLaplacian();
9431 // gp_XYZ xAxis, yAxis, zAxis;
9432 // for ( i = 0; i < _simplices.size(); ++i )
9434 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9435 // if ( xAxis.SquareModulus() > tol*tol )
9438 // for ( i = 1; i < _simplices.size(); ++i )
9440 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9441 // zAxis = xAxis ^ yAxis;
9442 // if ( zAxis.SquareModulus() > tol*tol )
9445 // if ( i == _simplices.size() ) return newPos;
9447 yAxis = zAxis ^ xAxis;
9448 xAxis /= xAxis.Modulus();
9449 yAxis /= yAxis.Modulus();
9451 // get half-planes of _simplices
9453 vector< _halfPlane > halfPlns( _simplices.size() );
9455 for ( size_t i = 0; i < _simplices.size(); ++i )
9457 const gp_XYZ& OP1 = vecs[ i ];
9458 const gp_XYZ& OP2 = vecs[ i+1 ];
9459 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
9460 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
9461 gp_XY vec12 = p2 - p1;
9462 double dist12 = vec12.Modulus();
9466 halfPlns[ nbHP ]._pos = p1;
9467 halfPlns[ nbHP ]._dir = vec12;
9468 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9472 // intersect boundaries of half-planes, define state of intersection points
9473 // in relation to all half-planes and calculate internal point of a 2D polygon
9476 gp_XY newPos2D (0,0);
9478 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9479 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9480 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9482 vector< vector< TIntPntState > > allIntPnts( nbHP );
9483 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9485 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9486 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9488 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9489 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9492 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9494 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9496 if ( iHP1 == iHP2 ) continue;
9498 TIntPntState & ips1 = intPnts1[ iHP2 ];
9499 if ( ips1.second == UNDEF )
9501 // find an intersection point of boundaries of iHP1 and iHP2
9503 if ( iHP2 == iPrev ) // intersection with neighbors is known
9504 ips1.first = halfPlns[ iHP1 ]._pos;
9505 else if ( iHP2 == iNext )
9506 ips1.first = halfPlns[ iHP2 ]._pos;
9507 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9508 ips1.second = NO_INT;
9510 // classify the found intersection point
9511 if ( ips1.second != NO_INT )
9513 ips1.second = NOT_OUT;
9514 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9515 if ( i != iHP1 && i != iHP2 &&
9516 halfPlns[ i ].IsOut( ips1.first, tol ))
9517 ips1.second = IS_OUT;
9519 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9520 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9521 TIntPntState & ips2 = intPnts2[ iHP1 ];
9524 if ( ips1.second == NOT_OUT )
9527 segEnds[ bool(segEnds[0]) ] = & ips1.first;
9531 // find a NOT_OUT segment of boundary which is located between
9532 // two NOT_OUT int points
9535 continue; // no such a segment
9539 // sort points along the boundary
9540 map< double, TIntPntState* > ipsByParam;
9541 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9543 TIntPntState & ips1 = intPnts1[ iHP2 ];
9544 if ( ips1.second != NO_INT )
9546 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
9547 double param = op * halfPlns[ iHP1 ]._dir;
9548 ipsByParam.insert( make_pair( param, & ips1 ));
9551 // look for two neighboring NOT_OUT points
9553 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9554 for ( ; u2ips != ipsByParam.end(); ++u2ips )
9556 TIntPntState & ips1 = *(u2ips->second);
9557 if ( ips1.second == NOT_OUT )
9558 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9559 else if ( nbNotOut >= 2 )
9566 if ( nbNotOut >= 2 )
9568 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9571 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9578 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9587 #endif // OLD_NEF_POLYGON
9589 //================================================================================
9591 * \brief Add a new segment to _LayerEdge during inflation
9593 //================================================================================
9595 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9600 if ( len > _maxLen )
9603 Block( eos.GetData() );
9605 const double lenDelta = len - _len;
9606 if ( lenDelta < len * 1e-3 )
9608 Block( eos.GetData() );
9612 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9613 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9615 if ( eos._hyp.IsOffsetMethod() )
9619 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9620 while ( faceIt->more() )
9622 const SMDS_MeshElement* face = faceIt->next();
9623 if ( !eos.GetNormal( face, faceNorm ))
9626 // translate plane of a face
9627 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9629 // find point of intersection of the face plane located at baryCenter
9630 // and _normal located at newXYZ
9631 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9632 double dot = ( faceNorm.XYZ() * _normal );
9633 if ( dot < std::numeric_limits<double>::min() )
9634 dot = lenDelta * 1e-3;
9635 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9636 newXYZ += step * _normal;
9638 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9642 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9645 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9646 _pos.push_back( newXYZ );
9648 if ( !eos._sWOL.IsNull() )
9652 if ( eos.SWOLType() == TopAbs_EDGE )
9654 double u = Precision::Infinite(); // to force projection w/o distance check
9655 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9656 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9657 _pos.back().SetCoord( u, 0, 0 );
9658 if ( _nodes.size() > 1 && uvOK )
9660 SMDS_EdgePositionPtr pos = n->GetPosition();
9661 pos->SetUParameter( u );
9666 gp_XY uv( Precision::Infinite(), 0 );
9667 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9668 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9669 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9670 if ( _nodes.size() > 1 && uvOK )
9672 SMDS_FacePositionPtr pos = n->GetPosition();
9673 pos->SetUParameter( uv.X() );
9674 pos->SetVParameter( uv.Y() );
9679 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9683 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9685 Block( eos.GetData() );
9693 if ( eos.ShapeType() != TopAbs_FACE )
9695 for ( size_t i = 0; i < _neibors.size(); ++i )
9696 //if ( _len > _neibors[i]->GetSmooLen() )
9697 _neibors[i]->Set( MOVED );
9701 dumpMove( n ); //debug
9704 //================================================================================
9706 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9708 //================================================================================
9710 void _LayerEdge::Block( _SolidData& data )
9712 //if ( Is( BLOCKED )) return;
9715 SMESH_Comment msg( "#BLOCK shape=");
9716 msg << data.GetShapeEdges( this )->_shapeID
9717 << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9718 dumpCmd( msg + " -- BEGIN");
9721 std::queue<_LayerEdge*> queue;
9724 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9725 while ( !queue.empty() )
9727 _LayerEdge* edge = queue.front(); queue.pop();
9728 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9729 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9730 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9732 _LayerEdge* neibor = edge->_neibors[iN];
9733 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9735 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9736 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9737 double minDist = pSrc.SquareDistance( pSrcN );
9738 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9739 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9740 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9741 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9742 //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9744 //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9745 // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9746 // neibor->_lenFactor / edge->_lenFactor );
9748 if ( neibor->_maxLen > newMaxLen )
9750 neibor->SetMaxLen( newMaxLen );
9751 if ( neibor->_maxLen < neibor->_len )
9753 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9754 int lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9755 while ( neibor->_len > neibor->_maxLen &&
9756 neibor->NbSteps() > lastStep )
9757 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9758 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9759 //neibor->Block( data );
9761 queue.push( neibor );
9765 dumpCmd( msg + " -- END");
9768 //================================================================================
9770 * \brief Remove last inflation step
9772 //================================================================================
9774 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9776 if ( _pos.size() > curStep && _nodes.size() > 1 )
9778 _pos.resize( curStep );
9780 gp_Pnt nXYZ = _pos.back();
9781 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9782 SMESH_TNodeXYZ curXYZ( n );
9783 if ( !eos._sWOL.IsNull() )
9785 TopLoc_Location loc;
9786 if ( eos.SWOLType() == TopAbs_EDGE )
9788 SMDS_EdgePositionPtr pos = n->GetPosition();
9789 pos->SetUParameter( nXYZ.X() );
9791 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9792 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9796 SMDS_FacePositionPtr pos = n->GetPosition();
9797 pos->SetUParameter( nXYZ.X() );
9798 pos->SetVParameter( nXYZ.Y() );
9799 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9800 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9803 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9806 if ( restoreLength )
9808 if ( NbSteps() == 0 )
9810 else if ( IsOnFace() && Is( MOVED ))
9811 _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9813 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9819 //================================================================================
9821 * \brief Return index of a _pos distant from _normal
9823 //================================================================================
9825 int _LayerEdge::GetSmoothedPos( const double tol )
9828 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9830 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9831 if ( normDist > tol * tol )
9837 //================================================================================
9839 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9841 //================================================================================
9843 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9845 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9848 // find the 1st smoothed _pos
9849 int iSmoothed = GetSmoothedPos( tol );
9850 if ( !iSmoothed ) return;
9852 gp_XYZ normal = _normal;
9853 if ( Is( NORMAL_UPDATED ))
9856 for ( size_t i = 0; i < _neibors.size(); ++i )
9858 if ( _neibors[i]->IsOnFace() )
9860 double dot = _normal * _neibors[i]->_normal;
9863 normal = _neibors[i]->_normal;
9869 for ( size_t i = 1; i < _pos.size(); ++i )
9871 normal = _pos[i] - _pos[0];
9872 double size = normal.Modulus();
9873 if ( size > RealSmall() )
9880 const double r = 0.2;
9881 for ( int iter = 0; iter < 50; ++iter )
9884 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9886 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9887 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9889 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9890 double newLen = ( 1-r ) * midLen + r * segLen[i];
9891 const_cast< double& >( segLen[i] ) = newLen;
9892 // check angle between normal and (_pos[i+1], _pos[i] )
9893 gp_XYZ posDir = _pos[i+1] - _pos[i];
9894 double size = posDir.SquareModulus();
9895 if ( size > RealSmall() )
9896 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9898 if ( minDot > 0.5 * 0.5 )
9904 //================================================================================
9906 * \brief Print flags
9908 //================================================================================
9910 std::string _LayerEdge::DumpFlags() const
9913 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9914 if ( _flags & flag )
9916 EFlags f = (EFlags) flag;
9918 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
9919 case MOVED: dump << "MOVED"; break;
9920 case SMOOTHED: dump << "SMOOTHED"; break;
9921 case DIFFICULT: dump << "DIFFICULT"; break;
9922 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9923 case BLOCKED: dump << "BLOCKED"; break;
9924 case INTERSECTED: dump << "INTERSECTED"; break;
9925 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
9926 case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9927 case MARKED: dump << "MARKED"; break;
9928 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
9929 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
9930 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
9931 case DISTORTED: dump << "DISTORTED"; break;
9932 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
9933 case SHRUNK: dump << "SHRUNK"; break;
9934 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
9938 cout << dump << endl;
9943 //================================================================================
9945 * \brief Create layers of prisms
9947 //================================================================================
9949 bool _ViscousBuilder::refine(_SolidData& data)
9951 SMESH_MesherHelper& helper = data.GetHelper();
9952 helper.SetElementsOnShape(false);
9954 Handle(Geom_Curve) curve;
9955 Handle(ShapeAnalysis_Surface) surface;
9956 TopoDS_Edge geomEdge;
9957 TopoDS_Face geomFace;
9958 TopLoc_Location loc;
9961 vector< gp_XYZ > pos3D;
9962 bool isOnEdge, isTooConvexFace = false;
9963 TGeomID prevBaseId = -1;
9964 TNode2Edge* n2eMap = 0;
9965 TNode2Edge::iterator n2e;
9967 // Create intermediate nodes on each _LayerEdge
9969 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9971 _EdgesOnShape& eos = data._edgesOnShape[iS];
9972 if ( eos._edges.empty() ) continue;
9974 if ( eos._edges[0]->_nodes.size() < 2 )
9975 continue; // on _noShrinkShapes
9977 // get data of a shrink shape
9979 geomEdge.Nullify(); geomFace.Nullify();
9980 curve.Nullify(); surface.Nullify();
9981 if ( !eos._sWOL.IsNull() )
9983 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9986 geomEdge = TopoDS::Edge( eos._sWOL );
9987 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9991 geomFace = TopoDS::Face( eos._sWOL );
9992 surface = helper.GetSurface( geomFace );
9995 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9997 geomFace = TopoDS::Face( eos._shape );
9998 surface = helper.GetSurface( geomFace );
9999 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
10000 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
10001 eos._eosC1[ i ]->_toSmooth = true;
10003 isTooConvexFace = false;
10004 if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
10005 isTooConvexFace = cf->_isTooCurved;
10008 vector< double > segLen;
10009 for ( size_t i = 0; i < eos._edges.size(); ++i )
10011 _LayerEdge& edge = *eos._edges[i];
10012 if ( edge._pos.size() < 2 )
10015 // get accumulated length of segments
10016 segLen.resize( edge._pos.size() );
10018 if ( eos._sWOL.IsNull() )
10020 bool useNormal = true;
10021 bool usePos = false;
10022 bool smoothed = false;
10023 double preci = 0.1 * edge._len;
10024 if ( eos._toSmooth && edge._pos.size() > 2 )
10026 smoothed = edge.GetSmoothedPos( preci );
10030 if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10032 useNormal = usePos = false;
10033 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10034 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10036 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10037 if ( surface->Gap() < 2. * edge._len )
10038 segLen[j] = surface->Gap();
10044 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10046 #ifndef __NODES_AT_POS
10047 useNormal = usePos = false;
10048 edge._pos[1] = edge._pos.back();
10049 edge._pos.resize( 2 );
10050 segLen.resize( 2 );
10051 segLen[ 1 ] = edge._len;
10054 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10056 useNormal = usePos = false;
10057 _LayerEdge tmpEdge; // get original _normal
10058 tmpEdge._nodes.push_back( edge._nodes[0] );
10059 if ( !setEdgeData( tmpEdge, eos, helper, data ))
10062 for ( size_t j = 1; j < edge._pos.size(); ++j )
10063 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10067 for ( size_t j = 1; j < edge._pos.size(); ++j )
10068 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10072 for ( size_t j = 1; j < edge._pos.size(); ++j )
10073 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10077 bool swapped = ( edge._pos.size() > 2 );
10081 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10082 if ( segLen[j] > segLen.back() )
10084 segLen.erase( segLen.begin() + j );
10085 edge._pos.erase( edge._pos.begin() + j );
10088 else if ( segLen[j] < segLen[j-1] )
10090 std::swap( segLen[j], segLen[j-1] );
10091 std::swap( edge._pos[j], edge._pos[j-1] );
10096 // smooth a path formed by edge._pos
10097 #ifndef __NODES_AT_POS
10098 if (( smoothed ) /*&&
10099 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10100 edge.SmoothPos( segLen, preci );
10103 else if ( eos._isRegularSWOL ) // usual SWOL
10105 if ( edge.Is( _LayerEdge::SMOOTHED ))
10107 SMESH_NodeXYZ p0( edge._nodes[0] );
10108 for ( size_t j = 1; j < edge._pos.size(); ++j )
10110 gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10111 segLen[j] = ( pj - p0 ) * edge._normal;
10116 for ( size_t j = 1; j < edge._pos.size(); ++j )
10117 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10120 else if ( !surface.IsNull() ) // SWOL surface with singularities
10122 pos3D.resize( edge._pos.size() );
10123 for ( size_t j = 0; j < edge._pos.size(); ++j )
10124 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10126 for ( size_t j = 1; j < edge._pos.size(); ++j )
10127 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10130 // allocate memory for new nodes if it is not yet refined
10131 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10132 if ( edge._nodes.size() == 2 )
10134 #ifdef __NODES_AT_POS
10135 int nbNodes = edge._pos.size();
10137 int nbNodes = eos._hyp.GetNumberLayers() + 1;
10139 edge._nodes.resize( nbNodes, 0 );
10140 edge._nodes[1] = 0;
10141 edge._nodes.back() = tgtNode;
10143 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10144 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10145 if ( baseShapeId != prevBaseId )
10147 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10148 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10149 prevBaseId = baseShapeId;
10151 _LayerEdge* edgeOnSameNode = 0;
10152 bool useExistingPos = false;
10153 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10155 edgeOnSameNode = n2e->second;
10156 useExistingPos = ( edgeOnSameNode->_len < edge._len );
10157 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10158 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
10161 SMDS_EdgePositionPtr epos = lastPos;
10162 epos->SetUParameter( otherTgtPos.X() );
10166 SMDS_FacePositionPtr fpos = lastPos;
10167 fpos->SetUParameter( otherTgtPos.X() );
10168 fpos->SetVParameter( otherTgtPos.Y() );
10171 // calculate height of the first layer
10173 const double T = segLen.back(); //data._hyp.GetTotalThickness();
10174 const double f = eos._hyp.GetStretchFactor();
10175 const int N = eos._hyp.GetNumberLayers();
10176 const double fPowN = pow( f, N );
10177 if ( fPowN - 1 <= numeric_limits<double>::min() )
10180 h0 = T * ( f - 1 )/( fPowN - 1 );
10182 const double zeroLen = std::numeric_limits<double>::min();
10184 // create intermediate nodes
10185 double hSum = 0, hi = h0/f;
10187 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10189 // compute an intermediate position
10192 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10194 int iPrevSeg = iSeg-1;
10195 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10197 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10198 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10199 #ifdef __NODES_AT_POS
10200 pos = edge._pos[ iStep ];
10202 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10203 if ( !eos._sWOL.IsNull() )
10205 // compute XYZ by parameters <pos>
10210 pos = curve->Value( u ).Transformed(loc);
10212 else if ( eos._isRegularSWOL )
10214 uv.SetCoord( pos.X(), pos.Y() );
10216 pos = surface->Value( pos.X(), pos.Y() );
10220 uv.SetCoord( pos.X(), pos.Y() );
10221 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10222 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10224 pos = surface->Value( uv );
10227 // create or update the node
10230 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10231 if ( !eos._sWOL.IsNull() )
10234 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10236 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10240 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10245 if ( !eos._sWOL.IsNull() )
10247 // make average pos from new and current parameters
10250 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10251 if ( useExistingPos )
10252 u = helper.GetNodeU( geomEdge, node );
10253 pos = curve->Value( u ).Transformed(loc);
10255 SMDS_EdgePositionPtr epos = node->GetPosition();
10256 epos->SetUParameter( u );
10260 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10261 if ( useExistingPos )
10262 uv = helper.GetNodeUV( geomFace, node );
10263 pos = surface->Value( uv );
10265 SMDS_FacePositionPtr fpos = node->GetPosition();
10266 fpos->SetUParameter( uv.X() );
10267 fpos->SetVParameter( uv.Y() );
10270 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10272 } // loop on edge._nodes
10274 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10277 edge._pos.back().SetCoord( u, 0,0);
10279 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10281 if ( edgeOnSameNode )
10282 edgeOnSameNode->_pos.back() = edge._pos.back();
10285 } // loop on eos._edges to create nodes
10288 if ( !getMeshDS()->IsEmbeddedMode() )
10289 // Log node movement
10290 for ( size_t i = 0; i < eos._edges.size(); ++i )
10292 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10293 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10300 helper.SetElementsOnShape(true);
10302 vector< vector<const SMDS_MeshNode*>* > nnVec;
10303 set< vector<const SMDS_MeshNode*>* > nnSet;
10304 set< int > degenEdgeInd;
10305 vector<const SMDS_MeshElement*> degenVols;
10307 TopExp_Explorer exp( data._solid, TopAbs_FACE );
10308 for ( ; exp.More(); exp.Next() )
10310 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10311 if ( data._ignoreFaceIds.count( faceID ))
10313 _EdgesOnShape* eos = data.GetShapeEdges( faceID );
10314 SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10317 std::vector< const SMDS_MeshElement* > vols;
10318 const bool isReversedFace = data._reversedFaceIds.count( faceID );
10319 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
10320 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
10321 while ( fIt->more() )
10323 const SMDS_MeshElement* face = fIt->next();
10324 const int nbNodes = face->NbCornerNodes();
10325 nnVec.resize( nbNodes );
10327 degenEdgeInd.clear();
10328 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10329 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10330 for ( int iN = 0; iN < nbNodes; ++iN )
10332 const SMDS_MeshNode* n = nIt->next();
10333 _LayerEdge* edge = data._n2eMap[ n ];
10334 const int i = isReversedFace ? nbNodes-1-iN : iN;
10335 nnVec[ i ] = & edge->_nodes;
10336 maxZ = std::max( maxZ, nnVec[ i ]->size() );
10337 minZ = std::min( minZ, nnVec[ i ]->size() );
10339 if ( helper.HasDegeneratedEdges() )
10340 nnSet.insert( nnVec[ i ]);
10345 if ( 0 < nnSet.size() && nnSet.size() < 3 )
10349 const SMDS_MeshElement* vol;
10356 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10358 vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10359 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
10360 vols.push_back( vol );
10363 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10365 for ( int iN = 0; iN < nbNodes; ++iN )
10366 if ( nnVec[ iN ]->size() < iZ+1 )
10367 degenEdgeInd.insert( iN );
10369 if ( degenEdgeInd.size() == 1 ) // PYRAM
10371 int i2 = *degenEdgeInd.begin();
10372 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10373 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10374 vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10375 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
10376 vols.push_back( vol );
10380 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10381 vol = helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10382 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10383 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10384 (*nnVec[ i3 ])[ iZ ]);
10385 vols.push_back( vol );
10393 for ( size_t iZ = 1; iZ < minZ; ++iZ )
10395 vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10396 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10397 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
10398 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
10399 vols.push_back( vol );
10402 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10404 for ( int iN = 0; iN < nbNodes; ++iN )
10405 if ( nnVec[ iN ]->size() < iZ+1 )
10406 degenEdgeInd.insert( iN );
10408 switch ( degenEdgeInd.size() )
10412 int i2 = *degenEdgeInd.begin();
10413 int i3 = *degenEdgeInd.rbegin();
10414 bool ok = ( i3 - i2 == 1 );
10415 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10416 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10417 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10419 vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10420 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10421 vols.push_back( vol );
10423 degenVols.push_back( vol );
10427 default: // degen HEX
10429 vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10430 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10431 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10432 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10433 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
10434 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
10435 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
10436 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
10437 vols.push_back( vol );
10438 degenVols.push_back( vol );
10445 return error("Not supported type of element", data._index);
10447 } // switch ( nbNodes )
10450 for ( size_t i = 0; i < vols.size(); ++i )
10451 group->Add( vols[ i ]);
10453 } // while ( fIt->more() )
10456 if ( !degenVols.empty() )
10458 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10459 if ( !err || err->IsOK() )
10461 SMESH_BadInputElements* badElems =
10462 new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10463 badElems->myBadElements.insert( badElems->myBadElements.end(),
10464 degenVols.begin(),degenVols.end() );
10465 err.reset( badElems );
10472 namespace VISCOUS_3D
10475 //--------------------------------------------------------------------------------
10477 * \brief Pair of periodic FACEs
10479 struct PeriodicFaces
10481 typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10483 ShrinkFace* _shriFace[2];
10484 TNodeNodeMap _nnMap;
10487 PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10488 bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10489 bool MoveNodes( const TopoDS_Face& tgtFace );
10490 void Clear() { _nnMap.clear(); }
10491 bool IsEmpty() const { return _nnMap.empty(); }
10494 //--------------------------------------------------------------------------------
10496 * \brief Shrink FACE data used to find periodic FACEs
10500 // ................................................................................
10501 struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10503 bool _isShrink, _isReverse;
10506 std::vector< SMESH_NodeXYZ > _nodes;
10507 TopAbs_ShapeEnum _vertSWOLType[2]; // shrink part includes VERTEXes
10508 AverageHyp* _vertHyp[2];
10511 _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10512 _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }
10515 bool operator==( const BndPart& other ) const
10517 return ( _isShrink == other._isShrink &&
10518 _nbSegments == other._nbSegments &&
10519 _nodes.size() == other._nodes.size() &&
10520 vertSWOLType1() == other.vertSWOLType1() &&
10521 vertSWOLType2() == other.vertSWOLType2() &&
10523 ( *_hyp == *other._hyp &&
10524 vertHyp1() == other.vertHyp1() &&
10525 vertHyp2() == other.vertHyp2() ))
10528 bool CanAppend( const BndPart& other )
10530 return ( _isShrink == other._isShrink &&
10532 ( *_hyp == *other._hyp &&
10533 *_hyp == vertHyp2() &&
10534 vertHyp2() == other.vertHyp1() ))
10537 void Append( const BndPart& other )
10539 _nbSegments += other._nbSegments;
10540 bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10541 _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10542 _vertSWOLType[1] = other._vertSWOLType[1];
10544 _vertHyp[1] = other._vertHyp[1];
10546 const SMDS_MeshNode* Node(size_t i) const
10548 return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10550 void Reverse() { _isReverse = !_isReverse; }
10551 const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse ]; }
10552 const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10553 const AverageHyp& vertHyp1() const { return *(_vertHyp[ _isReverse ]); }
10554 const AverageHyp& vertHyp2() const { return *(_vertHyp[ !_isReverse ]); }
10556 // ................................................................................
10558 SMESH_subMesh* _subMesh;
10559 _SolidData* _data1;
10560 _SolidData* _data2;
10561 //bool _isPeriodic;
10563 std::list< BndPart > _boundary;
10564 int _boundarySize, _nbBoundaryParts;
10566 void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10568 _subMesh = sm; _data1 = sd1; _data2 = sd2; //_isPeriodic = false;
10570 bool IsSame( const TopoDS_Face& face ) const
10572 return _subMesh->GetSubShape().IsSame( face );
10574 bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10576 return shrunkFaces.Contains( _subMesh->GetSubShape() );
10579 //================================================================================
10581 * Check if meshes on two FACEs are equal
10583 bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10585 if ( !IsSameNbElements( other ))
10588 this->SetBoundary();
10589 other.SetBoundary();
10590 if ( this->_boundarySize != other._boundarySize ||
10591 this->_nbBoundaryParts != other._nbBoundaryParts )
10594 for ( int isReverse = 0; isReverse < 2; ++isReverse )
10597 Reverse( _boundary );
10599 // check boundaries
10600 bool equalBoundary = false;
10601 for ( int iP = 0; iP < _nbBoundaryParts && !equalBoundary; ++iP )
10603 if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10604 // set first part at end
10605 _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10607 if ( !equalBoundary )
10610 // check connectivity
10611 std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10612 this->GetElements( elemsThis );
10613 other.GetElements( elemsOther );
10614 SMESH_MeshEditor::Sew_Error err =
10615 SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10616 this->_boundary.front().Node(0),
10617 other._boundary.front().Node(0),
10618 this->_boundary.front().Node(1),
10619 other._boundary.front().Node(1),
10621 if ( err != SMESH_MeshEditor::SEW_OK )
10624 // check node positions
10625 std::vector< gp_XYZ > srcPnts, tgtPnts;
10626 this->GetBoundaryPoints( srcPnts );
10627 other.GetBoundaryPoints( tgtPnts );
10628 if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10631 double tol = std::numeric_limits<double>::max();
10632 for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10633 tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10635 tol = 0.01 * Sqrt( tol );
10636 bool nodeCoincide = true;
10637 TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10638 for ( ; n2n != periodic._nnMap.end() && nodeCoincide; ++n2n )
10640 SMESH_NodeXYZ nSrc = n2n->first;
10641 SMESH_NodeXYZ nTgt = n2n->second;
10642 gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
10643 nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol );
10645 if ( nodeCoincide )
10651 bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
10653 SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
10654 SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
10655 return ( sm1->NbElements() == sm2->NbElements() &&
10656 sm1->NbNodes() == sm2->NbNodes() );
10659 void Reverse( std::list< BndPart >& boundary )
10661 boundary.reverse();
10662 for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
10668 if ( !_boundary.empty() )
10671 TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
10672 if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
10673 std::list< TopoDS_Edge > edges;
10674 std::list< int > nbEdgesInWire;
10675 /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
10677 // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
10678 // if ( nbWires > 1 ) {
10679 // edgesEnd = edges.begin();
10680 // std::advance( edgesEnd, nbEdgesInWire.front() );
10682 StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
10683 /*fwd=*/true, /*skipMedium=*/true );
10684 _boundarySize = fSide.NbSegments();
10686 //TopoDS_Vertex vv[2];
10687 //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
10688 for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
10691 _EdgesOnShape* eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
10693 bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
10694 if ( bndPart._isShrink )
10695 if (( _data1->_noShrinkShapes.count( eos->_shapeID )) ||
10696 ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
10697 bndPart._isShrink = false;
10699 if ( bndPart._isShrink )
10701 bndPart._hyp = & eos->_hyp;
10702 _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
10703 _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
10704 for ( int iV = 0; iV < 2; ++iV )
10706 bndPart._vertHyp [iV] = & eov[iV]->_hyp;
10707 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10708 if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
10709 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10710 if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
10712 eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
10713 if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
10714 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10715 else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
10716 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10720 std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
10721 bndPart._nodes.assign( nodes.begin(), nodes.end() );
10722 bndPart._nbSegments = bndPart._nodes.size() - 1;
10724 if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
10725 _boundary.push_back( bndPart );
10727 _boundary.back().Append( bndPart );
10730 _nbBoundaryParts = _boundary.size();
10731 if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
10733 _boundary.back().Append( _boundary.front() );
10734 _boundary.pop_front();
10735 --_nbBoundaryParts;
10739 void GetElements( std::set<const SMDS_MeshElement*>& theElems)
10741 if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
10742 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
10743 theElems.insert( theElems.end(), fIt->next() );
10748 void GetBoundaryPoints( std::vector< gp_XYZ >& points )
10750 points.reserve( _boundarySize );
10751 size_t nb = _boundary.rbegin()->_nodes.size();
10752 int lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
10753 std::list< BndPart >::const_iterator part = _boundary.begin();
10754 for ( ; part != _boundary.end(); ++part )
10756 size_t nb = part->_nodes.size();
10758 size_t iR = nb - 1;
10759 size_t* i = part->_isReverse ? &iR : &iF;
10760 if ( part->_nodes[ *i ]->GetID() == lastID )
10762 for ( ; iF < nb; ++iF, --iR )
10763 points.push_back( part->_nodes[ *i ]);
10765 lastID = part->_nodes[ *i ]->GetID();
10768 }; // struct ShrinkFace
10770 //--------------------------------------------------------------------------------
10772 * \brief Periodic FACEs
10776 std::vector< ShrinkFace > _shrinkFaces;
10777 std::vector< PeriodicFaces > _periodicFaces;
10779 PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
10781 for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10782 if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
10783 return & _periodicFaces[ i ];
10786 void ClearPeriodic( const TopoDS_Face& face )
10788 for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10789 if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
10790 _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
10791 _periodicFaces[ i ].Clear();
10795 //================================================================================
10797 * Check if a pair includes the given FACE and the other FACE is already shrunk
10799 bool PeriodicFaces::IncludeShrunk( const TopoDS_Face& face,
10800 const TopTools_MapOfShape& shrunkFaces ) const
10802 if ( IsEmpty() ) return false;
10803 return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
10804 ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
10807 //================================================================================
10809 * Make equal meshes on periodic faces by moving corresponding nodes
10811 bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
10813 int iTgt = _shriFace[1]->IsSame( tgtFace );
10814 int iSrc = 1 - iTgt;
10816 _SolidData* dataSrc = _shriFace[iSrc]->_data1;
10817 _SolidData* dataTgt = _shriFace[iTgt]->_data1;
10819 Trsf * trsf = & _trsf, trsfInverse;
10822 trsfInverse = _trsf;
10823 if ( !trsfInverse.Invert())
10825 trsf = &trsfInverse;
10827 SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
10829 TNode2Edge::iterator n2e;
10830 TNodeNodeMap::iterator n2n = _nnMap.begin();
10831 for ( ; n2n != _nnMap.end(); ++n2n )
10833 const SMDS_MeshNode* const* nn = & n2n->first;
10834 const SMDS_MeshNode* nSrc = nn[ iSrc ];
10835 const SMDS_MeshNode* nTgt = nn[ iTgt ];
10837 if (( nSrc->GetPosition()->GetDim() == 2 ) ||
10838 (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
10840 SMESH_NodeXYZ pSrc = nSrc;
10841 gp_XYZ pTgt = trsf->Transform( pSrc );
10842 meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
10846 _LayerEdge* leSrc = n2e->second;
10847 n2e = dataTgt->_n2eMap.find( nTgt );
10848 if ( n2e == dataTgt->_n2eMap.end() )
10850 _LayerEdge* leTgt = n2e->second;
10851 if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
10853 for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
10855 SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
10856 gp_XYZ pTgt = trsf->Transform( pSrc );
10857 meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
10861 bool done = ( n2n == _nnMap.end() );
10862 debugMsg( "PeriodicFaces::MoveNodes "
10863 << _shriFace[iSrc]->_subMesh->GetId() << " -> "
10864 << _shriFace[iTgt]->_subMesh->GetId() << " -- "
10865 << ( done ? "DONE" : "FAIL"));
10869 } // namespace VISCOUS_3D; Periodicity part
10872 //================================================================================
10874 * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
10875 * and should remain equal after shrink
10877 //================================================================================
10879 void _ViscousBuilder::findPeriodicFaces()
10881 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10882 // _LayerEdge's inflated along FACE or EDGE)
10883 std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
10884 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10886 _SolidData& data = _sdVec[i];
10887 std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10888 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10889 if ( s2s->second.ShapeType() == TopAbs_FACE )
10890 id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10893 _periodicity.reset( new Periodicity );
10894 _periodicity->_shrinkFaces.resize( id2sdMap.size() );
10896 std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
10897 for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
10899 _SolidData* sd1 = id2sdIt->second.front();
10900 _SolidData* sd2 = id2sdIt->second.back();
10901 _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
10904 for ( size_t i1 = 0; i1 < _periodicity->_shrinkFaces.size(); ++i1 )
10905 for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
10907 PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
10908 & _periodicity->_shrinkFaces[ i2 ]);
10909 if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
10911 _periodicity->_periodicFaces.push_back( pf );
10917 //================================================================================
10919 * \brief Shrink 2D mesh on faces to let space for inflated layers
10921 //================================================================================
10923 bool _ViscousBuilder::shrink(_SolidData& theData)
10925 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10926 // _LayerEdge's inflated along FACE or EDGE)
10927 map< TGeomID, list< _SolidData* > > f2sdMap;
10928 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10930 _SolidData& data = _sdVec[i];
10931 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10932 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10933 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
10935 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10937 // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
10938 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10939 // by StdMeshers_QuadToTriaAdaptor
10940 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10942 SMESH_ProxyMesh::SubMesh* proxySub =
10943 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10944 if ( proxySub->NbElements() == 0 )
10946 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10947 while ( fIt->more() )
10949 const SMDS_MeshElement* f = fIt->next();
10950 // as a result 3D algo will use elements from proxySub and not from smDS
10951 proxySub->AddElement( f );
10952 f->setIsMarked( true );
10954 // Mark nodes on the FACE to discriminate them from nodes
10955 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10956 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10958 const SMDS_MeshNode* n = f->GetNode( iN );
10959 if ( n->GetPosition()->GetDim() == 2 )
10960 n->setIsMarked( true );
10968 SMESH_MesherHelper helper( *_mesh );
10969 helper.ToFixNodeParameters( true );
10972 map< TGeomID, _Shrinker1D > e2shrMap;
10973 vector< _EdgesOnShape* > subEOS;
10974 vector< _LayerEdge* > lEdges;
10976 // loop on FACEs to shrink mesh on
10977 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10978 for ( ; f2sd != f2sdMap.end(); ++f2sd )
10980 list< _SolidData* > & dataList = f2sd->second;
10981 if ( dataList.front()->_n2eMap.empty() ||
10982 dataList.back() ->_n2eMap.empty() )
10983 continue; // not yet computed
10984 if ( dataList.front() != &theData &&
10985 dataList.back() != &theData )
10988 _SolidData& data = *dataList.front();
10989 _SolidData* data2 = dataList.size() > 1 ? dataList.back() : 0;
10990 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10991 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
10992 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10994 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10996 _shrunkFaces.Add( F );
10997 helper.SetSubShape( F );
10999 // ==============================
11000 // Use periodicity to move nodes
11001 // ==============================
11003 PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
11004 bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
11006 // ===========================
11007 // Prepare data for shrinking
11008 // ===========================
11010 // Collect nodes to smooth (they are marked at the beginning of this method)
11011 vector < const SMDS_MeshNode* > smoothNodes;
11013 if ( !movedByPeriod )
11015 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11016 while ( nIt->more() )
11018 const SMDS_MeshNode* n = nIt->next();
11019 if ( n->isMarked() )
11020 smoothNodes.push_back( n );
11023 // Find out face orientation
11024 double refSign = 1;
11025 const set<TGeomID> ignoreShapes;
11027 if ( !smoothNodes.empty() )
11029 vector<_Simplex> simplices;
11030 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11031 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11032 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11033 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11034 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11038 // Find _LayerEdge's inflated along F
11042 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11043 /*complexFirst=*/true); //!!!
11044 while ( subIt->more() )
11046 const TGeomID subID = subIt->next()->GetId();
11047 if ( data._noShrinkShapes.count( subID ))
11049 _EdgesOnShape* eos = data.GetShapeEdges( subID );
11050 if ( !eos || eos->_sWOL.IsNull() )
11051 if ( data2 ) // check in adjacent SOLID
11053 eos = data2->GetShapeEdges( subID );
11054 if ( !eos || eos->_sWOL.IsNull() )
11057 subEOS.push_back( eos );
11059 if ( !movedByPeriod )
11060 for ( size_t i = 0; i < eos->_edges.size(); ++i )
11062 lEdges.push_back( eos->_edges[ i ] );
11063 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11068 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11069 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11070 while ( fIt->more() )
11071 if ( const SMDS_MeshElement* f = fIt->next() )
11072 dumpChangeNodes( f );
11075 // Replace source nodes by target nodes in mesh faces to shrink
11076 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11077 const SMDS_MeshNode* nodes[20];
11078 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11080 _EdgesOnShape& eos = * subEOS[ iS ];
11081 for ( size_t i = 0; i < eos._edges.size(); ++i )
11083 _LayerEdge& edge = *eos._edges[i];
11084 const SMDS_MeshNode* srcNode = edge._nodes[0];
11085 const SMDS_MeshNode* tgtNode = edge._nodes.back();
11086 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11087 while ( fIt->more() )
11089 const SMDS_MeshElement* f = fIt->next();
11090 if ( !smDS->Contains( f ) || !f->isMarked() )
11092 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11093 for ( int iN = 0; nIt->more(); ++iN )
11095 const SMDS_MeshNode* n = nIt->next();
11096 nodes[iN] = ( n == srcNode ? tgtNode : n );
11098 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11099 dumpChangeNodes( f );
11105 // find out if a FACE is concave
11106 const bool isConcaveFace = isConcave( F, helper );
11108 // Create _SmoothNode's on face F
11109 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11111 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11112 const bool sortSimplices = isConcaveFace;
11113 for ( size_t i = 0; i < smoothNodes.size(); ++i )
11115 const SMDS_MeshNode* n = smoothNodes[i];
11116 nodesToSmooth[ i ]._node = n;
11117 // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11118 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11119 // fix up incorrect uv of nodes on the FACE
11120 helper.GetNodeUV( F, n, 0, &isOkUV);
11125 //if ( nodesToSmooth.empty() ) continue;
11127 // Find EDGE's to shrink and set simpices to LayerEdge's
11128 set< _Shrinker1D* > eShri1D;
11130 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11132 _EdgesOnShape& eos = * subEOS[ iS ];
11133 if ( eos.SWOLType() == TopAbs_EDGE )
11135 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11136 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11137 if ( !movedByPeriod )
11139 _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11140 eShri1D.insert( & shrinker );
11141 shrinker.AddEdge( eos._edges[0], eos, helper );
11142 // restore params of nodes on EDGE if the EDGE has been already
11143 // shrunk while shrinking other FACE
11144 shrinker.RestoreParams();
11147 for ( size_t i = 0; i < eos._edges.size(); ++i )
11149 _LayerEdge& edge = * eos._edges[i];
11150 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11152 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11153 // not-marked nodes are those added by refine()
11154 edge._nodes.back()->setIsMarked( true );
11159 bool toFixTria = false; // to improve quality of trias by diagonal swap
11160 if ( isConcaveFace && !movedByPeriod )
11162 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11163 if ( hasTria != hasQuad ) {
11164 toFixTria = hasTria;
11167 set<int> nbNodesSet;
11168 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11169 while ( fIt->more() && nbNodesSet.size() < 2 )
11170 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11171 toFixTria = ( *nbNodesSet.begin() == 3 );
11175 // ==================
11176 // Perform shrinking
11177 // ==================
11179 bool shrunk = !movedByPeriod;
11180 int nbBad, shriStep=0, smooStep=0;
11181 _SmoothNode::SmoothType smoothType
11182 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11183 SMESH_Comment errMsg;
11187 // Move boundary nodes (actually just set new UV)
11188 // -----------------------------------------------
11189 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11191 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11193 _EdgesOnShape& eos = * subEOS[ iS ];
11194 for ( size_t i = 0; i < eos._edges.size(); ++i )
11196 shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11201 // Move nodes on EDGE's
11202 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11203 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11204 for ( ; shr != eShri1D.end(); ++shr )
11205 (*shr)->Compute( /*set3D=*/false, helper );
11208 // -----------------
11209 int nbNoImpSteps = 0;
11212 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11214 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11216 int oldBadNb = nbBad;
11219 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11220 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11221 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11223 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11224 smooTy, /*set3D=*/isConcaveFace);
11226 if ( nbBad < oldBadNb )
11236 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11237 if ( shriStep > 200 )
11238 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11239 if ( !errMsg.empty() )
11242 // Fix narrow triangles by swapping diagonals
11243 // ---------------------------------------
11246 set<const SMDS_MeshNode*> usedNodes;
11247 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11249 // update working data
11250 set<const SMDS_MeshNode*>::iterator n;
11251 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11253 n = usedNodes.find( nodesToSmooth[ i ]._node );
11254 if ( n != usedNodes.end())
11256 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11257 nodesToSmooth[ i ]._simplices,
11258 ignoreShapes, NULL,
11259 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11260 usedNodes.erase( n );
11263 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11265 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11266 if ( n != usedNodes.end())
11268 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11269 lEdges[i]->_simplices,
11271 usedNodes.erase( n );
11275 // TODO: check effect of this additional smooth
11276 // additional laplacian smooth to increase allowed shrink step
11277 // for ( int st = 1; st; --st )
11279 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11280 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11282 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11283 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
11287 } // while ( shrunk )
11289 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11291 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11294 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11296 vector< const SMDS_MeshElement* > facesToRm;
11299 facesToRm.reserve( psm->NbElements() );
11300 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11301 facesToRm.push_back( ite->next() );
11303 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11304 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11307 for ( size_t i = 0; i < facesToRm.size(); ++i )
11308 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11312 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11313 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11314 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11315 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11316 subEOS[iS]->_edges[i]->_nodes.end() );
11318 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11319 while ( itn->more() ) {
11320 const SMDS_MeshNode* n = itn->next();
11321 if ( !nodesToKeep.count( n ))
11322 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11325 _periodicity->ClearPeriodic( F );
11327 // restore position and UV of target nodes
11329 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11330 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11332 _LayerEdge* edge = subEOS[iS]->_edges[i];
11333 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11334 if ( edge->_pos.empty() ||
11335 edge->Is( _LayerEdge::SHRUNK )) continue;
11336 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11338 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11339 pos->SetUParameter( edge->_pos[0].X() );
11340 pos->SetVParameter( edge->_pos[0].Y() );
11341 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11345 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11346 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11347 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11349 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11350 dumpMove( tgtNode );
11352 // shrink EDGE sub-meshes and set proxy sub-meshes
11353 UVPtStructVec uvPtVec;
11354 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11355 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11357 _Shrinker1D* shr = (*shrIt);
11358 shr->Compute( /*set3D=*/true, helper );
11360 // set proxy mesh of EDGEs w/o layers
11361 map< double, const SMDS_MeshNode* > nodes;
11362 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11363 // remove refinement nodes
11364 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11365 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11366 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11367 if ( u2n->second == sn0 || u2n->second == sn1 )
11369 while ( u2n->second != tn0 && u2n->second != tn1 )
11371 nodes.erase( nodes.begin(), u2n );
11373 u2n = --nodes.end();
11374 if ( u2n->second == sn0 || u2n->second == sn1 )
11376 while ( u2n->second != tn0 && u2n->second != tn1 )
11378 nodes.erase( ++u2n, nodes.end() );
11380 // set proxy sub-mesh
11381 uvPtVec.resize( nodes.size() );
11382 u2n = nodes.begin();
11383 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11384 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11386 uvPtVec[ i ].node = u2n->second;
11387 uvPtVec[ i ].param = u2n->first;
11388 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11390 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11391 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11394 // set proxy mesh of EDGEs with layers
11395 vector< _LayerEdge* > edges;
11396 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11398 _EdgesOnShape& eos = * subEOS[ iS ];
11399 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11401 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11402 data.SortOnEdge( E, eos._edges );
11405 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11406 if ( !eov->_edges.empty() )
11407 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11409 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11411 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11412 if ( !eov->_edges.empty() )
11413 edges.push_back( eov->_edges[0] ); // on last VERTEX
11415 uvPtVec.resize( edges.size() );
11416 for ( size_t i = 0; i < edges.size(); ++i )
11418 uvPtVec[ i ].node = edges[i]->_nodes.back();
11419 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11420 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11422 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11423 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11424 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11426 // temporary clear the FACE sub-mesh from faces made by refine()
11427 vector< const SMDS_MeshElement* > elems;
11428 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11429 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11430 elems.push_back( ite->next() );
11431 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11432 elems.push_back( ite->next() );
11435 // compute the mesh on the FACE
11436 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11437 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11439 // re-fill proxy sub-meshes of the FACE
11440 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11441 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11442 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11443 psm->AddElement( ite->next() );
11446 for ( size_t i = 0; i < elems.size(); ++i )
11447 smDS->AddElement( elems[i] );
11449 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11450 return error( errMsg );
11452 } // end of re-meshing in case of failed smoothing
11453 else if ( !movedByPeriod )
11455 // No wrongly shaped faces remain; final smooth. Set node XYZ.
11456 bool isStructuredFixed = false;
11457 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11458 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11459 if ( !isStructuredFixed )
11461 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11462 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11464 for ( int st = 3; st; --st )
11467 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11468 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11469 case 3: smoothType = _SmoothNode::ANGULAR; break;
11471 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11472 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11474 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11475 smoothType,/*set3D=*/st==1 );
11480 if ( !getMeshDS()->IsEmbeddedMode() )
11481 // Log node movement
11482 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11484 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11485 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11489 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11490 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11492 VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11494 } // loop on FACES to shrink mesh on
11497 // Replace source nodes by target nodes in shrunk mesh edges
11499 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11500 for ( ; e2shr != e2shrMap.end(); ++e2shr )
11501 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11506 //================================================================================
11508 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11510 //================================================================================
11512 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
11513 _EdgesOnShape& eos,
11514 SMESH_MesherHelper& helper,
11515 const SMESHDS_SubMesh* faceSubMesh)
11517 const SMDS_MeshNode* srcNode = edge._nodes[0];
11518 const SMDS_MeshNode* tgtNode = edge._nodes.back();
11520 if ( eos.SWOLType() == TopAbs_FACE )
11522 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11525 edge.Set( _LayerEdge::SHRUNK );
11526 return srcNode == tgtNode;
11528 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
11529 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11530 gp_Vec2d uvDir( srcUV, tgtUV );
11531 double uvLen = uvDir.Magnitude();
11533 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11536 //edge._pos.resize(1);
11537 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11539 // set UV of source node to target node
11540 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11541 pos->SetUParameter( srcUV.X() );
11542 pos->SetVParameter( srcUV.Y() );
11544 else // _sWOL is TopAbs_EDGE
11546 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11549 edge.Set( _LayerEdge::SHRUNK );
11550 return srcNode == tgtNode;
11552 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11553 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11554 if ( !edgeSM || edgeSM->NbElements() == 0 )
11555 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11557 const SMDS_MeshNode* n2 = 0;
11558 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11559 while ( eIt->more() && !n2 )
11561 const SMDS_MeshElement* e = eIt->next();
11562 if ( !edgeSM->Contains(e)) continue;
11563 n2 = e->GetNode( 0 );
11564 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11567 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11569 if ( n2 == tgtNode ) // for 3D_mesh_GHS3D_01/B1
11571 // shrunk by other SOLID
11572 edge.Set( _LayerEdge::SHRUNK ); // ???
11576 double uSrc = helper.GetNodeU( E, srcNode, n2 );
11577 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11578 double u2 = helper.GetNodeU( E, n2, srcNode );
11580 //edge._pos.clear();
11582 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11584 // tgtNode is located so that it does not make faces with wrong orientation
11585 edge.Set( _LayerEdge::SHRUNK );
11588 //edge._pos.resize(1);
11589 edge._pos[0].SetCoord( U_TGT, uTgt );
11590 edge._pos[0].SetCoord( U_SRC, uSrc );
11591 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11593 edge._simplices.resize( 1 );
11594 edge._simplices[0]._nPrev = n2;
11596 // set U of source node to the target node
11597 SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11598 pos->SetUParameter( uSrc );
11603 //================================================================================
11605 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
11607 //================================================================================
11609 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
11611 if ( edge._nodes.size() == 1 )
11616 const SMDS_MeshNode* srcNode = edge._nodes[0];
11617 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
11618 if ( S.IsNull() ) return;
11622 switch ( S.ShapeType() )
11627 TopLoc_Location loc;
11628 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
11629 if ( curve.IsNull() ) return;
11630 SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
11631 p = curve->Value( ePos->GetUParameter() );
11634 case TopAbs_VERTEX:
11636 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
11641 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
11642 dumpMove( srcNode );
11646 //================================================================================
11648 * \brief Try to fix triangles with high aspect ratio by swapping diagonals
11650 //================================================================================
11652 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
11653 SMESH_MesherHelper& helper,
11656 set<const SMDS_MeshNode*> * involvedNodes)
11658 SMESH::Controls::AspectRatio qualifier;
11659 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11660 const double maxAspectRatio = is2D ? 4. : 2;
11661 _NodeCoordHelper xyz( F, helper, is2D );
11663 // find bad triangles
11665 vector< const SMDS_MeshElement* > badTrias;
11666 vector< double > badAspects;
11667 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
11668 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11669 while ( fIt->more() )
11671 const SMDS_MeshElement * f = fIt->next();
11672 if ( f->NbCornerNodes() != 3 ) continue;
11673 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11674 double aspect = qualifier.GetValue( points );
11675 if ( aspect > maxAspectRatio )
11677 badTrias.push_back( f );
11678 badAspects.push_back( aspect );
11683 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11684 SMDS_ElemIteratorPtr fIt = sm->GetElements();
11685 while ( fIt->more() )
11687 const SMDS_MeshElement * f = fIt->next();
11688 if ( f->NbCornerNodes() == 3 )
11689 dumpChangeNodes( f );
11693 if ( badTrias.empty() )
11696 // find couples of faces to swap diagonal
11698 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11699 vector< T2Trias > triaCouples;
11701 TIDSortedElemSet involvedFaces, emptySet;
11702 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11705 double aspRatio [3];
11708 if ( !involvedFaces.insert( badTrias[iTia] ).second )
11710 for ( int iP = 0; iP < 3; ++iP )
11711 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11713 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11714 int bestCouple = -1;
11715 for ( int iSide = 0; iSide < 3; ++iSide )
11717 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11718 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11719 trias [iSide].first = badTrias[iTia];
11720 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11722 if (( ! trias[iSide].second ) ||
11723 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11724 ( ! sm->Contains( trias[iSide].second )))
11727 // aspect ratio of an adjacent tria
11728 for ( int iP = 0; iP < 3; ++iP )
11729 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11730 double aspectInit = qualifier.GetValue( points2 );
11732 // arrange nodes as after diag-swaping
11733 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11734 i3 = helper.WrapIndex( i1-1, 3 );
11736 i3 = helper.WrapIndex( i1+1, 3 );
11738 points1( 1+ iSide ) = points2( 1+ i3 );
11739 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
11741 // aspect ratio after diag-swaping
11742 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11743 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11746 // prevent inversion of a triangle
11747 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11748 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11749 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11752 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11753 bestCouple = iSide;
11756 if ( bestCouple >= 0 )
11758 triaCouples.push_back( trias[bestCouple] );
11759 involvedFaces.insert ( trias[bestCouple].second );
11763 involvedFaces.erase( badTrias[iTia] );
11766 if ( triaCouples.empty() )
11771 SMESH_MeshEditor editor( helper.GetMesh() );
11772 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11773 for ( size_t i = 0; i < triaCouples.size(); ++i )
11775 dumpChangeNodes( triaCouples[i].first );
11776 dumpChangeNodes( triaCouples[i].second );
11777 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11780 if ( involvedNodes )
11781 for ( size_t i = 0; i < triaCouples.size(); ++i )
11783 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11784 triaCouples[i].first->end_nodes() );
11785 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11786 triaCouples[i].second->end_nodes() );
11789 // just for debug dump resulting triangles
11790 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11791 for ( size_t i = 0; i < triaCouples.size(); ++i )
11793 dumpChangeNodes( triaCouples[i].first );
11794 dumpChangeNodes( triaCouples[i].second );
11798 //================================================================================
11800 * \brief Move target node to it's final position on the FACE during shrinking
11802 //================================================================================
11804 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11805 const TopoDS_Face& F,
11806 _EdgesOnShape& eos,
11807 SMESH_MesherHelper& helper )
11810 return false; // already at the target position
11812 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11814 if ( eos.SWOLType() == TopAbs_FACE )
11816 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
11817 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11818 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11819 const double uvLen = tgtUV.Distance( curUV );
11820 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11822 // Select shrinking step such that not to make faces with wrong orientation.
11823 double stepSize = 1e100;
11824 for ( size_t i = 0; i < _simplices.size(); ++i )
11826 if ( !_simplices[i]._nPrev->isMarked() ||
11827 !_simplices[i]._nNext->isMarked() )
11828 continue; // simplex of quadrangle created by addBoundaryElements()
11830 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11831 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11832 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11833 gp_XY dirN = uvN2 - uvN1;
11834 double det = uvDir.Crossed( dirN );
11835 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
11836 gp_XY dirN2Cur = curUV - uvN1;
11837 double step = dirN.Crossed( dirN2Cur ) / det;
11839 stepSize = Min( step, stepSize );
11842 if ( uvLen <= stepSize )
11848 else if ( stepSize > 0 )
11850 newUV = curUV + uvDir.XY() * stepSize * kSafe;
11856 SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11857 pos->SetUParameter( newUV.X() );
11858 pos->SetVParameter( newUV.Y() );
11861 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11862 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11863 dumpMove( tgtNode );
11866 else // _sWOL is TopAbs_EDGE
11868 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
11869 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
11870 SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11872 const double u2 = helper.GetNodeU( E, n2, tgtNode );
11873 const double uSrc = _pos[0].Coord( U_SRC );
11874 const double lenTgt = _pos[0].Coord( LEN_TGT );
11876 double newU = _pos[0].Coord( U_TGT );
11877 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11879 Set( _LayerEdge::SHRUNK );
11884 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11886 tgtPos->SetUParameter( newU );
11888 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11889 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11890 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11891 dumpMove( tgtNode );
11898 //================================================================================
11900 * \brief Perform smooth on the FACE
11901 * \retval bool - true if the node has been moved
11903 //================================================================================
11905 bool _SmoothNode::Smooth(int& nbBad,
11906 Handle(Geom_Surface)& surface,
11907 SMESH_MesherHelper& helper,
11908 const double refSign,
11912 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11914 // get uv of surrounding nodes
11915 vector<gp_XY> uv( _simplices.size() );
11916 for ( size_t i = 0; i < _simplices.size(); ++i )
11917 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11919 // compute new UV for the node
11920 gp_XY newPos (0,0);
11921 if ( how == TFI && _simplices.size() == 4 )
11924 for ( size_t i = 0; i < _simplices.size(); ++i )
11925 if ( _simplices[i]._nOpp )
11926 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11928 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11930 newPos = helper.calcTFI ( 0.5, 0.5,
11931 corners[0], corners[1], corners[2], corners[3],
11932 uv[1], uv[2], uv[3], uv[0] );
11934 else if ( how == ANGULAR )
11936 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11938 else if ( how == CENTROIDAL && _simplices.size() > 3 )
11940 // average centers of diagonals wieghted with their reciprocal lengths
11941 if ( _simplices.size() == 4 )
11943 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11944 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11945 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11949 double sumWeight = 0;
11950 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11951 for ( int i = 0; i < nb; ++i )
11954 int iTo = i + _simplices.size() - 1;
11955 for ( int j = iFrom; j < iTo; ++j )
11957 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11958 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11960 newPos += w * ( uv[i]+uv[i2] );
11963 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11968 // Laplacian smooth
11969 for ( size_t i = 0; i < _simplices.size(); ++i )
11971 newPos /= _simplices.size();
11974 // count quality metrics (orientation) of triangles around the node
11975 int nbOkBefore = 0;
11976 gp_XY tgtUV = helper.GetNodeUV( face, _node );
11977 for ( size_t i = 0; i < _simplices.size(); ++i )
11978 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11981 for ( size_t i = 0; i < _simplices.size(); ++i )
11982 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11984 if ( nbOkAfter < nbOkBefore )
11986 nbBad += _simplices.size() - nbOkBefore;
11990 SMDS_FacePositionPtr pos = _node->GetPosition();
11991 pos->SetUParameter( newPos.X() );
11992 pos->SetVParameter( newPos.Y() );
11999 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
12000 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
12004 nbBad += _simplices.size() - nbOkAfter;
12005 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
12008 //================================================================================
12010 * \brief Computes new UV using angle based smoothing technique
12012 //================================================================================
12014 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12015 const gp_XY& uvToFix,
12016 const double refSign)
12018 uv.push_back( uv.front() );
12020 vector< gp_XY > edgeDir ( uv.size() );
12021 vector< double > edgeSize( uv.size() );
12022 for ( size_t i = 1; i < edgeDir.size(); ++i )
12024 edgeDir [i-1] = uv[i] - uv[i-1];
12025 edgeSize[i-1] = edgeDir[i-1].Modulus();
12026 if ( edgeSize[i-1] < numeric_limits<double>::min() )
12027 edgeDir[i-1].SetX( 100 );
12029 edgeDir[i-1] /= edgeSize[i-1] * refSign;
12031 edgeDir.back() = edgeDir.front();
12032 edgeSize.back() = edgeSize.front();
12036 double sumSize = 0;
12037 for ( size_t i = 1; i < edgeDir.size(); ++i )
12039 if ( edgeDir[i-1].X() > 1. ) continue;
12041 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12042 if ( i == edgeDir.size() ) break;
12044 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12045 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
12046 gp_XY bisec = norm1 + norm2;
12047 double bisecSize = bisec.Modulus();
12048 if ( bisecSize < numeric_limits<double>::min() )
12050 bisec = -edgeDir[i1] + edgeDir[i];
12051 bisecSize = bisec.Modulus();
12053 bisec /= bisecSize;
12055 gp_XY dirToN = uvToFix - p;
12056 double distToN = dirToN.Modulus();
12057 if ( bisec * dirToN < 0 )
12058 distToN = -distToN;
12060 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
12062 sumSize += edgeSize[i1] + edgeSize[i];
12064 newPos /= /*nbEdges * */sumSize;
12068 //================================================================================
12070 * \brief Keep a _LayerEdge inflated along the EDGE
12072 //================================================================================
12074 void _Shrinker1D::AddEdge( const _LayerEdge* e,
12075 _EdgesOnShape& eos,
12076 SMESH_MesherHelper& helper )
12079 if ( _nodes.empty() )
12081 _edges[0] = _edges[1] = 0;
12084 // check _LayerEdge
12085 if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12087 if ( eos.SWOLType() != TopAbs_EDGE )
12088 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12089 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12090 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12092 // store _LayerEdge
12093 _geomEdge = TopoDS::Edge( eos._sWOL );
12095 BRep_Tool::Range( _geomEdge, f,l );
12096 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12097 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12101 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12102 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12104 if ( _nodes.empty() )
12106 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12107 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12109 TopLoc_Location loc;
12110 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12111 GeomAdaptor_Curve aCurve(C, f,l);
12112 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12114 int nbExpectNodes = eSubMesh->NbNodes();
12115 _initU .reserve( nbExpectNodes );
12116 _normPar.reserve( nbExpectNodes );
12117 _nodes .reserve( nbExpectNodes );
12118 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12119 while ( nIt->more() )
12121 const SMDS_MeshNode* node = nIt->next();
12123 // skip refinement nodes
12124 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12125 node == tgtNode0 || node == tgtNode1 )
12127 bool hasMarkedFace = false;
12128 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12129 while ( fIt->more() && !hasMarkedFace )
12130 hasMarkedFace = fIt->next()->isMarked();
12131 if ( !hasMarkedFace )
12134 _nodes.push_back( node );
12135 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12136 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12137 _normPar.push_back( len / totLen );
12142 // remove target node of the _LayerEdge from _nodes
12143 size_t nbFound = 0;
12144 for ( size_t i = 0; i < _nodes.size(); ++i )
12145 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12146 _nodes[i] = 0, nbFound++;
12147 if ( nbFound == _nodes.size() )
12152 //================================================================================
12154 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12156 //================================================================================
12158 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12160 if ( _done || _nodes.empty())
12162 const _LayerEdge* e = _edges[0];
12163 if ( !e ) e = _edges[1];
12166 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12167 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12170 if ( set3D || _done )
12172 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12173 GeomAdaptor_Curve aCurve(C, f,l);
12176 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12178 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12179 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12181 for ( size_t i = 0; i < _nodes.size(); ++i )
12183 if ( !_nodes[i] ) continue;
12184 double len = totLen * _normPar[i];
12185 GCPnts_AbscissaPoint discret( aCurve, len, f );
12186 if ( !discret.IsDone() )
12187 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12188 double u = discret.Parameter();
12189 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12190 pos->SetUParameter( u );
12191 gp_Pnt p = C->Value( u );
12192 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12197 BRep_Tool::Range( _geomEdge, f,l );
12199 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12201 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12203 for ( size_t i = 0; i < _nodes.size(); ++i )
12205 if ( !_nodes[i] ) continue;
12206 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12207 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12208 pos->SetUParameter( u );
12213 //================================================================================
12215 * \brief Restore initial parameters of nodes on EDGE
12217 //================================================================================
12219 void _Shrinker1D::RestoreParams()
12222 for ( size_t i = 0; i < _nodes.size(); ++i )
12224 if ( !_nodes[i] ) continue;
12225 SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12226 pos->SetUParameter( _initU[i] );
12231 //================================================================================
12233 * \brief Replace source nodes by target nodes in shrunk mesh edges
12235 //================================================================================
12237 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12239 const SMDS_MeshNode* nodes[3];
12240 for ( int i = 0; i < 2; ++i )
12242 if ( !_edges[i] ) continue;
12244 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12245 if ( !eSubMesh ) return;
12246 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12247 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12248 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12249 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12250 while ( eIt->more() )
12252 const SMDS_MeshElement* e = eIt->next();
12253 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12255 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12256 for ( int iN = 0; iN < e->NbNodes(); ++iN )
12258 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12259 nodes[iN] = ( n == srcNode ? tgtNode : n );
12261 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12266 //================================================================================
12268 * \brief Creates 2D and 1D elements on boundaries of new prisms
12270 //================================================================================
12272 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12274 SMESH_MesherHelper helper( *_mesh );
12276 vector< const SMDS_MeshNode* > faceNodes;
12278 //for ( size_t i = 0; i < _sdVec.size(); ++i )
12280 //_SolidData& data = _sdVec[i];
12281 TopTools_IndexedMapOfShape geomEdges;
12282 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12283 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12285 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12286 const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12287 if ( data._noShrinkShapes.count( edgeID ))
12290 // Get _LayerEdge's based on E
12292 map< double, const SMDS_MeshNode* > u2nodes;
12293 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12296 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12297 TNode2Edge & n2eMap = data._n2eMap;
12298 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12300 //check if 2D elements are needed on E
12301 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12302 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12303 ledges.push_back( n2e->second );
12305 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12306 continue; // no layers on E
12307 ledges.push_back( n2eMap[ u2n->second ]);
12309 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12310 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12311 int nbSharedPyram = 0;
12312 SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12313 while ( vIt->more() )
12315 const SMDS_MeshElement* v = vIt->next();
12316 nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12318 if ( nbSharedPyram > 1 )
12319 continue; // not free border of the pyramid
12322 faceNodes.push_back( ledges[0]->_nodes[0] );
12323 faceNodes.push_back( ledges[1]->_nodes[0] );
12324 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12325 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12327 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12328 continue; // faces already created
12330 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12331 ledges.push_back( n2eMap[ u2n->second ]);
12333 // Find out orientation and type of face to create
12335 bool reverse = false, isOnFace;
12338 map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12339 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12341 F = e2f->second.Oriented( TopAbs_FORWARD );
12342 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12343 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12344 reverse = !reverse, F.Reverse();
12345 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12346 reverse = !reverse;
12348 else if ( !data._ignoreFaceIds.count( e2f->first ))
12350 // find FACE with layers sharing E
12351 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12353 F = *( fIt->next() );
12355 // Find the sub-mesh to add new faces
12356 SMESHDS_SubMesh* sm = 0;
12358 sm = getMeshDS()->MeshElements( F );
12360 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12362 return error("error in addBoundaryElements()", data._index);
12364 // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12365 // faces for 3D meshing (PAL23414)
12366 SMESHDS_SubMesh* adjSM = 0;
12369 const TGeomID faceID = sm->GetID();
12370 PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12371 while ( const TopoDS_Shape* solid = soIt->next() )
12372 if ( !solid->IsSame( data._solid ))
12374 size_t iData = _solids.FindIndex( *solid ) - 1;
12375 if ( iData < _sdVec.size() &&
12376 _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12377 _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12379 SMESH_ProxyMesh::SubMesh* proxySub =
12380 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12381 if ( proxySub && proxySub->NbElements() > 0 )
12388 const int dj1 = reverse ? 0 : 1;
12389 const int dj2 = reverse ? 1 : 0;
12390 vector< const SMDS_MeshElement*> ff; // new faces row
12391 SMESHDS_Mesh* m = getMeshDS();
12392 for ( size_t j = 1; j < ledges.size(); ++j )
12394 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
12395 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
12396 ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12397 if ( nn1.size() == nn2.size() )
12400 for ( size_t z = 1; z < nn1.size(); ++z )
12401 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12403 for ( size_t z = 1; z < nn1.size(); ++z )
12404 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12406 else if ( nn1.size() == 1 )
12409 for ( size_t z = 1; z < nn2.size(); ++z )
12410 sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12412 for ( size_t z = 1; z < nn2.size(); ++z )
12413 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12418 for ( size_t z = 1; z < nn1.size(); ++z )
12419 sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12421 for ( size_t z = 1; z < nn1.size(); ++z )
12422 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12425 if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12427 for ( size_t z = 0; z < ff.size(); ++z )
12429 adjSM->AddElement( ff[ z ]);
12435 for ( int isFirst = 0; isFirst < 2; ++isFirst )
12437 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12438 _EdgesOnShape* eos = data.GetShapeEdges( edge );
12439 if ( eos && eos->SWOLType() == TopAbs_EDGE )
12441 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
12442 if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12444 helper.SetSubShape( eos->_sWOL );
12445 helper.SetElementsOnShape( true );
12446 for ( size_t z = 1; z < nn.size(); ++z )
12447 helper.AddEdge( nn[z-1], nn[z] );
12451 } // loop on EDGE's
12452 } // loop on _SolidData's