1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B2d.hxx>
50 #include <Bnd_B3d.hxx>
52 #include <GCPnts_AbscissaPoint.hxx>
53 #include <Geom2d_Circle.hxx>
54 #include <Geom2d_Line.hxx>
55 #include <Geom2d_TrimmedCurve.hxx>
56 #include <GeomAdaptor_Curve.hxx>
57 #include <GeomLib.hxx>
58 #include <Geom_Circle.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Line.hxx>
61 #include <Geom_TrimmedCurve.hxx>
62 #include <Precision.hxx>
63 #include <Standard_ErrorHandler.hxx>
64 #include <TColStd_Array1OfReal.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_IndexedMapOfShape.hxx>
68 #include <TopTools_ListOfShape.hxx>
69 #include <TopTools_MapOfShape.hxx>
71 #include <TopoDS_Edge.hxx>
72 #include <TopoDS_Face.hxx>
73 #include <TopoDS_Vertex.hxx>
87 //================================================================================
92 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
95 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
96 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
98 struct _MeshOfSolid : public SMESH_ProxyMesh,
99 public SMESH_subMeshEventListenerData
101 bool _n2nMapComputed;
103 _MeshOfSolid( SMESH_Mesh* mesh)
104 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
106 SMESH_ProxyMesh::setMesh( *mesh );
109 // returns submesh for a geom face
110 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
112 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
113 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
115 void setNode2Node(const SMDS_MeshNode* srcNode,
116 const SMDS_MeshNode* proxyNode,
117 const SMESH_ProxyMesh::SubMesh* subMesh)
119 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
122 //--------------------------------------------------------------------------------
124 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
125 * It is used to clear an inferior dim sub-meshes modified by viscous layers
127 class _ShrinkShapeListener : SMESH_subMeshEventListener
129 _ShrinkShapeListener()
130 : SMESH_subMeshEventListener(/*isDeletable=*/false,
131 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
133 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
134 virtual void ProcessEvent(const int event,
136 SMESH_subMesh* solidSM,
137 SMESH_subMeshEventListenerData* data,
138 const SMESH_Hypothesis* hyp)
140 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
142 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
146 //--------------------------------------------------------------------------------
148 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
149 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
150 * delete the data as soon as it has been used
152 class _ViscousListener : SMESH_subMeshEventListener
155 SMESH_subMeshEventListener(/*isDeletable=*/false,
156 "StdMeshers_ViscousLayers::_ViscousListener") {}
157 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
159 virtual void ProcessEvent(const int event,
161 SMESH_subMesh* subMesh,
162 SMESH_subMeshEventListenerData* data,
163 const SMESH_Hypothesis* hyp)
165 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
167 // delete SMESH_ProxyMesh containing temporary faces
168 subMesh->DeleteEventListener( this );
171 // Finds or creates proxy mesh of the solid
172 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
173 const TopoDS_Shape& solid,
176 if ( !mesh ) return 0;
177 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
178 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
179 if ( !data && toCreate )
181 data = new _MeshOfSolid(mesh);
182 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
183 sm->SetEventListener( Get(), data, sm );
187 // Removes proxy mesh of the solid
188 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
190 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
194 //================================================================================
196 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
197 * the main shape when sub-mesh of the main shape is cleared,
198 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
201 //================================================================================
203 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
205 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
206 SMESH_subMeshEventListenerData* data =
207 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
210 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
211 data->mySubMeshes.end())
212 data->mySubMeshes.push_back( sub );
216 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
217 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
220 //--------------------------------------------------------------------------------
222 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
223 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
224 * The class is used to check validity of face or volumes around a smoothed node;
225 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
229 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
230 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
231 _Simplex(const SMDS_MeshNode* nPrev=0,
232 const SMDS_MeshNode* nNext=0,
233 const SMDS_MeshNode* nOpp=0)
234 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
235 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
237 const double M[3][3] =
238 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
239 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
240 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
241 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
242 + M[0][1]*M[1][2]*M[2][0]
243 + M[0][2]*M[1][0]*M[2][1]
244 - M[0][0]*M[1][2]*M[2][1]
245 - M[0][1]*M[1][0]*M[2][2]
246 - M[0][2]*M[1][1]*M[2][0]);
247 return determinant > 1e-100;
249 bool IsForward(const gp_XY& tgtUV,
250 const SMDS_MeshNode* smoothedNode,
251 const TopoDS_Face& face,
252 SMESH_MesherHelper& helper,
253 const double refSign) const
255 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
256 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
257 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
259 return d*refSign > 1e-100;
261 bool IsNeighbour(const _Simplex& other) const
263 return _nPrev == other._nNext || _nNext == other._nPrev;
266 //--------------------------------------------------------------------------------
268 * Structure used to take into account surface curvature while smoothing
273 double _k; // factor to correct node smoothed position
274 double _h2lenRatio; // avgNormProj / (2*avgDist)
276 static _Curvature* New( double avgNormProj, double avgDist )
279 if ( fabs( avgNormProj / avgDist ) > 1./200 )
282 c->_r = avgDist * avgDist / avgNormProj;
283 c->_k = avgDist * avgDist / c->_r / c->_r;
284 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
285 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
289 double lenDelta(double len) const { return _k * ( _r + len ); }
290 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
293 //--------------------------------------------------------------------------------
295 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
299 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
300 const SMDS_MeshNode* _nodes[2];
301 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
303 double _wgt[2]; // weights of _nodes
304 _LayerEdge* _edges[2];
306 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
309 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
311 std::swap( _nodes[0], _nodes[1] );
312 std::swap( _wgt[0], _wgt[1] );
315 //--------------------------------------------------------------------------------
317 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
318 * and a node of the most internal layer (_nodes.back())
322 vector< const SMDS_MeshNode*> _nodes;
324 gp_XYZ _normal; // to solid surface
325 vector<gp_XYZ> _pos; // points computed during inflation
326 double _len; // length achived with the last step
327 double _cosin; // of angle (_normal ^ surface)
328 double _lenFactor; // to compute _len taking _cosin into account
330 // face or edge w/o layer along or near which _LayerEdge is inflated
332 // simplices connected to the source node (_nodes[0]);
333 // used for smoothing and quality check of _LayerEdge's based on the FACE
334 vector<_Simplex> _simplices;
335 // data for smoothing of _LayerEdge's based on the EDGE
336 _2NearEdges* _2neibors;
338 _Curvature* _curvature;
339 // TODO:: detele _Curvature, _plnNorm
341 void SetNewLength( double len, SMESH_MesherHelper& helper );
342 bool SetNewLength2d( Handle(Geom_Surface)& surface,
343 const TopoDS_Face& F,
344 SMESH_MesherHelper& helper );
345 void SetDataByNeighbors( const SMDS_MeshNode* n1,
346 const SMDS_MeshNode* n2,
347 SMESH_MesherHelper& helper);
348 void InvalidateStep( int curStep );
349 bool Smooth(int& badNb);
350 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
351 const TopoDS_Face& F,
352 SMESH_MesherHelper& helper);
353 bool FindIntersection( SMESH_ElementSearcher& searcher,
355 const double& epsilon,
356 const SMDS_MeshElement** face = 0);
357 bool SegTriaInter( const gp_Ax1& lastSegment,
358 const SMDS_MeshNode* n0,
359 const SMDS_MeshNode* n1,
360 const SMDS_MeshNode* n2,
362 const double& epsilon) const;
363 gp_Ax1 LastSegment(double& segLen) const;
364 bool IsOnEdge() const { return _2neibors; }
365 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
366 void SetCosin( double cosin );
370 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
372 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
373 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
376 //--------------------------------------------------------------------------------
378 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
380 //--------------------------------------------------------------------------------
382 * \brief Data of a SOLID
387 const StdMeshers_ViscousLayers* _hyp;
388 TopoDS_Shape _hypShape;
389 _MeshOfSolid* _proxyMesh;
390 set<TGeomID> _reversedFaceIds;
391 set<TGeomID> _ignoreFaceIds;
393 double _stepSize, _stepSizeCoeff;
394 const SMDS_MeshNode* _stepSizeNodes[2];
397 // edges of _n2eMap. We keep same data in two containers because
398 // iteration over the map is 5 time longer than over the vector
399 vector< _LayerEdge* > _edges;
401 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
402 // layers and a FACE w/o layers
403 // value: the shape (FACE or EDGE) to shrink mesh on.
404 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
405 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
407 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
408 set< TGeomID > _noShrinkFaces;
410 // <EDGE to smooth on> to <it's curve>
411 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
413 // end indices in _edges of _LayerEdge on one shape to smooth
414 vector< int > _endEdgeToSmooth;
416 double _epsilon; // precision for SegTriaInter()
418 int _index; // for debug
420 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
421 const StdMeshers_ViscousLayers* h=0,
422 const TopoDS_Shape& hs=TopoDS_Shape(),
424 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
427 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
430 Handle(Geom_Surface)& surface,
431 const TopoDS_Face& F,
432 SMESH_MesherHelper& helper);
434 //--------------------------------------------------------------------------------
436 * \brief Data of node on a shrinked FACE
440 const SMDS_MeshNode* _node;
441 //vector<const SMDS_MeshNode*> _nodesAround;
442 vector<_Simplex> _simplices; // for quality check
444 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
446 bool Smooth(int& badNb,
447 Handle(Geom_Surface)& surface,
448 SMESH_MesherHelper& helper,
449 const double refSign,
453 gp_XY computeAngularPos(vector<gp_XY>& uv,
454 const gp_XY& uvToFix,
455 const double refSign );
457 //--------------------------------------------------------------------------------
459 * \brief Builder of viscous layers
461 class _ViscousBuilder
466 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
467 const TopoDS_Shape& shape);
469 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
470 void RestoreListeners();
472 // computes SMESH_ProxyMesh::SubMesh::_n2n;
473 bool MakeN2NMap( _MeshOfSolid* pm );
477 bool findSolidsWithLayers();
478 bool findFacesWithLayers();
479 bool makeLayer(_SolidData& data);
480 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
481 SMESH_MesherHelper& helper, _SolidData& data);
482 bool findNeiborsOnEdge(const _LayerEdge* edge,
483 const SMDS_MeshNode*& n1,
484 const SMDS_MeshNode*& n2,
486 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
487 const set<TGeomID>& ingnoreShapes,
488 const _SolidData* dataToCheckOri = 0,
489 const bool toSort = false);
490 bool sortEdges( _SolidData& data,
491 vector< vector<_LayerEdge*> >& edgesByGeom);
492 void limitStepSize( _SolidData& data,
493 const SMDS_MeshElement* face,
495 void limitStepSize( _SolidData& data, const double minSize);
496 bool inflate(_SolidData& data);
497 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
498 bool smoothAnalyticEdge( _SolidData& data,
501 Handle(Geom_Surface)& surface,
502 const TopoDS_Face& F,
503 SMESH_MesherHelper& helper);
504 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
505 bool refine(_SolidData& data);
507 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
508 SMESH_MesherHelper& helper,
509 const SMESHDS_SubMesh* faceSubMesh );
510 void fixBadFaces(const TopoDS_Face& F,
511 SMESH_MesherHelper& helper,
514 set<const SMDS_MeshNode*> * involvedNodes=NULL);
515 bool addBoundaryElements();
517 bool error( const string& text, int solidID=-1 );
518 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
521 void makeGroupOfLE();
524 SMESH_ComputeErrorPtr _error;
526 vector< _SolidData > _sdVec;
529 //--------------------------------------------------------------------------------
531 * \brief Shrinker of nodes on the EDGE
535 vector<double> _initU;
536 vector<double> _normPar;
537 vector<const SMDS_MeshNode*> _nodes;
538 const _LayerEdge* _edges[2];
541 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
542 void Compute(bool set3D, SMESH_MesherHelper& helper);
543 void RestoreParams();
544 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
546 //--------------------------------------------------------------------------------
548 * \brief Class of temporary mesh face.
549 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
550 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
552 struct TmpMeshFace : public SMDS_MeshElement
554 vector<const SMDS_MeshNode* > _nn;
555 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
556 SMDS_MeshElement(id), _nn(nodes) {}
557 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
558 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
559 virtual vtkIdType GetVtkType() const { return -1; }
560 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
561 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
562 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
563 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
565 //--------------------------------------------------------------------------------
567 * \brief Class of temporary mesh face storing _LayerEdge it's based on
569 struct TmpMeshFaceOnEdge : public TmpMeshFace
571 _LayerEdge *_le1, *_le2;
572 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
573 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
575 _nn[0]=_le1->_nodes[0];
576 _nn[1]=_le1->_nodes.back();
577 _nn[2]=_le2->_nodes.back();
578 _nn[3]=_le2->_nodes[0];
581 //--------------------------------------------------------------------------------
583 * \brief Retriever of node coordinates either directly of from a surface by node UV.
584 * \warning Location of a surface is ignored
586 struct NodeCoordHelper
588 SMESH_MesherHelper& _helper;
589 const TopoDS_Face& _face;
590 Handle(Geom_Surface) _surface;
591 gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
593 NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
594 : _helper( helper ), _face( F )
599 _surface = BRep_Tool::Surface( _face, loc );
601 if ( _surface.IsNull() )
602 _fun = & NodeCoordHelper::direct;
604 _fun = & NodeCoordHelper::byUV;
606 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
609 gp_XYZ direct(const SMDS_MeshNode* n) const
611 return SMESH_TNodeXYZ( n );
613 gp_XYZ byUV (const SMDS_MeshNode* n) const
615 gp_XY uv = _helper.GetNodeUV( _face, n );
616 return _surface->Value( uv.X(), uv.Y() ).XYZ();
619 } // namespace VISCOUS_3D
621 //================================================================================
622 // StdMeshers_ViscousLayers hypothesis
624 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
625 :SMESH_Hypothesis(hypId, studyId, gen),
626 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
628 _name = StdMeshers_ViscousLayers::GetHypType();
629 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
630 } // --------------------------------------------------------------------------------
631 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
633 if ( faceIds != _shapeIds )
634 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
635 if ( _isToIgnoreShapes != toIgnore )
636 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
637 } // --------------------------------------------------------------------------------
638 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
640 if ( thickness != _thickness )
641 _thickness = thickness, NotifySubMeshesHypothesisModification();
642 } // --------------------------------------------------------------------------------
643 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
645 if ( _nbLayers != nb )
646 _nbLayers = nb, NotifySubMeshesHypothesisModification();
647 } // --------------------------------------------------------------------------------
648 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
650 if ( _stretchFactor != factor )
651 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
652 } // --------------------------------------------------------------------------------
654 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
655 const TopoDS_Shape& theShape,
656 const bool toMakeN2NMap) const
658 using namespace VISCOUS_3D;
659 _ViscousBuilder bulder;
660 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
661 if ( err && !err->IsOK() )
662 return SMESH_ProxyMesh::Ptr();
664 vector<SMESH_ProxyMesh::Ptr> components;
665 TopExp_Explorer exp( theShape, TopAbs_SOLID );
666 for ( ; exp.More(); exp.Next() )
668 if ( _MeshOfSolid* pm =
669 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
671 if ( toMakeN2NMap && !pm->_n2nMapComputed )
672 if ( !bulder.MakeN2NMap( pm ))
673 return SMESH_ProxyMesh::Ptr();
674 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
675 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
677 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
679 switch ( components.size() )
683 case 1: return components[0];
685 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
687 return SMESH_ProxyMesh::Ptr();
688 } // --------------------------------------------------------------------------------
689 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
691 save << " " << _nbLayers
693 << " " << _stretchFactor
694 << " " << _shapeIds.size();
695 for ( size_t i = 0; i < _shapeIds.size(); ++i )
696 save << " " << _shapeIds[i];
697 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
699 } // --------------------------------------------------------------------------------
700 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
702 int nbFaces, faceID, shapeToTreat;
703 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
704 while ( _shapeIds.size() < nbFaces && load >> faceID )
705 _shapeIds.push_back( faceID );
706 if ( load >> shapeToTreat )
707 _isToIgnoreShapes = !shapeToTreat;
709 _isToIgnoreShapes = true; // old behavior
711 } // --------------------------------------------------------------------------------
712 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
713 const TopoDS_Shape& theShape)
718 // END StdMeshers_ViscousLayers hypothesis
719 //================================================================================
723 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
727 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
728 gp_Pnt p = BRep_Tool::Pnt( fromV );
729 double distF = p.SquareDistance( c->Value( f ));
730 double distL = p.SquareDistance( c->Value( l ));
731 c->D1(( distF < distL ? f : l), p, dir );
732 if ( distL < distF ) dir.Reverse();
735 //--------------------------------------------------------------------------------
736 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
737 SMESH_MesherHelper& helper)
740 double f,l; gp_Pnt p;
741 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
742 double u = helper.GetNodeU( E, atNode );
746 //--------------------------------------------------------------------------------
747 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
748 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
750 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
751 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
752 gp_Pnt p; gp_Vec du, dv, norm;
753 surface->D1( uv.X(),uv.Y(), p, du,dv );
757 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
758 double u = helper.GetNodeU( fromE, node, 0, &ok );
760 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
761 if ( o == TopAbs_REVERSED )
764 gp_Vec dir = norm ^ du;
766 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
767 helper.IsClosedEdge( fromE ))
769 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
770 else c->D1( f, p, dv );
771 if ( o == TopAbs_REVERSED )
773 gp_Vec dir2 = norm ^ dv;
774 dir = dir.Normalized() + dir2.Normalized();
778 //--------------------------------------------------------------------------------
779 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
780 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
781 bool& ok, double* cosin=0)
783 double f,l; TopLoc_Location loc;
784 vector< TopoDS_Edge > edges; // sharing a vertex
785 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
788 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
789 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
790 edges.push_back( *e );
793 if ( !( ok = ( edges.size() > 0 ))) return dir;
794 // get average dir of edges going fromV
796 //if ( edges.size() > 1 )
797 for ( size_t i = 0; i < edges.size(); ++i )
799 edgeDir = getEdgeDir( edges[i], fromV );
800 double size2 = edgeDir.SquareModulus();
801 if ( size2 > numeric_limits<double>::min() )
802 edgeDir /= sqrt( size2 );
807 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
808 if ( edges.size() == 1 )
810 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
811 dir = fromEdgeDir + getFaceDir( F, edges[1], node, helper, ok );
812 else if ( dir * fromEdgeDir < 0 )
816 //dir /= edges.size();
818 double angle = gp_Vec( edgeDir ).Angle( dir );
819 *cosin = cos( angle );
824 //================================================================================
826 * \brief Returns true if a FACE is bound by a concave EDGE
828 //================================================================================
830 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
832 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
836 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
837 for ( ; eExp.More(); eExp.Next() )
839 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
840 if ( SMESH_Algo::isDegenerated( E )) continue;
841 // check if 2D curve is concave
842 BRepAdaptor_Curve2d curve( E, F );
843 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
844 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
845 curve.Intervals( intervals, GeomAbs_C2 );
846 bool isConvex = true;
847 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
849 double u1 = intervals( i );
850 double u2 = intervals( i+1 );
851 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
852 double cross = drv2 ^ drv1;
853 if ( E.Orientation() == TopAbs_REVERSED )
855 isConvex = ( cross > 0.1 ); //-1e-9 );
857 // check if concavity is strong enough to care about it
858 //const double maxAngle = 5 * Standard_PI180;
861 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
863 // map< double, const SMDS_MeshNode* > u2nodes;
864 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
865 // /*ignoreMedium=*/true, u2nodes))
867 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
868 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
869 // double uPrev = u2n->first;
870 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
872 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
873 // gp_Vec2d segmentDir( uvPrev, uv );
874 // curve.D1( uPrev, p, drv1 );
876 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
881 // uPrev = u2n->first;
885 // check angles at VERTEXes
887 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
888 for ( size_t iW = 0; iW < wires.size(); ++iW )
890 const int nbEdges = wires[iW]->NbEdges();
891 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
893 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
895 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
896 int iE2 = ( iE1 + 1 ) % nbEdges;
897 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
898 iE2 = ( iE2 + 1 ) % nbEdges;
899 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
900 wires[iW]->Edge( iE2 ), F );
901 if ( angle < -5. * M_PI / 180. )
907 //--------------------------------------------------------------------------------
908 // DEBUG. Dump intermediate node positions into a python script
913 const char* fname = "/tmp/viscous.py";
914 cout << "execfile('"<<fname<<"')"<<endl;
915 py = new ofstream(fname);
916 *py << "import SMESH" << endl
917 << "from salome.smesh import smeshBuilder" << endl
918 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
919 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
920 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
924 *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
927 ~PyDump() { Finish(); }
929 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
930 #define dumpMove(n) { _dumpMove(n, __LINE__);}
931 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
932 void _dumpFunction(const string& fun, int ln)
933 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
934 void _dumpMove(const SMDS_MeshNode* n, int ln)
935 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
936 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
937 void _dumpCmd(const string& txt, int ln)
938 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
939 void dumpFunctionEnd()
940 { if (py) *py<< " return"<< endl; }
941 void dumpChangeNodes( const SMDS_MeshElement* f )
942 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
943 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
944 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
946 struct PyDump { void Finish() {} };
947 #define dumpFunction(f) f
950 #define dumpFunctionEnd()
951 #define dumpChangeNodes(f)
955 using namespace VISCOUS_3D;
957 //================================================================================
959 * \brief Constructor of _ViscousBuilder
961 //================================================================================
963 _ViscousBuilder::_ViscousBuilder()
965 _error = SMESH_ComputeError::New(COMPERR_OK);
969 //================================================================================
971 * \brief Stores error description and returns false
973 //================================================================================
975 bool _ViscousBuilder::error(const string& text, int solidId )
977 _error->myName = COMPERR_ALGO_FAILED;
978 _error->myComment = string("Viscous layers builder: ") + text;
981 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
982 if ( !sm && !_sdVec.empty() )
983 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
984 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
986 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
987 if ( smError && smError->myAlgo )
988 _error->myAlgo = smError->myAlgo;
992 makeGroupOfLE(); // debug
997 //================================================================================
999 * \brief At study restoration, restore event listeners used to clear an inferior
1000 * dim sub-mesh modified by viscous layers
1002 //================================================================================
1004 void _ViscousBuilder::RestoreListeners()
1009 //================================================================================
1011 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1013 //================================================================================
1015 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1017 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1018 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1019 for ( ; fExp.More(); fExp.Next() )
1021 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1022 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1024 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1026 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1029 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1030 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1032 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1033 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1034 while( prxIt->more() )
1036 const SMDS_MeshElement* fSrc = srcIt->next();
1037 const SMDS_MeshElement* fPrx = prxIt->next();
1038 if ( fSrc->NbNodes() != fPrx->NbNodes())
1039 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1040 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1041 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1044 pm->_n2nMapComputed = true;
1048 //================================================================================
1050 * \brief Does its job
1052 //================================================================================
1054 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1055 const TopoDS_Shape& theShape)
1057 // TODO: set priority of solids during Gen::Compute()
1061 // check if proxy mesh already computed
1062 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1064 return error("No SOLID's in theShape"), _error;
1066 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1067 return SMESH_ComputeErrorPtr(); // everything already computed
1071 // TODO: ignore already computed SOLIDs
1072 if ( !findSolidsWithLayers())
1075 if ( !findFacesWithLayers() )
1078 for ( size_t i = 0; i < _sdVec.size(); ++i )
1080 if ( ! makeLayer(_sdVec[i]) )
1083 if ( _sdVec[i]._edges.size() == 0 )
1086 if ( ! inflate(_sdVec[i]) )
1089 if ( ! refine(_sdVec[i]) )
1095 addBoundaryElements();
1097 makeGroupOfLE(); // debug
1103 //================================================================================
1105 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1107 //================================================================================
1109 bool _ViscousBuilder::findSolidsWithLayers()
1112 TopTools_IndexedMapOfShape allSolids;
1113 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1114 _sdVec.reserve( allSolids.Extent());
1116 SMESH_Gen* gen = _mesh->GetGen();
1117 SMESH_HypoFilter filter;
1118 for ( int i = 1; i <= allSolids.Extent(); ++i )
1120 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1121 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1122 if ( !algo ) continue;
1123 // TODO: check if algo is hidden
1124 const list <const SMESHDS_Hypothesis *> & allHyps =
1125 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1126 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1127 const StdMeshers_ViscousLayers* viscHyp = 0;
1128 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1129 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1132 TopoDS_Shape hypShape;
1133 filter.Init( filter.Is( viscHyp ));
1134 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1136 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1139 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1140 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1143 if ( _sdVec.empty() )
1145 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1150 //================================================================================
1154 //================================================================================
1156 bool _ViscousBuilder::findFacesWithLayers()
1158 SMESH_MesherHelper helper( *_mesh );
1159 TopExp_Explorer exp;
1160 TopTools_IndexedMapOfShape solids;
1162 // collect all faces to ignore defined by hyp
1163 for ( size_t i = 0; i < _sdVec.size(); ++i )
1165 solids.Add( _sdVec[i]._solid );
1167 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1168 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1170 for ( size_t ii = 0; ii < ids.size(); ++ii )
1172 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1173 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1174 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1177 else // FACEs with layers are given
1179 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1180 for ( ; exp.More(); exp.Next() )
1182 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1183 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1184 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1188 // ignore internal FACEs if inlets and outlets are specified
1190 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1191 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1192 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1193 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1195 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1196 for ( ; exp.More(); exp.Next() )
1198 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1199 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1202 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1203 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1205 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1207 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1210 if ( helper.IsReversedSubMesh( face ))
1212 _sdVec[i]._reversedFaceIds.insert( faceInd );
1218 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1219 TopTools_IndexedMapOfShape shapes;
1220 for ( size_t i = 0; i < _sdVec.size(); ++i )
1223 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1224 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1226 const TopoDS_Shape& edge = shapes(iE);
1227 // find 2 faces sharing an edge
1229 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1230 while ( fIt->more())
1232 const TopoDS_Shape* f = fIt->next();
1233 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1234 FF[ int( !FF[0].IsNull()) ] = *f;
1236 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1237 // check presence of layers on them
1239 for ( int j = 0; j < 2; ++j )
1240 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1241 if ( ignore[0] == ignore[1] )
1242 continue; // nothing interesting
1243 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1244 // check presence of layers on fWOL within an adjacent SOLID
1245 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1246 while ( const TopoDS_Shape* solid = sIt->next() )
1247 if ( !solid->IsSame( _sdVec[i]._solid ))
1249 int iSolid = solids.FindIndex( *solid );
1250 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1251 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1253 _sdVec[i]._noShrinkFaces.insert( iFace );
1258 if ( !fWOL.IsNull())
1260 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1261 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1265 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1266 // the algo of the SOLID sharing the FACE does not support it
1267 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1268 for ( size_t i = 0; i < _sdVec.size(); ++i )
1270 TopTools_MapOfShape noShrinkVertices;
1271 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1272 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1274 const TopoDS_Shape& fWOL = e2f->second;
1275 TGeomID edgeID = e2f->first;
1276 bool notShrinkFace = false;
1277 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1278 while ( soIt->more())
1280 const TopoDS_Shape* solid = soIt->next();
1281 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1282 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1283 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1284 notShrinkFace = true;
1285 for ( size_t j = 0; j < _sdVec.size(); ++j )
1287 if ( _sdVec[j]._solid.IsSame( *solid ) )
1288 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1289 notShrinkFace = false;
1292 if ( notShrinkFace )
1294 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1295 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1296 noShrinkVertices.Add( vExp.Current() );
1299 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1300 // to the found not shrinked fWOL's
1301 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1302 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1304 TGeomID edgeID = e2f->first;
1305 TopoDS_Vertex VV[2];
1306 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1307 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1309 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1310 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1319 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1321 for ( size_t i = 0; i < _sdVec.size(); ++i )
1324 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1325 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1327 const TopoDS_Shape& vertex = shapes(iV);
1328 // find faces WOL sharing the vertex
1329 vector< TopoDS_Shape > facesWOL;
1330 int totalNbFaces = 0;
1331 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1332 while ( fIt->more())
1334 const TopoDS_Shape* f = fIt->next();
1335 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1338 const int fID = getMeshDS()->ShapeToIndex( *f );
1339 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1340 !_sdVec[i]._noShrinkFaces.count( fID ))
1341 facesWOL.push_back( *f );
1344 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1345 continue; // no layers at this vertex or no WOL
1346 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1347 switch ( facesWOL.size() )
1351 helper.SetSubShape( facesWOL[0] );
1352 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1354 TopoDS_Shape seamEdge;
1355 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1356 while ( eIt->more() && seamEdge.IsNull() )
1358 const TopoDS_Shape* e = eIt->next();
1359 if ( helper.IsRealSeam( *e ) )
1362 if ( !seamEdge.IsNull() )
1364 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1368 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1373 // find an edge shared by 2 faces
1374 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1375 while ( eIt->more())
1377 const TopoDS_Shape* e = eIt->next();
1378 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1379 helper.IsSubShape( *e, facesWOL[1]))
1381 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1387 return error("Not yet supported case", _sdVec[i]._index);
1395 //================================================================================
1397 * \brief Create the inner surface of the viscous layer and prepare data for infation
1399 //================================================================================
1401 bool _ViscousBuilder::makeLayer(_SolidData& data)
1403 // get all sub-shapes to make layers on
1404 set<TGeomID> subIds, faceIds;
1405 subIds = data._noShrinkFaces;
1406 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1407 for ( ; exp.More(); exp.Next() )
1409 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1410 if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1411 faceIds.insert( fSubM->GetId() );
1412 SMESH_subMeshIteratorPtr subIt =
1413 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1414 while ( subIt->more() )
1415 subIds.insert( subIt->next()->GetId() );
1418 // make a map to find new nodes on sub-shapes shared with other SOLID
1419 map< TGeomID, TNode2Edge* > s2neMap;
1420 map< TGeomID, TNode2Edge* >::iterator s2ne;
1421 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1422 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1424 TGeomID shapeInd = s2s->first;
1425 for ( size_t i = 0; i < _sdVec.size(); ++i )
1427 if ( _sdVec[i]._index == data._index ) continue;
1428 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1429 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1430 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1432 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1438 // Create temporary faces and _LayerEdge's
1440 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1442 data._stepSize = Precision::Infinite();
1443 data._stepSizeNodes[0] = 0;
1445 SMESH_MesherHelper helper( *_mesh );
1446 helper.SetSubShape( data._solid );
1447 helper.SetElementsOnShape(true);
1449 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1450 TNode2Edge::iterator n2e2;
1452 // collect _LayerEdge's of shapes they are based on
1453 const int nbShapes = getMeshDS()->MaxShapeIndex();
1454 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1456 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1458 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1459 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1461 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1462 SMESH_ProxyMesh::SubMesh* proxySub =
1463 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1465 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1466 while ( eIt->more() )
1468 const SMDS_MeshElement* face = eIt->next();
1469 newNodes.resize( face->NbCornerNodes() );
1470 double faceMaxCosin = -1;
1471 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1473 const SMDS_MeshNode* n = face->GetNode(i);
1474 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1475 if ( !(*n2e).second )
1478 _LayerEdge* edge = new _LayerEdge();
1480 edge->_nodes.push_back( n );
1481 const int shapeID = n->getshapeId();
1482 edgesByGeom[ shapeID ].push_back( edge );
1484 // set edge data or find already refined _LayerEdge and get data from it
1485 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1486 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1487 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1489 _LayerEdge* foundEdge = (*n2e2).second;
1490 edge->Copy( *foundEdge, helper );
1491 // location of the last node is modified but we can restore
1492 // it by node position on _sWOL stored by the node
1493 const_cast< SMDS_MeshNode* >
1494 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1498 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1499 if ( !setEdgeData( *edge, subIds, helper, data ))
1502 dumpMove(edge->_nodes.back());
1503 if ( edge->_cosin > 0.01 )
1505 if ( edge->_cosin > faceMaxCosin )
1506 faceMaxCosin = edge->_cosin;
1509 newNodes[ i ] = n2e->second->_nodes.back();
1511 // create a temporary face
1512 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1513 proxySub->AddElement( newFace );
1515 // compute inflation step size by min size of element on a convex surface
1516 if ( faceMaxCosin > 0.1 )
1517 limitStepSize( data, face, faceMaxCosin );
1518 } // loop on 2D elements on a FACE
1519 } // loop on FACEs of a SOLID
1521 data._epsilon = 1e-7;
1522 if ( data._stepSize < 1. )
1523 data._epsilon *= data._stepSize;
1525 // Put _LayerEdge's into the vector data._edges
1527 if ( !sortEdges( data, edgesByGeom ))
1530 // Set target nodes into _Simplex and _2NearEdges
1531 TNode2Edge::iterator n2e;
1532 for ( size_t i = 0; i < data._edges.size(); ++i )
1534 if ( data._edges[i]->IsOnEdge())
1535 for ( int j = 0; j < 2; ++j )
1537 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1538 break; // _LayerEdge is shared by two _SolidData's
1539 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1540 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1541 return error("_LayerEdge not found by src node", data._index);
1542 n = (*n2e).second->_nodes.back();
1543 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1546 for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1548 _Simplex& s = data._edges[i]->_simplices[j];
1549 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1550 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1558 //================================================================================
1560 * \brief Compute inflation step size by min size of element on a convex surface
1562 //================================================================================
1564 void _ViscousBuilder::limitStepSize( _SolidData& data,
1565 const SMDS_MeshElement* face,
1569 double minSize = 10 * data._stepSize;
1570 const int nbNodes = face->NbCornerNodes();
1571 for ( int i = 0; i < nbNodes; ++i )
1573 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1574 const SMDS_MeshNode* curN = face->GetNode( i );
1575 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1576 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1578 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1579 if ( dist < minSize )
1580 minSize = dist, iN = i;
1583 double newStep = 0.8 * minSize / cosin;
1584 if ( newStep < data._stepSize )
1586 data._stepSize = newStep;
1587 data._stepSizeCoeff = 0.8 / cosin;
1588 data._stepSizeNodes[0] = face->GetNode( iN );
1589 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1593 //================================================================================
1595 * \brief Compute inflation step size by min size of element on a convex surface
1597 //================================================================================
1599 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1601 if ( minSize < data._stepSize )
1603 data._stepSize = minSize;
1604 if ( data._stepSizeNodes[0] )
1607 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1608 data._stepSizeCoeff = data._stepSize / dist;
1613 //================================================================================
1615 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1617 //================================================================================
1619 bool _ViscousBuilder::sortEdges( _SolidData& data,
1620 vector< vector<_LayerEdge*> >& edgesByGeom)
1622 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1623 // boundry inclined at a sharp angle to the shape
1625 list< TGeomID > shapesToSmooth;
1627 SMESH_MesherHelper helper( *_mesh );
1630 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1632 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1633 if ( eS.empty() ) continue;
1634 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1635 bool needSmooth = false;
1636 switch ( S.ShapeType() )
1640 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1641 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1643 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1644 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1645 if ( eV.empty() ) continue;
1646 double cosin = eV[0]->_cosin;
1648 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1652 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1653 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1655 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1656 eV[0]->_nodes[0], helper, ok);
1657 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1658 double angle = dir1.Angle( dir2 );
1659 cosin = cos( angle );
1661 needSmooth = ( cosin > 0.1 );
1667 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1669 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1670 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1671 if ( eE.empty() ) continue;
1672 if ( eE[0]->_sWOL.IsNull() )
1674 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1675 needSmooth = ( eE[i]->_cosin > 0.1 );
1679 const TopoDS_Face& F1 = TopoDS::Face( S );
1680 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1681 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1682 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1684 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1685 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1686 double angle = dir1.Angle( dir2 );
1687 double cosin = cos( angle );
1688 needSmooth = ( cosin > 0.1 );
1700 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1701 else shapesToSmooth.push_back ( iS );
1704 } // loop on edgesByGeom
1706 data._edges.reserve( data._n2eMap.size() );
1707 data._endEdgeToSmooth.clear();
1709 // first we put _LayerEdge's on shapes to smooth
1710 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1711 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1713 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1714 if ( eVec.empty() ) continue;
1715 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1716 data._endEdgeToSmooth.push_back( data._edges.size() );
1720 // then the rest _LayerEdge's
1721 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1723 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1724 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1731 //================================================================================
1733 * \brief Set data of _LayerEdge needed for smoothing
1734 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1736 //================================================================================
1738 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1739 const set<TGeomID>& subIds,
1740 SMESH_MesherHelper& helper,
1743 SMESH_MeshEditor editor(_mesh);
1745 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1746 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1750 edge._curvature = 0;
1752 // --------------------------
1753 // Compute _normal and _cosin
1754 // --------------------------
1757 edge._normal.SetCoord(0,0,0);
1759 int totalNbFaces = 0;
1761 gp_Vec du, dv, geomNorm;
1764 TGeomID shapeInd = node->getshapeId();
1765 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1766 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1767 TopoDS_Shape vertEdge;
1769 if ( onShrinkShape ) // one of faces the node is on has no layers
1771 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1772 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1774 // inflate from VERTEX along EDGE
1775 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1777 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1779 // inflate from VERTEX along FACE
1780 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1781 node, helper, normOK, &edge._cosin);
1785 // inflate from EDGE along FACE
1786 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1787 node, helper, normOK);
1790 else // layers are on all faces of SOLID the node is on
1792 // find indices of geom faces the node lies on
1793 set<TGeomID> faceIds;
1794 if ( posType == SMDS_TOP_FACE )
1796 faceIds.insert( node->getshapeId() );
1800 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1801 while ( fIt->more() )
1802 faceIds.insert( editor.FindShape(fIt->next()));
1805 set<TGeomID>::iterator id = faceIds.begin();
1807 for ( ; id != faceIds.end(); ++id )
1809 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1810 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1813 F = TopoDS::Face( s );
1815 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1816 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1819 if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1824 else // hard singularity
1826 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1827 while ( fIt->more() )
1829 const SMDS_MeshElement* f = fIt->next();
1830 if ( editor.FindShape( f ) == *id )
1832 SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1833 if ( helper.IsReversedSubMesh( F ))
1838 double size2 = geomNorm.SquareMagnitude();
1839 if ( size2 > numeric_limits<double>::min() )
1840 geomNorm /= sqrt( size2 );
1845 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1847 edge._normal += geomNorm.XYZ();
1849 if ( totalNbFaces == 0 )
1850 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1852 edge._normal /= totalNbFaces;
1857 edge._cosin = 0; break;
1859 case SMDS_TOP_EDGE: {
1860 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1861 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1862 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1863 edge._cosin = cos( angle );
1864 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1867 case SMDS_TOP_VERTEX: {
1868 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1869 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1870 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
1871 edge._cosin = cos( angle );
1872 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1876 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1880 double normSize = edge._normal.SquareModulus();
1881 if ( normSize < numeric_limits<double>::min() )
1882 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1884 edge._normal /= sqrt( normSize );
1886 // TODO: if ( !normOK ) then get normal by mesh faces
1888 // Set the rest data
1889 // --------------------
1890 if ( onShrinkShape )
1892 edge._sWOL = (*s2s).second;
1894 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1895 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1896 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1898 // set initial position which is parameters on _sWOL in this case
1899 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1901 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1902 edge._pos.push_back( gp_XYZ( u, 0, 0));
1903 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1907 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1908 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1909 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1914 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1916 if ( posType == SMDS_TOP_FACE )
1918 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
1919 double avgNormProj = 0, avgLen = 0;
1920 for ( size_t i = 0; i < edge._simplices.size(); ++i )
1922 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1923 avgNormProj += edge._normal * vec;
1924 avgLen += vec.Modulus();
1926 avgNormProj /= edge._simplices.size();
1927 avgLen /= edge._simplices.size();
1928 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1932 // Set neighbour nodes for a _LayerEdge based on EDGE
1934 if ( posType == SMDS_TOP_EDGE /*||
1935 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1937 edge._2neibors = new _2NearEdges;
1938 // target node instead of source ones will be set later
1939 if ( ! findNeiborsOnEdge( &edge,
1940 edge._2neibors->_nodes[0],
1941 edge._2neibors->_nodes[1],
1944 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1945 edge._2neibors->_nodes[1],
1949 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1954 //================================================================================
1956 * \brief Find 2 neigbor nodes of a node on EDGE
1958 //================================================================================
1960 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1961 const SMDS_MeshNode*& n1,
1962 const SMDS_MeshNode*& n2,
1965 const SMDS_MeshNode* node = edge->_nodes[0];
1966 const int shapeInd = node->getshapeId();
1967 SMESHDS_SubMesh* edgeSM = 0;
1968 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1971 edgeSM = getMeshDS()->MeshElements( shapeInd );
1972 if ( !edgeSM || edgeSM->NbElements() == 0 )
1973 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1977 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1978 while ( eIt->more() && !n2 )
1980 const SMDS_MeshElement* e = eIt->next();
1981 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1982 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1985 if (!edgeSM->Contains(e)) continue;
1989 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1990 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1992 ( iN++ ? n2 : n1 ) = nNeibor;
1995 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1999 //================================================================================
2001 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2003 //================================================================================
2005 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2006 const SMDS_MeshNode* n2,
2007 SMESH_MesherHelper& helper)
2009 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2012 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2013 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2014 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2018 double sumLen = vec1.Modulus() + vec2.Modulus();
2019 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2020 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2021 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2022 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2023 if ( _curvature ) delete _curvature;
2024 _curvature = _Curvature::New( avgNormProj, avgLen );
2026 // if ( _curvature )
2027 // cout << _nodes[0]->GetID()
2028 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2029 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2030 // << _curvature->lenDelta(0) << endl;
2035 if ( _sWOL.IsNull() )
2037 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2038 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2039 gp_XYZ plnNorm = dirE ^ _normal;
2040 double proj0 = plnNorm * vec1;
2041 double proj1 = plnNorm * vec2;
2042 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2044 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2045 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2050 //================================================================================
2052 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2053 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2055 //================================================================================
2057 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2059 _nodes = other._nodes;
2060 _normal = other._normal;
2062 _lenFactor = other._lenFactor;
2063 _cosin = other._cosin;
2064 _sWOL = other._sWOL;
2065 _2neibors = other._2neibors;
2066 _curvature = 0; std::swap( _curvature, other._curvature );
2067 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2069 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2071 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2072 _pos.push_back( gp_XYZ( u, 0, 0));
2076 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2077 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2081 //================================================================================
2083 * \brief Set _cosin and _lenFactor
2085 //================================================================================
2087 void _LayerEdge::SetCosin( double cosin )
2090 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
2093 //================================================================================
2095 * \brief Fills a vector<_Simplex >
2097 //================================================================================
2099 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2100 vector<_Simplex>& simplices,
2101 const set<TGeomID>& ingnoreShapes,
2102 const _SolidData* dataToCheckOri,
2106 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2107 while ( fIt->more() )
2109 const SMDS_MeshElement* f = fIt->next();
2110 const TGeomID shapeInd = f->getshapeId();
2111 if ( ingnoreShapes.count( shapeInd )) continue;
2112 const int nbNodes = f->NbCornerNodes();
2113 const int srcInd = f->GetNodeIndex( node );
2114 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2115 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2116 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2117 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2118 std::swap( nPrev, nNext );
2119 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2124 vector<_Simplex> sortedSimplices( simplices.size() );
2125 sortedSimplices[0] = simplices[0];
2127 for ( size_t i = 1; i < simplices.size(); ++i )
2129 for ( size_t j = 1; j < simplices.size(); ++j )
2130 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2132 sortedSimplices[i] = simplices[j];
2137 if ( nbFound == simplices.size() - 1 )
2138 simplices.swap( sortedSimplices );
2142 //================================================================================
2144 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2146 //================================================================================
2148 void _ViscousBuilder::makeGroupOfLE()
2151 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2153 if ( _sdVec[i]._edges.empty() ) continue;
2154 // string name = SMESH_Comment("_LayerEdge's_") << i;
2156 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2157 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2158 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2160 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2161 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2163 _LayerEdge* le = _sdVec[i]._edges[j];
2164 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2165 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2166 << ", " << le->_nodes[iN]->GetID() <<"])");
2167 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2171 dumpFunction( SMESH_Comment("makeNormals") << i );
2172 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2174 _LayerEdge& edge = *_sdVec[i]._edges[j];
2175 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2176 nXYZ += edge._normal * _sdVec[i]._stepSize;
2177 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2178 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2182 // name = SMESH_Comment("tmp_faces ") << i;
2183 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2184 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2185 // SMESH_MeshEditor editor( _mesh );
2186 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2187 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2188 for ( ; fExp.More(); fExp.Next() )
2190 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2192 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2193 while ( fIt->more())
2195 const SMDS_MeshElement* e = fIt->next();
2196 SMESH_Comment cmd("mesh.AddFace([");
2197 for ( int j=0; j < e->NbCornerNodes(); ++j )
2198 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2200 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2201 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2210 //================================================================================
2212 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2214 //================================================================================
2216 bool _ViscousBuilder::inflate(_SolidData& data)
2218 SMESH_MesherHelper helper( *_mesh );
2220 // Limit inflation step size by geometry size found by itersecting
2221 // normals of _LayerEdge's with mesh faces
2222 double geomSize = Precision::Infinite(), intersecDist;
2223 auto_ptr<SMESH_ElementSearcher> searcher
2224 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2225 data._proxyMesh->GetFaces( data._solid )) );
2226 for ( size_t i = 0; i < data._edges.size(); ++i )
2228 if ( data._edges[i]->IsOnEdge() ) continue;
2229 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2230 if ( geomSize > intersecDist && intersecDist > 0 )
2231 geomSize = intersecDist;
2233 if ( data._stepSize > 0.3 * geomSize )
2234 limitStepSize( data, 0.3 * geomSize );
2236 const double tgtThick = data._hyp->GetTotalThickness();
2237 if ( data._stepSize > tgtThick )
2238 limitStepSize( data, tgtThick );
2240 if ( data._stepSize < 1. )
2241 data._epsilon = data._stepSize * 1e-7;
2244 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2247 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2248 int nbSteps = 0, nbRepeats = 0;
2249 while ( 1.01 * avgThick < tgtThick )
2251 // new target length
2252 curThick += data._stepSize;
2253 if ( curThick > tgtThick )
2255 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2259 // Elongate _LayerEdge's
2260 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2261 for ( size_t i = 0; i < data._edges.size(); ++i )
2263 data._edges[i]->SetNewLength( curThick, helper );
2268 if ( !updateNormals( data, helper ) )
2271 // Improve and check quality
2272 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2276 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2277 for ( size_t i = 0; i < data._edges.size(); ++i )
2279 data._edges[i]->InvalidateStep( nbSteps+1 );
2283 break; // no more inflating possible
2287 // Evaluate achieved thickness
2289 for ( size_t i = 0; i < data._edges.size(); ++i )
2290 avgThick += data._edges[i]->_len;
2291 avgThick /= data._edges.size();
2293 cout << "-- Thickness " << avgThick << " reached" << endl;
2296 if ( distToIntersection < avgThick*1.5 )
2299 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2300 << avgThick << " ) * 1.5" << endl;
2305 limitStepSize( data, 0.25 * distToIntersection );
2306 if ( data._stepSizeNodes[0] )
2307 data._stepSize = data._stepSizeCoeff *
2308 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2312 return error("failed at the very first inflation step", data._index);
2317 //================================================================================
2319 * \brief Improve quality of layer inner surface and check intersection
2321 //================================================================================
2323 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2325 double & distToIntersection)
2327 if ( data._endEdgeToSmooth.empty() )
2328 return true; // no shapes needing smoothing
2330 bool moved, improved;
2332 SMESH_MesherHelper helper(*_mesh);
2333 Handle(Geom_Surface) surface;
2337 for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2340 iEnd = data._endEdgeToSmooth[ iS ];
2342 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2343 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2345 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2346 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2347 helper.SetSubShape( F );
2348 surface = BRep_Tool::Surface( F );
2353 F.Nullify(); surface.Nullify();
2355 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2357 if ( data._edges[ iBeg ]->IsOnEdge() )
2359 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2361 // try a simple solution on an analytic EDGE
2362 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2368 for ( int i = iBeg; i < iEnd; ++i )
2370 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2372 dumpCmd( SMESH_Comment("# end step ")<<step);
2374 while ( moved && step++ < 5 );
2375 //cout << " NB STEPS: " << step << endl;
2382 int step = 0, stepLimit = 5, badNb = 0; moved = true;
2383 while (( ++step <= stepLimit && moved ) || improved )
2385 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2386 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2387 int oldBadNb = badNb;
2390 for ( int i = iBeg; i < iEnd; ++i )
2391 moved |= data._edges[i]->Smooth(badNb);
2392 improved = ( badNb < oldBadNb );
2394 // issue 22576. no bad faces but still there are intersections to fix
2395 if ( improved && badNb == 0 )
2396 stepLimit = step + 3;
2403 for ( int i = iBeg; i < iEnd; ++i )
2405 _LayerEdge* edge = data._edges[i];
2406 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2407 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2408 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2410 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2411 << " "<< edge->_simplices[j]._nPrev->GetID()
2412 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2420 } // loop on shapes to smooth
2422 // Check if the last segments of _LayerEdge intersects 2D elements;
2423 // checked elements are either temporary faces or faces on surfaces w/o the layers
2425 auto_ptr<SMESH_ElementSearcher> searcher
2426 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2427 data._proxyMesh->GetFaces( data._solid )) );
2429 distToIntersection = Precision::Infinite();
2431 const SMDS_MeshElement* intFace = 0;
2433 const SMDS_MeshElement* closestFace = 0;
2436 for ( size_t i = 0; i < data._edges.size(); ++i )
2438 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2440 if ( distToIntersection > dist )
2442 distToIntersection = dist;
2445 closestFace = intFace;
2452 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2453 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2454 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2455 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2456 << ") distance = " << distToIntersection<< endl;
2463 //================================================================================
2465 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2466 * _LayerEdge's to be in a consequent order
2468 //================================================================================
2470 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2473 Handle(Geom_Surface)& surface,
2474 const TopoDS_Face& F,
2475 SMESH_MesherHelper& helper)
2477 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2479 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2481 if ( i2curve == _edge2curve.end() )
2483 // sort _LayerEdge's by position on the EDGE
2485 map< double, _LayerEdge* > u2edge;
2486 for ( int i = iFrom; i < iTo; ++i )
2487 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2489 ASSERT( u2edge.size() == iTo - iFrom );
2490 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2491 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2492 _edges[i] = u2e->second;
2494 // set _2neibors according to the new order
2495 for ( int i = iFrom; i < iTo-1; ++i )
2496 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2497 _edges[i]->_2neibors->reverse();
2498 if ( u2edge.size() > 1 &&
2499 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2500 _edges[iTo-1]->_2neibors->reverse();
2503 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2505 TopLoc_Location loc; double f,l;
2507 Handle(Geom_Line) line;
2508 Handle(Geom_Circle) circle;
2509 bool isLine, isCirc;
2510 if ( F.IsNull() ) // 3D case
2512 // check if the EDGE is a line
2513 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2514 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2515 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2517 line = Handle(Geom_Line)::DownCast( curve );
2518 circle = Handle(Geom_Circle)::DownCast( curve );
2519 isLine = (!line.IsNull());
2520 isCirc = (!circle.IsNull());
2522 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2525 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2526 while ( nIt->more() )
2527 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2528 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2530 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2531 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2532 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2533 for ( int i = 0; i < 3 && !isLine; ++i )
2534 isLine = ( size.Coord( i+1 ) <= lineTol );
2536 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2543 // check if the EDGE is a line
2544 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2545 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2546 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2548 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2549 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2550 isLine = (!line2d.IsNull());
2551 isCirc = (!circle2d.IsNull());
2553 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2556 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2557 while ( nIt->more() )
2558 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2559 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2561 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2562 for ( int i = 0; i < 2 && !isLine; ++i )
2563 isLine = ( size.Coord( i+1 ) <= lineTol );
2565 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2571 line = new Geom_Line( gp::OX() ); // only type does matter
2575 gp_Pnt2d p = circle2d->Location();
2576 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2577 circle = new Geom_Circle( ax, 1.); // only center position does matter
2581 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2589 return i2curve->second;
2592 //================================================================================
2594 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2596 //================================================================================
2598 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2601 Handle(Geom_Surface)& surface,
2602 const TopoDS_Face& F,
2603 SMESH_MesherHelper& helper)
2605 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2606 helper.GetMeshDS());
2607 TopoDS_Edge E = TopoDS::Edge( S );
2609 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2610 if ( curve.IsNull() ) return false;
2612 // compute a relative length of segments
2613 vector< double > len( iTo-iFrom+1 );
2615 double curLen, prevLen = len[0] = 1.0;
2616 for ( int i = iFrom; i < iTo; ++i )
2618 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2619 len[i-iFrom+1] = len[i-iFrom] + curLen;
2624 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2626 if ( F.IsNull() ) // 3D
2628 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2629 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2630 for ( int i = iFrom; i < iTo; ++i )
2632 double r = len[i-iFrom] / len.back();
2633 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2634 data._edges[i]->_pos.back() = newPos;
2635 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2636 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2637 dumpMove( tgtNode );
2642 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2643 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2644 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2645 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2647 int iPeriodic = helper.GetPeriodicIndex();
2648 if ( iPeriodic == 1 || iPeriodic == 2 )
2650 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2651 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2652 std::swap( uv0, uv1 );
2655 const gp_XY rangeUV = uv1 - uv0;
2656 for ( int i = iFrom; i < iTo; ++i )
2658 double r = len[i-iFrom] / len.back();
2659 gp_XY newUV = uv0 + r * rangeUV;
2660 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2662 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2663 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2664 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2665 dumpMove( tgtNode );
2667 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2668 pos->SetUParameter( newUV.X() );
2669 pos->SetVParameter( newUV.Y() );
2675 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2677 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2678 gp_Pnt center3D = circle->Location();
2680 if ( F.IsNull() ) // 3D
2682 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2683 data._edges[iTo-1]->_2neibors->_nodes[1] )
2684 return true; // closed EDGE - nothing to do
2686 return false; // TODO ???
2690 const gp_XY center( center3D.X(), center3D.Y() );
2692 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2693 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2694 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2695 gp_Vec2d vec0( center, uv0 );
2696 gp_Vec2d vecM( center, uvM );
2697 gp_Vec2d vec1( center, uv1 );
2698 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2699 double uMidl = vec0.Angle( vecM );
2700 if ( uLast * uMidl < 0. )
2701 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2702 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2704 gp_Ax2d axis( center, vec0 );
2705 gp_Circ2d circ( axis, radius );
2706 for ( int i = iFrom; i < iTo; ++i )
2708 double newU = uLast * len[i-iFrom] / len.back();
2709 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2710 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2712 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2713 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2714 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2715 dumpMove( tgtNode );
2717 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2718 pos->SetUParameter( newUV.X() );
2719 pos->SetVParameter( newUV.Y() );
2728 //================================================================================
2730 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2731 * _LayerEdge's on neighbor EDGE's
2733 //================================================================================
2735 bool _ViscousBuilder::updateNormals( _SolidData& data,
2736 SMESH_MesherHelper& helper )
2738 // make temporary quadrangles got by extrusion of
2739 // mesh edges along _LayerEdge._normal's
2741 vector< const SMDS_MeshElement* > tmpFaces;
2743 set< SMESH_TLink > extrudedLinks; // contains target nodes
2744 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2746 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2747 for ( size_t i = 0; i < data._edges.size(); ++i )
2749 _LayerEdge* edge = data._edges[i];
2750 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2751 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2752 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2754 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2755 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2756 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2757 if ( !link_isnew.second )
2759 extrudedLinks.erase( link_isnew.first );
2760 continue; // already extruded and will no more encounter
2762 // look for a _LayerEdge containg tgt2
2763 // _LayerEdge* neiborEdge = 0;
2764 // size_t di = 0; // check _edges[i+di] and _edges[i-di]
2765 // while ( !neiborEdge && ++di <= data._edges.size() )
2767 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2768 // neiborEdge = data._edges[i+di];
2769 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2770 // neiborEdge = data._edges[i-di];
2772 // if ( !neiborEdge )
2773 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2774 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2776 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2777 tmpFaces.push_back( f );
2779 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2780 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2781 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2786 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2787 // Perform two loops on _LayerEdge on EDGE's:
2788 // 1) to find and fix intersection
2789 // 2) to check that no new intersection appears as result of 1)
2791 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2793 auto_ptr<SMESH_ElementSearcher> searcher
2794 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
2796 // 1) Find intersections
2798 const SMDS_MeshElement* face;
2799 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2800 TLEdge2LEdgeSet edge2CloseEdge;
2802 const double eps = data._epsilon * data._epsilon;
2803 for ( size_t i = 0; i < data._edges.size(); ++i )
2805 _LayerEdge* edge = data._edges[i];
2806 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2807 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2809 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2810 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2811 ee.insert( f->_le1 );
2812 ee.insert( f->_le2 );
2813 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2814 edge2CloseEdge[ f->_le1 ].insert( edge );
2815 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2816 edge2CloseEdge[ f->_le2 ].insert( edge );
2820 // Set _LayerEdge._normal
2822 if ( !edge2CloseEdge.empty() )
2824 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2826 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2827 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2829 _LayerEdge* edge1 = e2ee->first;
2830 _LayerEdge* edge2 = 0;
2831 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2833 // find EDGEs the edges reside
2835 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2836 if ( S.ShapeType() != TopAbs_EDGE )
2837 continue; // TODO: find EDGE by VERTEX
2838 E1 = TopoDS::Edge( S );
2839 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2840 while ( E2.IsNull() && eIt != ee.end())
2842 _LayerEdge* e2 = *eIt++;
2843 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2844 if ( S.ShapeType() == TopAbs_EDGE )
2845 E2 = TopoDS::Edge( S ), edge2 = e2;
2847 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2849 // find 3 FACEs sharing 2 EDGEs
2851 TopoDS_Face FF1[2], FF2[2];
2852 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2853 while ( fIt->more() && FF1[1].IsNull())
2855 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2856 if ( helper.IsSubShape( *F, data._solid))
2857 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2859 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2860 while ( fIt->more() && FF2[1].IsNull())
2862 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2863 if ( helper.IsSubShape( *F, data._solid))
2864 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2866 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2867 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2868 std::swap( FF1[0], FF1[1] );
2869 if ( FF2[0].IsSame( FF1[0]) )
2870 std::swap( FF2[0], FF2[1] );
2871 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2874 // // get a new normal for edge1
2876 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2877 if ( edge1->_cosin < 0 )
2878 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2879 if ( edge2->_cosin < 0 )
2880 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2881 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2882 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2883 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2884 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2885 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2886 // newNorm.Normalize();
2888 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2889 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2890 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2891 newNorm.Normalize();
2893 edge1->_normal = newNorm.XYZ();
2895 // update data of edge1 depending on _normal
2896 const SMDS_MeshNode *n1, *n2;
2897 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2898 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2899 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2901 edge1->SetDataByNeighbors( n1, n2, helper );
2903 if ( edge1->_cosin < 0 )
2906 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2907 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2908 edge1->SetCosin( cos( angle ));
2910 // limit data._stepSize
2911 if ( edge1->_cosin > 0.1 )
2913 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2914 while ( fIt->more() )
2915 limitStepSize( data, fIt->next(), edge1->_cosin );
2917 // set new XYZ of target node
2918 edge1->InvalidateStep( 1 );
2920 edge1->SetNewLength( data._stepSize, helper );
2923 // Update normals and other dependent data of not intersecting _LayerEdge's
2924 // neighboring the intersecting ones
2926 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2928 _LayerEdge* edge1 = e2ee->first;
2929 if ( !edge1->_2neibors )
2931 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2933 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2934 if ( edge2CloseEdge.count ( neighbor ))
2935 continue; // j-th neighbor is also intersected
2936 _LayerEdge* prevEdge = edge1;
2937 const int nbSteps = 6;
2938 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2940 if ( !neighbor->_2neibors )
2941 break; // neighbor is on VERTEX
2943 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2944 if ( nextEdge == prevEdge )
2945 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2946 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2947 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2948 double r = double(step-1)/nbSteps;
2949 if ( !nextEdge->_2neibors )
2952 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2953 newNorm.Normalize();
2955 neighbor->_normal = newNorm;
2956 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2957 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2959 neighbor->InvalidateStep( 1 );
2961 neighbor->SetNewLength( data._stepSize, helper );
2963 // goto the next neighbor
2964 prevEdge = neighbor;
2965 neighbor = nextEdge;
2971 // 2) Check absence of intersections
2974 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
2980 //================================================================================
2982 * \brief Looks for intersection of it's last segment with faces
2983 * \param distance - returns shortest distance from the last node to intersection
2985 //================================================================================
2987 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2989 const double& epsilon,
2990 const SMDS_MeshElement** face)
2992 vector< const SMDS_MeshElement* > suspectFaces;
2994 gp_Ax1 lastSegment = LastSegment(segLen);
2995 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2997 bool segmentIntersected = false;
2998 distance = Precision::Infinite();
2999 int iFace = -1; // intersected face
3000 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3002 const SMDS_MeshElement* face = suspectFaces[j];
3003 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3004 face->GetNodeIndex( _nodes[0] ) >= 0 )
3005 continue; // face sharing _LayerEdge node
3006 const int nbNodes = face->NbCornerNodes();
3007 bool intFound = false;
3009 SMDS_MeshElement::iterator nIt = face->begin_nodes();
3012 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3016 const SMDS_MeshNode* tria[3];
3019 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3022 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3028 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3029 segmentIntersected = true;
3030 if ( distance > dist )
3031 distance = dist, iFace = j;
3034 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3035 // if ( distance && iFace > -1 )
3037 // // distance is used to limit size of inflation step which depends on
3038 // // whether the intersected face bears viscous layers or not
3039 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3043 if ( segmentIntersected )
3046 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3047 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3048 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3049 << ", intersection with face ("
3050 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3051 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3052 << ") distance = " << distance - segLen<< endl;
3058 return segmentIntersected;
3061 //================================================================================
3063 * \brief Returns size and direction of the last segment
3065 //================================================================================
3067 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3069 // find two non-coincident positions
3070 gp_XYZ orig = _pos.back();
3072 int iPrev = _pos.size() - 2;
3073 while ( iPrev >= 0 )
3075 dir = orig - _pos[iPrev];
3076 if ( dir.SquareModulus() > 1e-100 )
3086 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3087 segDir.SetDirection( _normal );
3092 gp_Pnt pPrev = _pos[ iPrev ];
3093 if ( !_sWOL.IsNull() )
3095 TopLoc_Location loc;
3096 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3099 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3100 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3104 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3105 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3107 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3109 segDir.SetLocation( pPrev );
3110 segDir.SetDirection( dir );
3111 segLen = dir.Modulus();
3117 //================================================================================
3119 * \brief Test intersection of the last segment with a given triangle
3120 * using Moller-Trumbore algorithm
3121 * Intersection is detected if distance to intersection is less than _LayerEdge._len
3123 //================================================================================
3125 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
3126 const SMDS_MeshNode* n0,
3127 const SMDS_MeshNode* n1,
3128 const SMDS_MeshNode* n2,
3130 const double& EPSILON) const
3132 //const double EPSILON = 1e-6;
3134 gp_XYZ orig = lastSegment.Location().XYZ();
3135 gp_XYZ dir = lastSegment.Direction().XYZ();
3137 SMESH_TNodeXYZ vert0( n0 );
3138 SMESH_TNodeXYZ vert1( n1 );
3139 SMESH_TNodeXYZ vert2( n2 );
3141 /* calculate distance from vert0 to ray origin */
3142 gp_XYZ tvec = orig - vert0;
3144 if ( tvec * dir > EPSILON )
3145 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3148 gp_XYZ edge1 = vert1 - vert0;
3149 gp_XYZ edge2 = vert2 - vert0;
3151 /* begin calculating determinant - also used to calculate U parameter */
3152 gp_XYZ pvec = dir ^ edge2;
3154 /* if determinant is near zero, ray lies in plane of triangle */
3155 double det = edge1 * pvec;
3157 if (det > -EPSILON && det < EPSILON)
3159 double inv_det = 1.0 / det;
3161 /* calculate U parameter and test bounds */
3162 double u = ( tvec * pvec ) * inv_det;
3163 if (u < 0.0 || u > 1.0)
3166 /* prepare to test V parameter */
3167 gp_XYZ qvec = tvec ^ edge1;
3169 /* calculate V parameter and test bounds */
3170 double v = (dir * qvec) * inv_det;
3171 if ( v < 0.0 || u + v > 1.0 )
3174 /* calculate t, ray intersects triangle */
3175 t = (edge2 * qvec) * inv_det;
3177 // if (det < EPSILON)
3180 // /* calculate distance from vert0 to ray origin */
3181 // gp_XYZ tvec = orig - vert0;
3183 // /* calculate U parameter and test bounds */
3184 // double u = tvec * pvec;
3185 // if (u < 0.0 || u > det)
3188 // /* prepare to test V parameter */
3189 // gp_XYZ qvec = tvec ^ edge1;
3191 // /* calculate V parameter and test bounds */
3192 // double v = dir * qvec;
3193 // if (v < 0.0 || u + v > det)
3196 // /* calculate t, scale parameters, ray intersects triangle */
3197 // double t = edge2 * qvec;
3198 // double inv_det = 1.0 / det;
3206 //================================================================================
3208 * \brief Perform smooth of _LayerEdge's based on EDGE's
3209 * \retval bool - true if node has been moved
3211 //================================================================================
3213 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3214 const TopoDS_Face& F,
3215 SMESH_MesherHelper& helper)
3217 ASSERT( IsOnEdge() );
3219 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3220 SMESH_TNodeXYZ oldPos( tgtNode );
3221 double dist01, distNewOld;
3223 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3224 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3225 dist01 = p0.Distance( _2neibors->_nodes[1] );
3227 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3228 double lenDelta = 0;
3231 //lenDelta = _curvature->lenDelta( _len );
3232 lenDelta = _curvature->lenDeltaByDist( dist01 );
3233 newPos.ChangeCoord() += _normal * lenDelta;
3236 distNewOld = newPos.Distance( oldPos );
3240 if ( _2neibors->_plnNorm )
3242 // put newPos on the plane defined by source node and _plnNorm
3243 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3244 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3245 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3247 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3248 _pos.back() = newPos.XYZ();
3252 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3253 gp_XY uv( Precision::Infinite(), 0 );
3254 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3255 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3257 newPos = surface->Value( uv.X(), uv.Y() );
3258 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3261 if ( _curvature && lenDelta < 0 )
3263 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3264 _len -= prevPos.Distance( oldPos );
3265 _len += prevPos.Distance( newPos );
3267 bool moved = distNewOld > dist01/50;
3269 dumpMove( tgtNode ); // debug
3274 //================================================================================
3276 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3277 * \retval bool - true if _tgtNode has been moved
3279 //================================================================================
3281 bool _LayerEdge::Smooth(int& badNb)
3283 if ( _simplices.size() < 2 )
3284 return false; // _LayerEdge inflated along EDGE or FACE
3286 // compute new position for the last _pos
3287 gp_XYZ newPos (0,0,0);
3288 for ( size_t i = 0; i < _simplices.size(); ++i )
3289 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3290 newPos /= _simplices.size();
3293 newPos += _normal * _curvature->lenDelta( _len );
3295 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3296 // if ( _cosin < -0.1)
3298 // // Avoid decreasing length of edge on concave surface
3299 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3300 // gp_Vec newMove( prevPos, newPos );
3301 // newPos = _pos.back() + newMove.XYZ();
3303 // else if ( _cosin > 0.3 )
3305 // // Avoid increasing length of edge too much
3308 // count quality metrics (orientation) of tetras around _tgtNode
3310 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3311 for ( size_t i = 0; i < _simplices.size(); ++i )
3312 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3315 for ( size_t i = 0; i < _simplices.size(); ++i )
3316 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3318 if ( nbOkAfter < nbOkBefore )
3321 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3323 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3324 _len += prevPos.Distance(newPos);
3326 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3327 _pos.back() = newPos;
3329 badNb += _simplices.size() - nbOkAfter;
3336 //================================================================================
3338 * \brief Add a new segment to _LayerEdge during inflation
3340 //================================================================================
3342 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3344 if ( _len - len > -1e-6 )
3346 _pos.push_back( _pos.back() );
3350 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3351 SMESH_TNodeXYZ oldXYZ( n );
3352 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3353 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3355 _pos.push_back( nXYZ );
3357 if ( !_sWOL.IsNull() )
3360 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3362 double u = Precision::Infinite(); // to force projection w/o distance check
3363 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3364 _pos.back().SetCoord( u, 0, 0 );
3365 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3366 pos->SetUParameter( u );
3370 gp_XY uv( Precision::Infinite(), 0 );
3371 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3372 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3373 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3374 pos->SetUParameter( uv.X() );
3375 pos->SetVParameter( uv.Y() );
3377 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3379 dumpMove( n ); //debug
3382 //================================================================================
3384 * \brief Remove last inflation step
3386 //================================================================================
3388 void _LayerEdge::InvalidateStep( int curStep )
3390 if ( _pos.size() > curStep )
3392 _pos.resize( curStep );
3393 gp_Pnt nXYZ = _pos.back();
3394 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3395 if ( !_sWOL.IsNull() )
3397 TopLoc_Location loc;
3398 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3400 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3401 pos->SetUParameter( nXYZ.X() );
3403 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3404 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3408 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3409 pos->SetUParameter( nXYZ.X() );
3410 pos->SetVParameter( nXYZ.Y() );
3411 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3412 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3415 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3420 //================================================================================
3422 * \brief Create layers of prisms
3424 //================================================================================
3426 bool _ViscousBuilder::refine(_SolidData& data)
3428 SMESH_MesherHelper helper( *_mesh );
3429 helper.SetSubShape( data._solid );
3430 helper.SetElementsOnShape(false);
3432 Handle(Geom_Curve) curve;
3433 Handle(Geom_Surface) surface;
3434 TopoDS_Edge geomEdge;
3435 TopoDS_Face geomFace;
3436 TopLoc_Location loc;
3437 double f,l, u/*, distXYZ[4]*/;
3441 for ( size_t i = 0; i < data._edges.size(); ++i )
3443 _LayerEdge& edge = *data._edges[i];
3445 // get accumulated length of segments
3446 vector< double > segLen( edge._pos.size() );
3448 for ( size_t j = 1; j < edge._pos.size(); ++j )
3449 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3451 // allocate memory for new nodes if it is not yet refined
3452 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3453 if ( edge._nodes.size() == 2 )
3455 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3457 edge._nodes.back() = tgtNode;
3459 if ( !edge._sWOL.IsNull() )
3461 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3462 // restore position of the last node
3466 geomEdge = TopoDS::Edge( edge._sWOL );
3467 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3468 // double u = helper.GetNodeU( tgtNode );
3469 // p = curve->Value( u );
3473 geomFace = TopoDS::Face( edge._sWOL );
3474 surface = BRep_Tool::Surface( geomFace, loc );
3475 // gp_XY uv = helper.GetNodeUV( tgtNode );
3476 // p = surface->Value( uv.X(), uv.Y() );
3478 // p.Transform( loc );
3479 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3481 // calculate height of the first layer
3483 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3484 const double f = data._hyp->GetStretchFactor();
3485 const int N = data._hyp->GetNumberLayers();
3486 const double fPowN = pow( f, N );
3487 if ( fPowN - 1 <= numeric_limits<double>::min() )
3490 h0 = T * ( f - 1 )/( fPowN - 1 );
3492 const double zeroLen = std::numeric_limits<double>::min();
3494 // create intermediate nodes
3495 double hSum = 0, hi = h0/f;
3497 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3499 // compute an intermediate position
3502 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3504 int iPrevSeg = iSeg-1;
3505 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3507 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3508 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3510 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3511 if ( !edge._sWOL.IsNull() )
3513 // compute XYZ by parameters <pos>
3517 pos = curve->Value( u ).Transformed(loc);
3521 uv.SetCoord( pos.X(), pos.Y() );
3522 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3525 // create or update the node
3528 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3529 if ( !edge._sWOL.IsNull() )
3532 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3534 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3538 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3543 if ( !edge._sWOL.IsNull() )
3545 // make average pos from new and current parameters
3548 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3549 pos = curve->Value( u ).Transformed(loc);
3553 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3554 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3557 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3562 if ( !getMeshDS()->IsEmbeddedMode() )
3563 // Log node movement
3564 for ( size_t i = 0; i < data._edges.size(); ++i )
3566 _LayerEdge& edge = *data._edges[i];
3567 SMESH_TNodeXYZ p ( edge._nodes.back() );
3568 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3571 // TODO: make quadratic prisms and polyhedrons(?)
3573 helper.SetElementsOnShape(true);
3575 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3576 for ( ; exp.More(); exp.Next() )
3578 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3580 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3581 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3582 vector< vector<const SMDS_MeshNode*>* > nnVec;
3583 while ( fIt->more() )
3585 const SMDS_MeshElement* face = fIt->next();
3586 int nbNodes = face->NbCornerNodes();
3587 nnVec.resize( nbNodes );
3588 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3589 for ( int iN = 0; iN < nbNodes; ++iN )
3591 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3592 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3595 int nbZ = nnVec[0]->size();
3599 for ( int iZ = 1; iZ < nbZ; ++iZ )
3600 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3601 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3604 for ( int iZ = 1; iZ < nbZ; ++iZ )
3605 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3606 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3607 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3608 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3611 return error("Not supported type of element", data._index);
3618 //================================================================================
3620 * \brief Shrink 2D mesh on faces to let space for inflated layers
3622 //================================================================================
3624 bool _ViscousBuilder::shrink()
3626 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3627 // inflated along FACE or EDGE)
3628 map< TGeomID, _SolidData* > f2sdMap;
3629 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3631 _SolidData& data = _sdVec[i];
3632 TopTools_MapOfShape FFMap;
3633 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3634 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3635 if ( s2s->second.ShapeType() == TopAbs_FACE )
3637 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3639 if ( FFMap.Add( (*s2s).second ))
3640 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3641 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3642 // by StdMeshers_QuadToTriaAdaptor
3643 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3645 SMESH_ProxyMesh::SubMesh* proxySub =
3646 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3647 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3648 while ( fIt->more() )
3649 proxySub->AddElement( fIt->next() );
3650 // as a result 3D algo will use elements from proxySub and not from smDS
3655 SMESH_MesherHelper helper( *_mesh );
3656 helper.ToFixNodeParameters( true );
3659 map< TGeomID, _Shrinker1D > e2shrMap;
3661 // loop on FACES to srink mesh on
3662 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3663 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3665 _SolidData& data = *f2sd->second;
3666 TNode2Edge& n2eMap = data._n2eMap;
3667 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3669 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3671 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3672 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3674 helper.SetSubShape(F);
3676 // ===========================
3677 // Prepare data for shrinking
3678 // ===========================
3680 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3681 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3682 vector < const SMDS_MeshNode* > smoothNodes;
3684 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3685 while ( nIt->more() )
3687 const SMDS_MeshNode* n = nIt->next();
3688 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3689 smoothNodes.push_back( n );
3692 // Find out face orientation
3694 const set<TGeomID> ignoreShapes;
3696 if ( !smoothNodes.empty() )
3698 vector<_Simplex> simplices;
3699 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3700 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3701 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3702 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3703 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3707 // Find _LayerEdge's inflated along F
3708 vector< _LayerEdge* > lEdges;
3710 SMESH_subMeshIteratorPtr subIt =
3711 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3712 while ( subIt->more() )
3714 SMESH_subMesh* sub = subIt->next();
3715 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3716 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3718 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3719 while ( nIt->more() )
3721 _LayerEdge* edge = n2eMap[ nIt->next() ];
3722 lEdges.push_back( edge );
3723 prepareEdgeToShrink( *edge, F, helper, smDS );
3728 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3729 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3730 while ( fIt->more() )
3731 if ( const SMDS_MeshElement* f = fIt->next() )
3732 dumpChangeNodes( f );
3734 // Replace source nodes by target nodes in mesh faces to shrink
3735 const SMDS_MeshNode* nodes[20];
3736 for ( size_t i = 0; i < lEdges.size(); ++i )
3738 _LayerEdge& edge = *lEdges[i];
3739 const SMDS_MeshNode* srcNode = edge._nodes[0];
3740 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3741 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3742 while ( fIt->more() )
3744 const SMDS_MeshElement* f = fIt->next();
3745 if ( !smDS->Contains( f ))
3747 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
3748 for ( int iN = 0; nIt->more(); ++iN )
3750 const SMDS_MeshNode* n = nIt->next();
3751 nodes[iN] = ( n == srcNode ? tgtNode : n );
3753 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3757 // find out if a FACE is concave
3758 const bool isConcaveFace = isConcave( F, helper );
3760 // Create _SmoothNode's on face F
3761 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3763 const bool sortSimplices = isConcaveFace;
3764 for ( size_t i = 0; i < smoothNodes.size(); ++i )
3766 const SMDS_MeshNode* n = smoothNodes[i];
3767 nodesToSmooth[ i ]._node = n;
3768 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3769 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
3770 // fix up incorrect uv of nodes on the FACE
3771 helper.GetNodeUV( F, n, 0, &isOkUV);
3775 //if ( nodesToSmooth.empty() ) continue;
3777 // Find EDGE's to shrink and set simpices to LayerEdge's
3778 set< _Shrinker1D* > eShri1D;
3780 for ( size_t i = 0; i < lEdges.size(); ++i )
3782 _LayerEdge* edge = lEdges[i];
3783 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3785 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3786 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3787 eShri1D.insert( & srinker );
3788 srinker.AddEdge( edge, helper );
3789 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3790 // restore params of nodes on EGDE if the EDGE has been already
3791 // srinked while srinking another FACE
3792 srinker.RestoreParams();
3794 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
3798 bool toFixTria = false; // to improve quality of trias by diagonal swap
3799 if ( isConcaveFace )
3801 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3802 if ( hasTria != hasQuad ) {
3803 toFixTria = hasTria;
3806 set<int> nbNodesSet;
3807 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3808 while ( fIt->more() && nbNodesSet.size() < 2 )
3809 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3810 toFixTria = ( *nbNodesSet.begin() == 3 );
3814 // ==================
3815 // Perform shrinking
3816 // ==================
3818 bool shrinked = true;
3819 int badNb, shriStep=0, smooStep=0;
3820 _SmoothNode::SmoothType smoothType
3821 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
3825 // Move boundary nodes (actually just set new UV)
3826 // -----------------------------------------------
3827 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
3829 for ( size_t i = 0; i < lEdges.size(); ++i )
3831 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3835 // Move nodes on EDGE's
3836 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
3837 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3838 for ( ; shr != eShri1D.end(); ++shr )
3839 (*shr)->Compute( /*set3D=*/false, helper );
3842 // -----------------
3843 int nbNoImpSteps = 0;
3846 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3848 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3850 int oldBadNb = badNb;
3853 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3855 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3856 smoothType, /*set3D=*/isConcaveFace);
3858 if ( badNb < oldBadNb )
3866 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3867 if ( shriStep > 200 )
3868 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
3870 // Fix narrow triangles by swapping diagonals
3871 // ---------------------------------------
3874 set<const SMDS_MeshNode*> usedNodes;
3875 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
3877 // update working data
3878 set<const SMDS_MeshNode*>::iterator n;
3879 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
3881 n = usedNodes.find( nodesToSmooth[ i ]._node );
3882 if ( n != usedNodes.end())
3884 getSimplices( nodesToSmooth[ i ]._node,
3885 nodesToSmooth[ i ]._simplices,
3887 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
3888 usedNodes.erase( n );
3891 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
3893 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
3894 if ( n != usedNodes.end())
3896 getSimplices( lEdges[i]->_nodes.back(),
3897 lEdges[i]->_simplices,
3899 usedNodes.erase( n );
3903 } // while ( shrinked )
3905 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3906 bool isStructuredFixed = false;
3907 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
3908 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
3909 if ( !isStructuredFixed )
3911 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
3912 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
3914 for ( int st = 3; st; --st )
3917 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
3918 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
3919 case 3: smoothType = _SmoothNode::ANGULAR; break;
3921 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3922 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3924 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3925 smoothType,/*set3D=*/st==1 );
3930 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3931 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3933 if ( !getMeshDS()->IsEmbeddedMode() )
3934 // Log node movement
3935 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3937 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3938 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3941 } // loop on FACES to srink mesh on
3944 // Replace source nodes by target nodes in shrinked mesh edges
3946 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3947 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3948 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3953 //================================================================================
3955 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3957 //================================================================================
3959 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3960 const TopoDS_Face& F,
3961 SMESH_MesherHelper& helper,
3962 const SMESHDS_SubMesh* faceSubMesh)
3964 const SMDS_MeshNode* srcNode = edge._nodes[0];
3965 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3969 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3971 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3972 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3973 gp_Vec2d uvDir( srcUV, tgtUV );
3974 double uvLen = uvDir.Magnitude();
3976 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3979 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3980 // vector<const SMDS_MeshElement*> faces;
3981 // multimap< double, const SMDS_MeshNode* > proj2node;
3982 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3983 // while ( fIt->more() )
3985 // const SMDS_MeshElement* f = fIt->next();
3986 // if ( faceSubMesh->Contains( f ))
3987 // faces.push_back( f );
3989 // for ( size_t i = 0; i < faces.size(); ++i )
3991 // const int nbNodes = faces[i]->NbCornerNodes();
3992 // for ( int j = 0; j < nbNodes; ++j )
3994 // const SMDS_MeshNode* n = faces[i]->GetNode(j);
3995 // if ( n == srcNode ) continue;
3996 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3997 // ( faces.size() > 1 || nbNodes > 3 ))
3999 // gp_Pnt2d uv = helper.GetNodeUV( F, n );
4000 // gp_Vec2d uvDirN( srcUV, uv );
4001 // double proj = uvDirN * uvDir;
4002 // proj2node.insert( make_pair( proj, n ));
4006 // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4007 // const double minProj = p2n->first;
4008 // const double projThreshold = 1.1 * uvLen;
4009 // if ( minProj > projThreshold )
4011 // // tgtNode is located so that it does not make faces with wrong orientation
4014 edge._pos.resize(1);
4015 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4017 // store most risky nodes in _simplices
4018 // p2nEnd = proj2node.lower_bound( projThreshold );
4019 // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4020 // edge._simplices.resize( nbSimpl );
4021 // for ( int i = 0; i < nbSimpl; ++i )
4023 // edge._simplices[i]._nPrev = p2n->second;
4024 // if ( ++p2n != p2nEnd )
4025 // edge._simplices[i]._nNext = p2n->second;
4027 // set UV of source node to target node
4028 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4029 pos->SetUParameter( srcUV.X() );
4030 pos->SetVParameter( srcUV.Y() );
4032 else // _sWOL is TopAbs_EDGE
4034 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4035 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4036 if ( !edgeSM || edgeSM->NbElements() == 0 )
4037 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4039 const SMDS_MeshNode* n2 = 0;
4040 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4041 while ( eIt->more() && !n2 )
4043 const SMDS_MeshElement* e = eIt->next();
4044 if ( !edgeSM->Contains(e)) continue;
4045 n2 = e->GetNode( 0 );
4046 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4049 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4051 double uSrc = helper.GetNodeU( E, srcNode, n2 );
4052 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4053 double u2 = helper.GetNodeU( E, n2, srcNode );
4055 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4057 // tgtNode is located so that it does not make faces with wrong orientation
4060 edge._pos.resize(1);
4061 edge._pos[0].SetCoord( U_TGT, uTgt );
4062 edge._pos[0].SetCoord( U_SRC, uSrc );
4063 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4065 edge._simplices.resize( 1 );
4066 edge._simplices[0]._nPrev = n2;
4068 // set UV of source node to target node
4069 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4070 pos->SetUParameter( uSrc );
4074 //================================================================================
4076 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4078 //================================================================================
4080 // Compute UV to follow during shrinking
4082 // const SMDS_MeshNode* srcNode = edge._nodes[0];
4083 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
4085 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4086 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4087 // gp_Vec2d uvDir( srcUV, tgtUV );
4088 // double uvLen = uvDir.Magnitude();
4091 // // Select shrinking step such that not to make faces with wrong orientation.
4092 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4093 // const double minStepSize = uvLen / 20;
4094 // double stepSize = uvLen;
4095 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4096 // while ( fIt->more() )
4098 // const SMDS_MeshElement* f = fIt->next();
4099 // if ( !faceSubMesh->Contains( f )) continue;
4100 // const int nbNodes = f->NbCornerNodes();
4101 // for ( int i = 0; i < nbNodes; ++i )
4103 // const SMDS_MeshNode* n = f->GetNode(i);
4104 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4106 // gp_XY uv = helper.GetNodeUV( F, n );
4107 // gp_Vec2d uvDirN( srcUV, uv );
4108 // double proj = uvDirN * uvDir;
4109 // if ( proj < stepSize && proj > minStepSize )
4115 // const int nbSteps = ceil( uvLen / stepSize );
4116 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4117 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4118 // edge._pos.resize( nbSteps );
4119 // edge._pos[0] = tgtUV0;
4120 // for ( int i = 1; i < nbSteps; ++i )
4122 // double r = i / double( nbSteps );
4123 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4128 //================================================================================
4130 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4132 //================================================================================
4134 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
4135 SMESH_MesherHelper& helper,
4138 set<const SMDS_MeshNode*> * involvedNodes)
4140 SMESH::Controls::AspectRatio qualifier;
4141 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4142 const double maxAspectRatio = is2D ? 4. : 2;
4143 NodeCoordHelper xyz( F, helper, is2D );
4145 // find bad triangles
4147 vector< const SMDS_MeshElement* > badTrias;
4148 vector< double > badAspects;
4149 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
4150 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4151 while ( fIt->more() )
4153 const SMDS_MeshElement * f = fIt->next();
4154 if ( f->NbCornerNodes() != 3 ) continue;
4155 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4156 double aspect = qualifier.GetValue( points );
4157 if ( aspect > maxAspectRatio )
4159 badTrias.push_back( f );
4160 badAspects.push_back( aspect );
4165 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4166 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4167 while ( fIt->more() )
4169 const SMDS_MeshElement * f = fIt->next();
4170 if ( f->NbCornerNodes() == 3 )
4171 dumpChangeNodes( f );
4175 if ( badTrias.empty() )
4178 // find couples of faces to swap diagonal
4180 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4181 vector< T2Trias > triaCouples;
4183 TIDSortedElemSet involvedFaces, emptySet;
4184 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4187 double aspRatio [3];
4190 if ( !involvedFaces.insert( badTrias[iTia] ).second )
4192 for ( int iP = 0; iP < 3; ++iP )
4193 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4195 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4196 int bestCouple = -1;
4197 for ( int iSide = 0; iSide < 3; ++iSide )
4199 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4200 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4201 trias [iSide].first = badTrias[iTia];
4202 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4204 if (( ! trias[iSide].second ) ||
4205 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4206 ( ! sm->Contains( trias[iSide].second )))
4209 // aspect ratio of an adjacent tria
4210 for ( int iP = 0; iP < 3; ++iP )
4211 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4212 double aspectInit = qualifier.GetValue( points2 );
4214 // arrange nodes as after diag-swaping
4215 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4216 i3 = helper.WrapIndex( i1-1, 3 );
4218 i3 = helper.WrapIndex( i1+1, 3 );
4220 points1( 1+ iSide ) = points2( 1+ i3 );
4221 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
4223 // aspect ratio after diag-swaping
4224 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4225 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4228 // prevent inversion of a triangle
4229 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4230 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4231 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4234 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4238 if ( bestCouple >= 0 )
4240 triaCouples.push_back( trias[bestCouple] );
4241 involvedFaces.insert ( trias[bestCouple].second );
4245 involvedFaces.erase( badTrias[iTia] );
4248 if ( triaCouples.empty() )
4253 SMESH_MeshEditor editor( helper.GetMesh() );
4254 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4255 for ( size_t i = 0; i < triaCouples.size(); ++i )
4257 dumpChangeNodes( triaCouples[i].first );
4258 dumpChangeNodes( triaCouples[i].second );
4259 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4262 if ( involvedNodes )
4263 for ( size_t i = 0; i < triaCouples.size(); ++i )
4265 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4266 triaCouples[i].first->end_nodes() );
4267 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4268 triaCouples[i].second->end_nodes() );
4271 // just for debug dump resulting triangles
4272 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4273 for ( size_t i = 0; i < triaCouples.size(); ++i )
4275 dumpChangeNodes( triaCouples[i].first );
4276 dumpChangeNodes( triaCouples[i].second );
4280 //================================================================================
4282 * \brief Move target node to it's final position on the FACE during shrinking
4284 //================================================================================
4286 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4287 const TopoDS_Face& F,
4288 SMESH_MesherHelper& helper )
4291 return false; // already at the target position
4293 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4295 if ( _sWOL.ShapeType() == TopAbs_FACE )
4297 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4298 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4299 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4300 const double uvLen = tgtUV.Distance( curUV );
4301 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4303 // Select shrinking step such that not to make faces with wrong orientation.
4304 double stepSize = uvLen;
4305 for ( size_t i = 0; i < _simplices.size(); ++i )
4307 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4308 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4309 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4310 gp_XY dirN = uvN2 - uvN1;
4311 double det = uvDir.Crossed( dirN );
4312 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
4313 gp_XY dirN2Cur = curUV - uvN1;
4314 double step = dirN.Crossed( dirN2Cur ) / det;
4316 stepSize = Min( step, stepSize );
4319 if ( uvLen - stepSize < _len / 200. )
4324 else if ( stepSize > 0 )
4326 newUV = curUV + uvDir.XY() * stepSize * kSafe;
4332 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4333 pos->SetUParameter( newUV.X() );
4334 pos->SetVParameter( newUV.Y() );
4337 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4338 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4339 dumpMove( tgtNode );
4342 else // _sWOL is TopAbs_EDGE
4344 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4345 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4346 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4348 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4349 const double uSrc = _pos[0].Coord( U_SRC );
4350 const double lenTgt = _pos[0].Coord( LEN_TGT );
4352 double newU = _pos[0].Coord( U_TGT );
4353 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4359 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4361 tgtPos->SetUParameter( newU );
4363 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4364 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4365 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4366 dumpMove( tgtNode );
4372 //================================================================================
4374 * \brief Perform smooth on the FACE
4375 * \retval bool - true if the node has been moved
4377 //================================================================================
4379 bool _SmoothNode::Smooth(int& badNb,
4380 Handle(Geom_Surface)& surface,
4381 SMESH_MesherHelper& helper,
4382 const double refSign,
4386 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4388 // get uv of surrounding nodes
4389 vector<gp_XY> uv( _simplices.size() );
4390 for ( size_t i = 0; i < _simplices.size(); ++i )
4391 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4393 // compute new UV for the node
4395 if ( how == TFI && _simplices.size() == 4 )
4398 for ( size_t i = 0; i < _simplices.size(); ++i )
4399 if ( _simplices[i]._nOpp )
4400 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4402 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4404 newPos = helper.calcTFI ( 0.5, 0.5,
4405 corners[0], corners[1], corners[2], corners[3],
4406 uv[1], uv[2], uv[3], uv[0] );
4408 else if ( how == ANGULAR )
4410 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4412 else if ( how == CENTROIDAL && _simplices.size() > 3 )
4414 // average centers of diagonals wieghted with their reciprocal lengths
4415 if ( _simplices.size() == 4 )
4417 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4418 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4419 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4423 double sumWeight = 0;
4424 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4425 for ( int i = 0; i < nb; ++i )
4428 int iTo = i + _simplices.size() - 1;
4429 for ( int j = iFrom; j < iTo; ++j )
4431 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4432 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4434 newPos += w * ( uv[i]+uv[i2] );
4437 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4443 for ( size_t i = 0; i < _simplices.size(); ++i )
4445 newPos /= _simplices.size();
4448 // count quality metrics (orientation) of triangles around the node
4450 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4451 for ( size_t i = 0; i < _simplices.size(); ++i )
4452 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4455 for ( size_t i = 0; i < _simplices.size(); ++i )
4456 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4458 if ( nbOkAfter < nbOkBefore )
4460 badNb += _simplices.size() - nbOkBefore;
4464 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4465 pos->SetUParameter( newPos.X() );
4466 pos->SetVParameter( newPos.Y() );
4473 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4474 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4478 badNb += _simplices.size() - nbOkAfter;
4479 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4482 //================================================================================
4484 * \brief Computes new UV using angle based smoothing technic
4486 //================================================================================
4488 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4489 const gp_XY& uvToFix,
4490 const double refSign)
4492 uv.push_back( uv.front() );
4494 vector< gp_XY > edgeDir ( uv.size() );
4495 vector< double > edgeSize( uv.size() );
4496 for ( size_t i = 1; i < edgeDir.size(); ++i )
4498 edgeDir [i-1] = uv[i] - uv[i-1];
4499 edgeSize[i-1] = edgeDir[i-1].Modulus();
4500 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4501 edgeDir[i-1].SetX( 100 );
4503 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4505 edgeDir.back() = edgeDir.front();
4506 edgeSize.back() = edgeSize.front();
4511 for ( size_t i = 1; i < edgeDir.size(); ++i )
4513 if ( edgeDir[i-1].X() > 1. ) continue;
4515 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4516 if ( i == edgeDir.size() ) break;
4518 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4519 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4520 gp_XY bisec = norm1 + norm2;
4521 double bisecSize = bisec.Modulus();
4522 if ( bisecSize < numeric_limits<double>::min() )
4524 bisec = -edgeDir[i1] + edgeDir[i];
4525 bisecSize = bisec.Modulus();
4529 gp_XY dirToN = uvToFix - p;
4530 double distToN = dirToN.Modulus();
4531 if ( bisec * dirToN < 0 )
4534 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4536 sumSize += edgeSize[i1] + edgeSize[i];
4538 newPos /= /*nbEdges * */sumSize;
4542 //================================================================================
4544 * \brief Delete _SolidData
4546 //================================================================================
4548 _SolidData::~_SolidData()
4550 for ( size_t i = 0; i < _edges.size(); ++i )
4552 if ( _edges[i] && _edges[i]->_2neibors )
4553 delete _edges[i]->_2neibors;
4558 //================================================================================
4560 * \brief Add a _LayerEdge inflated along the EDGE
4562 //================================================================================
4564 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4567 if ( _nodes.empty() )
4569 _edges[0] = _edges[1] = 0;
4573 if ( e == _edges[0] || e == _edges[1] )
4575 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4576 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4577 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4578 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4581 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4583 BRep_Tool::Range( E, f,l );
4584 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4585 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4589 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4590 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4592 if ( _nodes.empty() )
4594 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4595 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4597 TopLoc_Location loc;
4598 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4599 GeomAdaptor_Curve aCurve(C, f,l);
4600 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4602 int nbExpectNodes = eSubMesh->NbNodes();
4603 _initU .reserve( nbExpectNodes );
4604 _normPar.reserve( nbExpectNodes );
4605 _nodes .reserve( nbExpectNodes );
4606 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4607 while ( nIt->more() )
4609 const SMDS_MeshNode* node = nIt->next();
4610 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4611 node == tgtNode0 || node == tgtNode1 )
4612 continue; // refinement nodes
4613 _nodes.push_back( node );
4614 _initU.push_back( helper.GetNodeU( E, node ));
4615 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4616 _normPar.push_back( len / totLen );
4621 // remove target node of the _LayerEdge from _nodes
4623 for ( size_t i = 0; i < _nodes.size(); ++i )
4624 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4625 _nodes[i] = 0, nbFound++;
4626 if ( nbFound == _nodes.size() )
4631 //================================================================================
4633 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4635 //================================================================================
4637 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4639 if ( _done || _nodes.empty())
4641 const _LayerEdge* e = _edges[0];
4642 if ( !e ) e = _edges[1];
4645 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4646 ( !_edges[1] || _edges[1]->_pos.empty() ));
4648 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4650 if ( set3D || _done )
4652 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4653 GeomAdaptor_Curve aCurve(C, f,l);
4656 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4658 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4659 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4661 for ( size_t i = 0; i < _nodes.size(); ++i )
4663 if ( !_nodes[i] ) continue;
4664 double len = totLen * _normPar[i];
4665 GCPnts_AbscissaPoint discret( aCurve, len, f );
4666 if ( !discret.IsDone() )
4667 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4668 double u = discret.Parameter();
4669 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4670 pos->SetUParameter( u );
4671 gp_Pnt p = C->Value( u );
4672 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4677 BRep_Tool::Range( E, f,l );
4679 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4681 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4683 for ( size_t i = 0; i < _nodes.size(); ++i )
4685 if ( !_nodes[i] ) continue;
4686 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4687 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4688 pos->SetUParameter( u );
4693 //================================================================================
4695 * \brief Restore initial parameters of nodes on EDGE
4697 //================================================================================
4699 void _Shrinker1D::RestoreParams()
4702 for ( size_t i = 0; i < _nodes.size(); ++i )
4704 if ( !_nodes[i] ) continue;
4705 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4706 pos->SetUParameter( _initU[i] );
4711 //================================================================================
4713 * \brief Replace source nodes by target nodes in shrinked mesh edges
4715 //================================================================================
4717 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4719 const SMDS_MeshNode* nodes[3];
4720 for ( int i = 0; i < 2; ++i )
4722 if ( !_edges[i] ) continue;
4724 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4725 if ( !eSubMesh ) return;
4726 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4727 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4728 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4729 while ( eIt->more() )
4731 const SMDS_MeshElement* e = eIt->next();
4732 if ( !eSubMesh->Contains( e ))
4734 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4735 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4737 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4738 nodes[iN] = ( n == srcNode ? tgtNode : n );
4740 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4745 //================================================================================
4747 * \brief Creates 2D and 1D elements on boundaries of new prisms
4749 //================================================================================
4751 bool _ViscousBuilder::addBoundaryElements()
4753 SMESH_MesherHelper helper( *_mesh );
4755 for ( size_t i = 0; i < _sdVec.size(); ++i )
4757 _SolidData& data = _sdVec[i];
4758 TopTools_IndexedMapOfShape geomEdges;
4759 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4760 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4762 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4764 // Get _LayerEdge's based on E
4766 map< double, const SMDS_MeshNode* > u2nodes;
4767 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4770 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4771 TNode2Edge & n2eMap = data._n2eMap;
4772 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4774 //check if 2D elements are needed on E
4775 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4776 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4777 ledges.push_back( n2e->second );
4779 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4780 continue; // no layers on E
4781 ledges.push_back( n2eMap[ u2n->second ]);
4783 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4784 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4785 int nbSharedPyram = 0;
4786 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4787 while ( vIt->more() )
4789 const SMDS_MeshElement* v = vIt->next();
4790 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4792 if ( nbSharedPyram > 1 )
4793 continue; // not free border of the pyramid
4795 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4796 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4797 continue; // faces already created
4799 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4800 ledges.push_back( n2eMap[ u2n->second ]);
4802 // Find out orientation and type of face to create
4804 bool reverse = false, isOnFace;
4806 map< TGeomID, TopoDS_Shape >::iterator e2f =
4807 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4809 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4811 F = e2f->second.Oriented( TopAbs_FORWARD );
4812 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4813 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4814 reverse = !reverse, F.Reverse();
4815 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
4820 // find FACE with layers sharing E
4821 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4822 while ( fIt->more() && F.IsNull() )
4824 const TopoDS_Shape* pF = fIt->next();
4825 if ( helper.IsSubShape( *pF, data._solid) &&
4826 !data._ignoreFaceIds.count( e2f->first ))
4830 // Find the sub-mesh to add new faces
4831 SMESHDS_SubMesh* sm = 0;
4833 sm = getMeshDS()->MeshElements( F );
4835 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4837 return error("error in addBoundaryElements()", data._index);
4840 const int dj1 = reverse ? 0 : 1;
4841 const int dj2 = reverse ? 1 : 0;
4842 for ( size_t j = 1; j < ledges.size(); ++j )
4844 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4845 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4847 for ( size_t z = 1; z < nn1.size(); ++z )
4848 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4850 for ( size_t z = 1; z < nn1.size(); ++z )
4851 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4855 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4857 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4858 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4860 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4861 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4863 helper.SetSubShape( edge->_sWOL );
4864 helper.SetElementsOnShape( true );
4865 for ( size_t z = 1; z < nn.size(); ++z )
4866 helper.AddEdge( nn[z-1], nn[z] );