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, badNb = 0; moved = true;
2383 while (( ++step <= 5 && 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 );
2399 for ( int i = iBeg; i < iEnd; ++i )
2401 _LayerEdge* edge = data._edges[i];
2402 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2403 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2404 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2406 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2407 << " "<< edge->_simplices[j]._nPrev->GetID()
2408 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2416 } // loop on shapes to smooth
2418 // Check if the last segments of _LayerEdge intersects 2D elements;
2419 // checked elements are either temporary faces or faces on surfaces w/o the layers
2421 auto_ptr<SMESH_ElementSearcher> searcher
2422 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2423 data._proxyMesh->GetFaces( data._solid )) );
2425 distToIntersection = Precision::Infinite();
2427 const SMDS_MeshElement* intFace = 0;
2429 const SMDS_MeshElement* closestFace = 0;
2432 for ( size_t i = 0; i < data._edges.size(); ++i )
2434 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2436 if ( distToIntersection > dist )
2438 distToIntersection = dist;
2441 closestFace = intFace;
2448 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2449 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2450 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2451 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2452 << ") distance = " << distToIntersection<< endl;
2459 //================================================================================
2461 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2462 * _LayerEdge's to be in a consequent order
2464 //================================================================================
2466 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2469 Handle(Geom_Surface)& surface,
2470 const TopoDS_Face& F,
2471 SMESH_MesherHelper& helper)
2473 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2475 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2477 if ( i2curve == _edge2curve.end() )
2479 // sort _LayerEdge's by position on the EDGE
2481 map< double, _LayerEdge* > u2edge;
2482 for ( int i = iFrom; i < iTo; ++i )
2483 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2485 ASSERT( u2edge.size() == iTo - iFrom );
2486 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2487 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2488 _edges[i] = u2e->second;
2490 // set _2neibors according to the new order
2491 for ( int i = iFrom; i < iTo-1; ++i )
2492 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2493 _edges[i]->_2neibors->reverse();
2494 if ( u2edge.size() > 1 &&
2495 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2496 _edges[iTo-1]->_2neibors->reverse();
2499 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2501 TopLoc_Location loc; double f,l;
2503 Handle(Geom_Line) line;
2504 Handle(Geom_Circle) circle;
2505 bool isLine, isCirc;
2506 if ( F.IsNull() ) // 3D case
2508 // check if the EDGE is a line
2509 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2510 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2511 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2513 line = Handle(Geom_Line)::DownCast( curve );
2514 circle = Handle(Geom_Circle)::DownCast( curve );
2515 isLine = (!line.IsNull());
2516 isCirc = (!circle.IsNull());
2518 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2521 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2522 while ( nIt->more() )
2523 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2524 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2526 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2527 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2528 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2529 for ( int i = 0; i < 3 && !isLine; ++i )
2530 isLine = ( size.Coord( i+1 ) <= lineTol );
2532 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2539 // check if the EDGE is a line
2540 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2541 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2542 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2544 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2545 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2546 isLine = (!line2d.IsNull());
2547 isCirc = (!circle2d.IsNull());
2549 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2552 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2553 while ( nIt->more() )
2554 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2555 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2557 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2558 for ( int i = 0; i < 2 && !isLine; ++i )
2559 isLine = ( size.Coord( i+1 ) <= lineTol );
2561 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2567 line = new Geom_Line( gp::OX() ); // only type does matter
2571 gp_Pnt2d p = circle2d->Location();
2572 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2573 circle = new Geom_Circle( ax, 1.); // only center position does matter
2577 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2585 return i2curve->second;
2588 //================================================================================
2590 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2592 //================================================================================
2594 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2597 Handle(Geom_Surface)& surface,
2598 const TopoDS_Face& F,
2599 SMESH_MesherHelper& helper)
2601 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2602 helper.GetMeshDS());
2603 TopoDS_Edge E = TopoDS::Edge( S );
2605 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2606 if ( curve.IsNull() ) return false;
2608 // compute a relative length of segments
2609 vector< double > len( iTo-iFrom+1 );
2611 double curLen, prevLen = len[0] = 1.0;
2612 for ( int i = iFrom; i < iTo; ++i )
2614 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2615 len[i-iFrom+1] = len[i-iFrom] + curLen;
2620 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2622 if ( F.IsNull() ) // 3D
2624 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2625 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2626 for ( int i = iFrom; i < iTo; ++i )
2628 double r = len[i-iFrom] / len.back();
2629 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2630 data._edges[i]->_pos.back() = newPos;
2631 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2632 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2633 dumpMove( tgtNode );
2638 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2639 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2640 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2641 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2643 int iPeriodic = helper.GetPeriodicIndex();
2644 if ( iPeriodic == 1 || iPeriodic == 2 )
2646 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2647 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2648 std::swap( uv0, uv1 );
2651 const gp_XY rangeUV = uv1 - uv0;
2652 for ( int i = iFrom; i < iTo; ++i )
2654 double r = len[i-iFrom] / len.back();
2655 gp_XY newUV = uv0 + r * rangeUV;
2656 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2658 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2659 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2660 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2661 dumpMove( tgtNode );
2663 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2664 pos->SetUParameter( newUV.X() );
2665 pos->SetVParameter( newUV.Y() );
2671 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2673 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2674 gp_Pnt center3D = circle->Location();
2676 if ( F.IsNull() ) // 3D
2678 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2679 data._edges[iTo-1]->_2neibors->_nodes[1] )
2680 return true; // closed EDGE - nothing to do
2682 return false; // TODO ???
2686 const gp_XY center( center3D.X(), center3D.Y() );
2688 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2689 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2690 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2691 gp_Vec2d vec0( center, uv0 );
2692 gp_Vec2d vecM( center, uvM );
2693 gp_Vec2d vec1( center, uv1 );
2694 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2695 double uMidl = vec0.Angle( vecM );
2696 if ( uLast * uMidl < 0. )
2697 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2698 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2700 gp_Ax2d axis( center, vec0 );
2701 gp_Circ2d circ( axis, radius );
2702 for ( int i = iFrom; i < iTo; ++i )
2704 double newU = uLast * len[i-iFrom] / len.back();
2705 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2706 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2708 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2709 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2710 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2711 dumpMove( tgtNode );
2713 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2714 pos->SetUParameter( newUV.X() );
2715 pos->SetVParameter( newUV.Y() );
2724 //================================================================================
2726 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2727 * _LayerEdge's on neighbor EDGE's
2729 //================================================================================
2731 bool _ViscousBuilder::updateNormals( _SolidData& data,
2732 SMESH_MesherHelper& helper )
2734 // make temporary quadrangles got by extrusion of
2735 // mesh edges along _LayerEdge._normal's
2737 vector< const SMDS_MeshElement* > tmpFaces;
2739 set< SMESH_TLink > extrudedLinks; // contains target nodes
2740 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2742 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2743 for ( size_t i = 0; i < data._edges.size(); ++i )
2745 _LayerEdge* edge = data._edges[i];
2746 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2747 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2748 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2750 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2751 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2752 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2753 if ( !link_isnew.second )
2755 extrudedLinks.erase( link_isnew.first );
2756 continue; // already extruded and will no more encounter
2758 // look for a _LayerEdge containg tgt2
2759 // _LayerEdge* neiborEdge = 0;
2760 // size_t di = 0; // check _edges[i+di] and _edges[i-di]
2761 // while ( !neiborEdge && ++di <= data._edges.size() )
2763 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2764 // neiborEdge = data._edges[i+di];
2765 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2766 // neiborEdge = data._edges[i-di];
2768 // if ( !neiborEdge )
2769 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2770 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2772 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2773 tmpFaces.push_back( f );
2775 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2776 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2777 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2782 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2783 // Perform two loops on _LayerEdge on EDGE's:
2784 // 1) to find and fix intersection
2785 // 2) to check that no new intersection appears as result of 1)
2787 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2789 auto_ptr<SMESH_ElementSearcher> searcher
2790 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
2792 // 1) Find intersections
2794 const SMDS_MeshElement* face;
2795 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2796 TLEdge2LEdgeSet edge2CloseEdge;
2798 const double eps = data._epsilon * data._epsilon;
2799 for ( size_t i = 0; i < data._edges.size(); ++i )
2801 _LayerEdge* edge = data._edges[i];
2802 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2803 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2805 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2806 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2807 ee.insert( f->_le1 );
2808 ee.insert( f->_le2 );
2809 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2810 edge2CloseEdge[ f->_le1 ].insert( edge );
2811 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2812 edge2CloseEdge[ f->_le2 ].insert( edge );
2816 // Set _LayerEdge._normal
2818 if ( !edge2CloseEdge.empty() )
2820 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2822 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2823 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2825 _LayerEdge* edge1 = e2ee->first;
2826 _LayerEdge* edge2 = 0;
2827 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2829 // find EDGEs the edges reside
2831 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2832 if ( S.ShapeType() != TopAbs_EDGE )
2833 continue; // TODO: find EDGE by VERTEX
2834 E1 = TopoDS::Edge( S );
2835 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2836 while ( E2.IsNull() && eIt != ee.end())
2838 _LayerEdge* e2 = *eIt++;
2839 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2840 if ( S.ShapeType() == TopAbs_EDGE )
2841 E2 = TopoDS::Edge( S ), edge2 = e2;
2843 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2845 // find 3 FACEs sharing 2 EDGEs
2847 TopoDS_Face FF1[2], FF2[2];
2848 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2849 while ( fIt->more() && FF1[1].IsNull())
2851 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2852 if ( helper.IsSubShape( *F, data._solid))
2853 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2855 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2856 while ( fIt->more() && FF2[1].IsNull())
2858 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2859 if ( helper.IsSubShape( *F, data._solid))
2860 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2862 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2863 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2864 std::swap( FF1[0], FF1[1] );
2865 if ( FF2[0].IsSame( FF1[0]) )
2866 std::swap( FF2[0], FF2[1] );
2867 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2870 // // get a new normal for edge1
2872 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2873 if ( edge1->_cosin < 0 )
2874 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2875 if ( edge2->_cosin < 0 )
2876 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2877 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2878 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2879 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2880 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2881 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2882 // newNorm.Normalize();
2884 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2885 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2886 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2887 newNorm.Normalize();
2889 edge1->_normal = newNorm.XYZ();
2891 // update data of edge1 depending on _normal
2892 const SMDS_MeshNode *n1, *n2;
2893 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2894 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2895 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2897 edge1->SetDataByNeighbors( n1, n2, helper );
2899 if ( edge1->_cosin < 0 )
2902 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2903 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2904 edge1->SetCosin( cos( angle ));
2906 // limit data._stepSize
2907 if ( edge1->_cosin > 0.1 )
2909 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2910 while ( fIt->more() )
2911 limitStepSize( data, fIt->next(), edge1->_cosin );
2913 // set new XYZ of target node
2914 edge1->InvalidateStep( 1 );
2916 edge1->SetNewLength( data._stepSize, helper );
2919 // Update normals and other dependent data of not intersecting _LayerEdge's
2920 // neighboring the intersecting ones
2922 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2924 _LayerEdge* edge1 = e2ee->first;
2925 if ( !edge1->_2neibors )
2927 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2929 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2930 if ( edge2CloseEdge.count ( neighbor ))
2931 continue; // j-th neighbor is also intersected
2932 _LayerEdge* prevEdge = edge1;
2933 const int nbSteps = 6;
2934 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2936 if ( !neighbor->_2neibors )
2937 break; // neighbor is on VERTEX
2939 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2940 if ( nextEdge == prevEdge )
2941 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2942 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2943 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2944 double r = double(step-1)/nbSteps;
2945 if ( !nextEdge->_2neibors )
2948 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2949 newNorm.Normalize();
2951 neighbor->_normal = newNorm;
2952 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2953 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2955 neighbor->InvalidateStep( 1 );
2957 neighbor->SetNewLength( data._stepSize, helper );
2959 // goto the next neighbor
2960 prevEdge = neighbor;
2961 neighbor = nextEdge;
2967 // 2) Check absence of intersections
2970 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
2976 //================================================================================
2978 * \brief Looks for intersection of it's last segment with faces
2979 * \param distance - returns shortest distance from the last node to intersection
2981 //================================================================================
2983 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2985 const double& epsilon,
2986 const SMDS_MeshElement** face)
2988 vector< const SMDS_MeshElement* > suspectFaces;
2990 gp_Ax1 lastSegment = LastSegment(segLen);
2991 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2993 bool segmentIntersected = false;
2994 distance = Precision::Infinite();
2995 int iFace = -1; // intersected face
2996 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2998 const SMDS_MeshElement* face = suspectFaces[j];
2999 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3000 face->GetNodeIndex( _nodes[0] ) >= 0 )
3001 continue; // face sharing _LayerEdge node
3002 const int nbNodes = face->NbCornerNodes();
3003 bool intFound = false;
3005 SMDS_MeshElement::iterator nIt = face->begin_nodes();
3008 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3012 const SMDS_MeshNode* tria[3];
3015 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3018 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3024 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3025 segmentIntersected = true;
3026 if ( distance > dist )
3027 distance = dist, iFace = j;
3030 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3031 // if ( distance && iFace > -1 )
3033 // // distance is used to limit size of inflation step which depends on
3034 // // whether the intersected face bears viscous layers or not
3035 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3039 if ( segmentIntersected )
3042 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3043 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3044 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3045 << ", intersection with face ("
3046 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3047 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3048 << ") distance = " << distance - segLen<< endl;
3054 return segmentIntersected;
3057 //================================================================================
3059 * \brief Returns size and direction of the last segment
3061 //================================================================================
3063 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3065 // find two non-coincident positions
3066 gp_XYZ orig = _pos.back();
3068 int iPrev = _pos.size() - 2;
3069 while ( iPrev >= 0 )
3071 dir = orig - _pos[iPrev];
3072 if ( dir.SquareModulus() > 1e-100 )
3082 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3083 segDir.SetDirection( _normal );
3088 gp_Pnt pPrev = _pos[ iPrev ];
3089 if ( !_sWOL.IsNull() )
3091 TopLoc_Location loc;
3092 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3095 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3096 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3100 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3101 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3103 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3105 segDir.SetLocation( pPrev );
3106 segDir.SetDirection( dir );
3107 segLen = dir.Modulus();
3113 //================================================================================
3115 * \brief Test intersection of the last segment with a given triangle
3116 * using Moller-Trumbore algorithm
3117 * Intersection is detected if distance to intersection is less than _LayerEdge._len
3119 //================================================================================
3121 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
3122 const SMDS_MeshNode* n0,
3123 const SMDS_MeshNode* n1,
3124 const SMDS_MeshNode* n2,
3126 const double& EPSILON) const
3128 //const double EPSILON = 1e-6;
3130 gp_XYZ orig = lastSegment.Location().XYZ();
3131 gp_XYZ dir = lastSegment.Direction().XYZ();
3133 SMESH_TNodeXYZ vert0( n0 );
3134 SMESH_TNodeXYZ vert1( n1 );
3135 SMESH_TNodeXYZ vert2( n2 );
3137 /* calculate distance from vert0 to ray origin */
3138 gp_XYZ tvec = orig - vert0;
3140 if ( tvec * dir > EPSILON )
3141 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3144 gp_XYZ edge1 = vert1 - vert0;
3145 gp_XYZ edge2 = vert2 - vert0;
3147 /* begin calculating determinant - also used to calculate U parameter */
3148 gp_XYZ pvec = dir ^ edge2;
3150 /* if determinant is near zero, ray lies in plane of triangle */
3151 double det = edge1 * pvec;
3153 if (det > -EPSILON && det < EPSILON)
3155 double inv_det = 1.0 / det;
3157 /* calculate U parameter and test bounds */
3158 double u = ( tvec * pvec ) * inv_det;
3159 if (u < 0.0 || u > 1.0)
3162 /* prepare to test V parameter */
3163 gp_XYZ qvec = tvec ^ edge1;
3165 /* calculate V parameter and test bounds */
3166 double v = (dir * qvec) * inv_det;
3167 if ( v < 0.0 || u + v > 1.0 )
3170 /* calculate t, ray intersects triangle */
3171 t = (edge2 * qvec) * inv_det;
3173 // if (det < EPSILON)
3176 // /* calculate distance from vert0 to ray origin */
3177 // gp_XYZ tvec = orig - vert0;
3179 // /* calculate U parameter and test bounds */
3180 // double u = tvec * pvec;
3181 // if (u < 0.0 || u > det)
3184 // /* prepare to test V parameter */
3185 // gp_XYZ qvec = tvec ^ edge1;
3187 // /* calculate V parameter and test bounds */
3188 // double v = dir * qvec;
3189 // if (v < 0.0 || u + v > det)
3192 // /* calculate t, scale parameters, ray intersects triangle */
3193 // double t = edge2 * qvec;
3194 // double inv_det = 1.0 / det;
3202 //================================================================================
3204 * \brief Perform smooth of _LayerEdge's based on EDGE's
3205 * \retval bool - true if node has been moved
3207 //================================================================================
3209 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3210 const TopoDS_Face& F,
3211 SMESH_MesherHelper& helper)
3213 ASSERT( IsOnEdge() );
3215 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3216 SMESH_TNodeXYZ oldPos( tgtNode );
3217 double dist01, distNewOld;
3219 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3220 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3221 dist01 = p0.Distance( _2neibors->_nodes[1] );
3223 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3224 double lenDelta = 0;
3227 //lenDelta = _curvature->lenDelta( _len );
3228 lenDelta = _curvature->lenDeltaByDist( dist01 );
3229 newPos.ChangeCoord() += _normal * lenDelta;
3232 distNewOld = newPos.Distance( oldPos );
3236 if ( _2neibors->_plnNorm )
3238 // put newPos on the plane defined by source node and _plnNorm
3239 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3240 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3241 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3243 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3244 _pos.back() = newPos.XYZ();
3248 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3249 gp_XY uv( Precision::Infinite(), 0 );
3250 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3251 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3253 newPos = surface->Value( uv.X(), uv.Y() );
3254 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3257 if ( _curvature && lenDelta < 0 )
3259 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3260 _len -= prevPos.Distance( oldPos );
3261 _len += prevPos.Distance( newPos );
3263 bool moved = distNewOld > dist01/50;
3265 dumpMove( tgtNode ); // debug
3270 //================================================================================
3272 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3273 * \retval bool - true if _tgtNode has been moved
3275 //================================================================================
3277 bool _LayerEdge::Smooth(int& badNb)
3279 if ( _simplices.size() < 2 )
3280 return false; // _LayerEdge inflated along EDGE or FACE
3282 // compute new position for the last _pos
3283 gp_XYZ newPos (0,0,0);
3284 for ( size_t i = 0; i < _simplices.size(); ++i )
3285 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3286 newPos /= _simplices.size();
3289 newPos += _normal * _curvature->lenDelta( _len );
3291 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3292 // if ( _cosin < -0.1)
3294 // // Avoid decreasing length of edge on concave surface
3295 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3296 // gp_Vec newMove( prevPos, newPos );
3297 // newPos = _pos.back() + newMove.XYZ();
3299 // else if ( _cosin > 0.3 )
3301 // // Avoid increasing length of edge too much
3304 // count quality metrics (orientation) of tetras around _tgtNode
3306 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3307 for ( size_t i = 0; i < _simplices.size(); ++i )
3308 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3311 for ( size_t i = 0; i < _simplices.size(); ++i )
3312 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3314 if ( nbOkAfter < nbOkBefore )
3317 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3319 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3320 _len += prevPos.Distance(newPos);
3322 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3323 _pos.back() = newPos;
3325 badNb += _simplices.size() - nbOkAfter;
3332 //================================================================================
3334 * \brief Add a new segment to _LayerEdge during inflation
3336 //================================================================================
3338 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3340 if ( _len - len > -1e-6 )
3342 _pos.push_back( _pos.back() );
3346 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3347 SMESH_TNodeXYZ oldXYZ( n );
3348 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3349 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3351 _pos.push_back( nXYZ );
3353 if ( !_sWOL.IsNull() )
3356 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3358 double u = Precision::Infinite(); // to force projection w/o distance check
3359 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3360 _pos.back().SetCoord( u, 0, 0 );
3361 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3362 pos->SetUParameter( u );
3366 gp_XY uv( Precision::Infinite(), 0 );
3367 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3368 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3369 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3370 pos->SetUParameter( uv.X() );
3371 pos->SetVParameter( uv.Y() );
3373 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3375 dumpMove( n ); //debug
3378 //================================================================================
3380 * \brief Remove last inflation step
3382 //================================================================================
3384 void _LayerEdge::InvalidateStep( int curStep )
3386 if ( _pos.size() > curStep )
3388 _pos.resize( curStep );
3389 gp_Pnt nXYZ = _pos.back();
3390 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3391 if ( !_sWOL.IsNull() )
3393 TopLoc_Location loc;
3394 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3396 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3397 pos->SetUParameter( nXYZ.X() );
3399 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3400 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3404 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3405 pos->SetUParameter( nXYZ.X() );
3406 pos->SetVParameter( nXYZ.Y() );
3407 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3408 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3411 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3416 //================================================================================
3418 * \brief Create layers of prisms
3420 //================================================================================
3422 bool _ViscousBuilder::refine(_SolidData& data)
3424 SMESH_MesherHelper helper( *_mesh );
3425 helper.SetSubShape( data._solid );
3426 helper.SetElementsOnShape(false);
3428 Handle(Geom_Curve) curve;
3429 Handle(Geom_Surface) surface;
3430 TopoDS_Edge geomEdge;
3431 TopoDS_Face geomFace;
3432 TopLoc_Location loc;
3433 double f,l, u/*, distXYZ[4]*/;
3437 for ( size_t i = 0; i < data._edges.size(); ++i )
3439 _LayerEdge& edge = *data._edges[i];
3441 // get accumulated length of segments
3442 vector< double > segLen( edge._pos.size() );
3444 for ( size_t j = 1; j < edge._pos.size(); ++j )
3445 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3447 // allocate memory for new nodes if it is not yet refined
3448 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3449 if ( edge._nodes.size() == 2 )
3451 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3453 edge._nodes.back() = tgtNode;
3455 if ( !edge._sWOL.IsNull() )
3457 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3458 // restore position of the last node
3462 geomEdge = TopoDS::Edge( edge._sWOL );
3463 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3464 // double u = helper.GetNodeU( tgtNode );
3465 // p = curve->Value( u );
3469 geomFace = TopoDS::Face( edge._sWOL );
3470 surface = BRep_Tool::Surface( geomFace, loc );
3471 // gp_XY uv = helper.GetNodeUV( tgtNode );
3472 // p = surface->Value( uv.X(), uv.Y() );
3474 // p.Transform( loc );
3475 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3477 // calculate height of the first layer
3479 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3480 const double f = data._hyp->GetStretchFactor();
3481 const int N = data._hyp->GetNumberLayers();
3482 const double fPowN = pow( f, N );
3483 if ( fPowN - 1 <= numeric_limits<double>::min() )
3486 h0 = T * ( f - 1 )/( fPowN - 1 );
3488 const double zeroLen = std::numeric_limits<double>::min();
3490 // create intermediate nodes
3491 double hSum = 0, hi = h0/f;
3493 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3495 // compute an intermediate position
3498 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3500 int iPrevSeg = iSeg-1;
3501 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3503 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3504 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3506 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3507 if ( !edge._sWOL.IsNull() )
3509 // compute XYZ by parameters <pos>
3513 pos = curve->Value( u ).Transformed(loc);
3517 uv.SetCoord( pos.X(), pos.Y() );
3518 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3521 // create or update the node
3524 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3525 if ( !edge._sWOL.IsNull() )
3528 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3530 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3534 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3539 if ( !edge._sWOL.IsNull() )
3541 // make average pos from new and current parameters
3544 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3545 pos = curve->Value( u ).Transformed(loc);
3549 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3550 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3553 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3558 if ( !getMeshDS()->IsEmbeddedMode() )
3559 // Log node movement
3560 for ( size_t i = 0; i < data._edges.size(); ++i )
3562 _LayerEdge& edge = *data._edges[i];
3563 SMESH_TNodeXYZ p ( edge._nodes.back() );
3564 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3567 // TODO: make quadratic prisms and polyhedrons(?)
3569 helper.SetElementsOnShape(true);
3571 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3572 for ( ; exp.More(); exp.Next() )
3574 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3576 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3577 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3578 vector< vector<const SMDS_MeshNode*>* > nnVec;
3579 while ( fIt->more() )
3581 const SMDS_MeshElement* face = fIt->next();
3582 int nbNodes = face->NbCornerNodes();
3583 nnVec.resize( nbNodes );
3584 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3585 for ( int iN = 0; iN < nbNodes; ++iN )
3587 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3588 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3591 int nbZ = nnVec[0]->size();
3595 for ( int iZ = 1; iZ < nbZ; ++iZ )
3596 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3597 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3600 for ( int iZ = 1; iZ < nbZ; ++iZ )
3601 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3602 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3603 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3604 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3607 return error("Not supported type of element", data._index);
3614 //================================================================================
3616 * \brief Shrink 2D mesh on faces to let space for inflated layers
3618 //================================================================================
3620 bool _ViscousBuilder::shrink()
3622 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3623 // inflated along FACE or EDGE)
3624 map< TGeomID, _SolidData* > f2sdMap;
3625 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3627 _SolidData& data = _sdVec[i];
3628 TopTools_MapOfShape FFMap;
3629 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3630 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3631 if ( s2s->second.ShapeType() == TopAbs_FACE )
3633 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3635 if ( FFMap.Add( (*s2s).second ))
3636 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3637 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3638 // by StdMeshers_QuadToTriaAdaptor
3639 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3641 SMESH_ProxyMesh::SubMesh* proxySub =
3642 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3643 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3644 while ( fIt->more() )
3645 proxySub->AddElement( fIt->next() );
3646 // as a result 3D algo will use elements from proxySub and not from smDS
3651 SMESH_MesherHelper helper( *_mesh );
3652 helper.ToFixNodeParameters( true );
3655 map< TGeomID, _Shrinker1D > e2shrMap;
3657 // loop on FACES to srink mesh on
3658 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3659 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3661 _SolidData& data = *f2sd->second;
3662 TNode2Edge& n2eMap = data._n2eMap;
3663 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3665 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3667 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3668 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3670 helper.SetSubShape(F);
3672 // ===========================
3673 // Prepare data for shrinking
3674 // ===========================
3676 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3677 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3678 vector < const SMDS_MeshNode* > smoothNodes;
3680 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3681 while ( nIt->more() )
3683 const SMDS_MeshNode* n = nIt->next();
3684 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3685 smoothNodes.push_back( n );
3688 // Find out face orientation
3690 const set<TGeomID> ignoreShapes;
3692 if ( !smoothNodes.empty() )
3694 vector<_Simplex> simplices;
3695 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3696 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3697 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3698 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3699 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3703 // Find _LayerEdge's inflated along F
3704 vector< _LayerEdge* > lEdges;
3706 SMESH_subMeshIteratorPtr subIt =
3707 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3708 while ( subIt->more() )
3710 SMESH_subMesh* sub = subIt->next();
3711 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3712 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3714 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3715 while ( nIt->more() )
3717 _LayerEdge* edge = n2eMap[ nIt->next() ];
3718 lEdges.push_back( edge );
3719 prepareEdgeToShrink( *edge, F, helper, smDS );
3724 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3725 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3726 while ( fIt->more() )
3727 if ( const SMDS_MeshElement* f = fIt->next() )
3728 dumpChangeNodes( f );
3730 // Replace source nodes by target nodes in mesh faces to shrink
3731 const SMDS_MeshNode* nodes[20];
3732 for ( size_t i = 0; i < lEdges.size(); ++i )
3734 _LayerEdge& edge = *lEdges[i];
3735 const SMDS_MeshNode* srcNode = edge._nodes[0];
3736 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3737 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3738 while ( fIt->more() )
3740 const SMDS_MeshElement* f = fIt->next();
3741 if ( !smDS->Contains( f ))
3743 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
3744 for ( int iN = 0; nIt->more(); ++iN )
3746 const SMDS_MeshNode* n = nIt->next();
3747 nodes[iN] = ( n == srcNode ? tgtNode : n );
3749 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3753 // find out if a FACE is concave
3754 const bool isConcaveFace = isConcave( F, helper );
3756 // Create _SmoothNode's on face F
3757 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3759 const bool sortSimplices = isConcaveFace;
3760 for ( size_t i = 0; i < smoothNodes.size(); ++i )
3762 const SMDS_MeshNode* n = smoothNodes[i];
3763 nodesToSmooth[ i ]._node = n;
3764 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3765 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
3766 // fix up incorrect uv of nodes on the FACE
3767 helper.GetNodeUV( F, n, 0, &isOkUV);
3771 //if ( nodesToSmooth.empty() ) continue;
3773 // Find EDGE's to shrink and set simpices to LayerEdge's
3774 set< _Shrinker1D* > eShri1D;
3776 for ( size_t i = 0; i < lEdges.size(); ++i )
3778 _LayerEdge* edge = lEdges[i];
3779 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3781 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3782 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3783 eShri1D.insert( & srinker );
3784 srinker.AddEdge( edge, helper );
3785 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3786 // restore params of nodes on EGDE if the EDGE has been already
3787 // srinked while srinking another FACE
3788 srinker.RestoreParams();
3790 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
3794 bool toFixTria = false; // to improve quality of trias by diagonal swap
3795 if ( isConcaveFace )
3797 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3798 if ( hasTria != hasQuad ) {
3799 toFixTria = hasTria;
3802 set<int> nbNodesSet;
3803 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3804 while ( fIt->more() && nbNodesSet.size() < 2 )
3805 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3806 toFixTria = ( *nbNodesSet.begin() == 3 );
3810 // ==================
3811 // Perform shrinking
3812 // ==================
3814 bool shrinked = true;
3815 int badNb, shriStep=0, smooStep=0;
3816 _SmoothNode::SmoothType smoothType
3817 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
3821 // Move boundary nodes (actually just set new UV)
3822 // -----------------------------------------------
3823 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
3825 for ( size_t i = 0; i < lEdges.size(); ++i )
3827 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3831 // Move nodes on EDGE's
3832 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
3833 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3834 for ( ; shr != eShri1D.end(); ++shr )
3835 (*shr)->Compute( /*set3D=*/false, helper );
3838 // -----------------
3839 int nbNoImpSteps = 0;
3842 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3844 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3846 int oldBadNb = badNb;
3849 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3851 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3852 smoothType, /*set3D=*/isConcaveFace);
3854 if ( badNb < oldBadNb )
3862 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3863 if ( shriStep > 200 )
3864 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
3866 // Fix narrow triangles by swapping diagonals
3867 // ---------------------------------------
3870 set<const SMDS_MeshNode*> usedNodes;
3871 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
3873 // update working data
3874 set<const SMDS_MeshNode*>::iterator n;
3875 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
3877 n = usedNodes.find( nodesToSmooth[ i ]._node );
3878 if ( n != usedNodes.end())
3880 getSimplices( nodesToSmooth[ i ]._node,
3881 nodesToSmooth[ i ]._simplices,
3883 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
3884 usedNodes.erase( n );
3887 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
3889 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
3890 if ( n != usedNodes.end())
3892 getSimplices( lEdges[i]->_nodes.back(),
3893 lEdges[i]->_simplices,
3895 usedNodes.erase( n );
3899 } // while ( shrinked )
3901 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3902 bool isStructuredFixed = false;
3903 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
3904 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
3905 if ( !isStructuredFixed )
3907 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
3908 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
3910 for ( int st = 3; st; --st )
3913 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
3914 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
3915 case 3: smoothType = _SmoothNode::ANGULAR; break;
3917 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3918 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3920 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3921 smoothType,/*set3D=*/st==1 );
3926 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3927 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3929 if ( !getMeshDS()->IsEmbeddedMode() )
3930 // Log node movement
3931 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3933 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3934 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3937 } // loop on FACES to srink mesh on
3940 // Replace source nodes by target nodes in shrinked mesh edges
3942 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3943 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3944 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3949 //================================================================================
3951 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3953 //================================================================================
3955 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3956 const TopoDS_Face& F,
3957 SMESH_MesherHelper& helper,
3958 const SMESHDS_SubMesh* faceSubMesh)
3960 const SMDS_MeshNode* srcNode = edge._nodes[0];
3961 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3965 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3967 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3968 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3969 gp_Vec2d uvDir( srcUV, tgtUV );
3970 double uvLen = uvDir.Magnitude();
3972 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3975 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3976 // vector<const SMDS_MeshElement*> faces;
3977 // multimap< double, const SMDS_MeshNode* > proj2node;
3978 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3979 // while ( fIt->more() )
3981 // const SMDS_MeshElement* f = fIt->next();
3982 // if ( faceSubMesh->Contains( f ))
3983 // faces.push_back( f );
3985 // for ( size_t i = 0; i < faces.size(); ++i )
3987 // const int nbNodes = faces[i]->NbCornerNodes();
3988 // for ( int j = 0; j < nbNodes; ++j )
3990 // const SMDS_MeshNode* n = faces[i]->GetNode(j);
3991 // if ( n == srcNode ) continue;
3992 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3993 // ( faces.size() > 1 || nbNodes > 3 ))
3995 // gp_Pnt2d uv = helper.GetNodeUV( F, n );
3996 // gp_Vec2d uvDirN( srcUV, uv );
3997 // double proj = uvDirN * uvDir;
3998 // proj2node.insert( make_pair( proj, n ));
4002 // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4003 // const double minProj = p2n->first;
4004 // const double projThreshold = 1.1 * uvLen;
4005 // if ( minProj > projThreshold )
4007 // // tgtNode is located so that it does not make faces with wrong orientation
4010 edge._pos.resize(1);
4011 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4013 // store most risky nodes in _simplices
4014 // p2nEnd = proj2node.lower_bound( projThreshold );
4015 // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4016 // edge._simplices.resize( nbSimpl );
4017 // for ( int i = 0; i < nbSimpl; ++i )
4019 // edge._simplices[i]._nPrev = p2n->second;
4020 // if ( ++p2n != p2nEnd )
4021 // edge._simplices[i]._nNext = p2n->second;
4023 // set UV of source node to target node
4024 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4025 pos->SetUParameter( srcUV.X() );
4026 pos->SetVParameter( srcUV.Y() );
4028 else // _sWOL is TopAbs_EDGE
4030 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4031 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4032 if ( !edgeSM || edgeSM->NbElements() == 0 )
4033 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4035 const SMDS_MeshNode* n2 = 0;
4036 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4037 while ( eIt->more() && !n2 )
4039 const SMDS_MeshElement* e = eIt->next();
4040 if ( !edgeSM->Contains(e)) continue;
4041 n2 = e->GetNode( 0 );
4042 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4045 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4047 double uSrc = helper.GetNodeU( E, srcNode, n2 );
4048 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4049 double u2 = helper.GetNodeU( E, n2, srcNode );
4051 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4053 // tgtNode is located so that it does not make faces with wrong orientation
4056 edge._pos.resize(1);
4057 edge._pos[0].SetCoord( U_TGT, uTgt );
4058 edge._pos[0].SetCoord( U_SRC, uSrc );
4059 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4061 edge._simplices.resize( 1 );
4062 edge._simplices[0]._nPrev = n2;
4064 // set UV of source node to target node
4065 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4066 pos->SetUParameter( uSrc );
4070 //================================================================================
4072 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4074 //================================================================================
4076 // Compute UV to follow during shrinking
4078 // const SMDS_MeshNode* srcNode = edge._nodes[0];
4079 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
4081 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4082 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4083 // gp_Vec2d uvDir( srcUV, tgtUV );
4084 // double uvLen = uvDir.Magnitude();
4087 // // Select shrinking step such that not to make faces with wrong orientation.
4088 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4089 // const double minStepSize = uvLen / 20;
4090 // double stepSize = uvLen;
4091 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4092 // while ( fIt->more() )
4094 // const SMDS_MeshElement* f = fIt->next();
4095 // if ( !faceSubMesh->Contains( f )) continue;
4096 // const int nbNodes = f->NbCornerNodes();
4097 // for ( int i = 0; i < nbNodes; ++i )
4099 // const SMDS_MeshNode* n = f->GetNode(i);
4100 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4102 // gp_XY uv = helper.GetNodeUV( F, n );
4103 // gp_Vec2d uvDirN( srcUV, uv );
4104 // double proj = uvDirN * uvDir;
4105 // if ( proj < stepSize && proj > minStepSize )
4111 // const int nbSteps = ceil( uvLen / stepSize );
4112 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4113 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4114 // edge._pos.resize( nbSteps );
4115 // edge._pos[0] = tgtUV0;
4116 // for ( int i = 1; i < nbSteps; ++i )
4118 // double r = i / double( nbSteps );
4119 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4124 //================================================================================
4126 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4128 //================================================================================
4130 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
4131 SMESH_MesherHelper& helper,
4134 set<const SMDS_MeshNode*> * involvedNodes)
4136 SMESH::Controls::AspectRatio qualifier;
4137 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4138 const double maxAspectRatio = is2D ? 4. : 2;
4139 NodeCoordHelper xyz( F, helper, is2D );
4141 // find bad triangles
4143 vector< const SMDS_MeshElement* > badTrias;
4144 vector< double > badAspects;
4145 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
4146 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4147 while ( fIt->more() )
4149 const SMDS_MeshElement * f = fIt->next();
4150 if ( f->NbCornerNodes() != 3 ) continue;
4151 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4152 double aspect = qualifier.GetValue( points );
4153 if ( aspect > maxAspectRatio )
4155 badTrias.push_back( f );
4156 badAspects.push_back( aspect );
4161 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4162 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4163 while ( fIt->more() )
4165 const SMDS_MeshElement * f = fIt->next();
4166 if ( f->NbCornerNodes() == 3 )
4167 dumpChangeNodes( f );
4171 if ( badTrias.empty() )
4174 // find couples of faces to swap diagonal
4176 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4177 vector< T2Trias > triaCouples;
4179 TIDSortedElemSet involvedFaces, emptySet;
4180 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4183 double aspRatio [3];
4186 if ( !involvedFaces.insert( badTrias[iTia] ).second )
4188 for ( int iP = 0; iP < 3; ++iP )
4189 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4191 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4192 int bestCouple = -1;
4193 for ( int iSide = 0; iSide < 3; ++iSide )
4195 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4196 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4197 trias [iSide].first = badTrias[iTia];
4198 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4200 if (( ! trias[iSide].second ) ||
4201 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4202 ( ! sm->Contains( trias[iSide].second )))
4205 // aspect ratio of an adjacent tria
4206 for ( int iP = 0; iP < 3; ++iP )
4207 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4208 double aspectInit = qualifier.GetValue( points2 );
4210 // arrange nodes as after diag-swaping
4211 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4212 i3 = helper.WrapIndex( i1-1, 3 );
4214 i3 = helper.WrapIndex( i1+1, 3 );
4216 points1( 1+ iSide ) = points2( 1+ i3 );
4217 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
4219 // aspect ratio after diag-swaping
4220 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4221 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4224 // prevent inversion of a triangle
4225 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4226 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4227 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4230 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4234 if ( bestCouple >= 0 )
4236 triaCouples.push_back( trias[bestCouple] );
4237 involvedFaces.insert ( trias[bestCouple].second );
4241 involvedFaces.erase( badTrias[iTia] );
4244 if ( triaCouples.empty() )
4249 SMESH_MeshEditor editor( helper.GetMesh() );
4250 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4251 for ( size_t i = 0; i < triaCouples.size(); ++i )
4253 dumpChangeNodes( triaCouples[i].first );
4254 dumpChangeNodes( triaCouples[i].second );
4255 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4258 if ( involvedNodes )
4259 for ( size_t i = 0; i < triaCouples.size(); ++i )
4261 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4262 triaCouples[i].first->end_nodes() );
4263 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4264 triaCouples[i].second->end_nodes() );
4267 // just for debug dump resulting triangles
4268 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4269 for ( size_t i = 0; i < triaCouples.size(); ++i )
4271 dumpChangeNodes( triaCouples[i].first );
4272 dumpChangeNodes( triaCouples[i].second );
4276 //================================================================================
4278 * \brief Move target node to it's final position on the FACE during shrinking
4280 //================================================================================
4282 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4283 const TopoDS_Face& F,
4284 SMESH_MesherHelper& helper )
4287 return false; // already at the target position
4289 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4291 if ( _sWOL.ShapeType() == TopAbs_FACE )
4293 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4294 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4295 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4296 const double uvLen = tgtUV.Distance( curUV );
4297 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4299 // Select shrinking step such that not to make faces with wrong orientation.
4300 double stepSize = uvLen;
4301 for ( size_t i = 0; i < _simplices.size(); ++i )
4303 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4304 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4305 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4306 gp_XY dirN = uvN2 - uvN1;
4307 double det = uvDir.Crossed( dirN );
4308 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
4309 gp_XY dirN2Cur = curUV - uvN1;
4310 double step = dirN.Crossed( dirN2Cur ) / det;
4312 stepSize = Min( step, stepSize );
4315 if ( uvLen - stepSize < _len / 200. )
4320 else if ( stepSize > 0 )
4322 newUV = curUV + uvDir.XY() * stepSize * kSafe;
4328 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4329 pos->SetUParameter( newUV.X() );
4330 pos->SetVParameter( newUV.Y() );
4333 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4334 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4335 dumpMove( tgtNode );
4338 else // _sWOL is TopAbs_EDGE
4340 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4341 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4342 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4344 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4345 const double uSrc = _pos[0].Coord( U_SRC );
4346 const double lenTgt = _pos[0].Coord( LEN_TGT );
4348 double newU = _pos[0].Coord( U_TGT );
4349 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4355 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4357 tgtPos->SetUParameter( newU );
4359 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4360 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4361 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4362 dumpMove( tgtNode );
4368 //================================================================================
4370 * \brief Perform smooth on the FACE
4371 * \retval bool - true if the node has been moved
4373 //================================================================================
4375 bool _SmoothNode::Smooth(int& badNb,
4376 Handle(Geom_Surface)& surface,
4377 SMESH_MesherHelper& helper,
4378 const double refSign,
4382 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4384 // get uv of surrounding nodes
4385 vector<gp_XY> uv( _simplices.size() );
4386 for ( size_t i = 0; i < _simplices.size(); ++i )
4387 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4389 // compute new UV for the node
4391 if ( how == TFI && _simplices.size() == 4 )
4394 for ( size_t i = 0; i < _simplices.size(); ++i )
4395 if ( _simplices[i]._nOpp )
4396 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4398 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4400 newPos = helper.calcTFI ( 0.5, 0.5,
4401 corners[0], corners[1], corners[2], corners[3],
4402 uv[1], uv[2], uv[3], uv[0] );
4404 else if ( how == ANGULAR )
4406 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4408 else if ( how == CENTROIDAL && _simplices.size() > 3 )
4410 // average centers of diagonals wieghted with their reciprocal lengths
4411 if ( _simplices.size() == 4 )
4413 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4414 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4415 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4419 double sumWeight = 0;
4420 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4421 for ( int i = 0; i < nb; ++i )
4424 int iTo = i + _simplices.size() - 1;
4425 for ( int j = iFrom; j < iTo; ++j )
4427 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4428 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4430 newPos += w * ( uv[i]+uv[i2] );
4433 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4439 for ( size_t i = 0; i < _simplices.size(); ++i )
4441 newPos /= _simplices.size();
4444 // count quality metrics (orientation) of triangles around the node
4446 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4447 for ( size_t i = 0; i < _simplices.size(); ++i )
4448 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4451 for ( size_t i = 0; i < _simplices.size(); ++i )
4452 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4454 if ( nbOkAfter < nbOkBefore )
4456 badNb += _simplices.size() - nbOkBefore;
4460 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4461 pos->SetUParameter( newPos.X() );
4462 pos->SetVParameter( newPos.Y() );
4469 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4470 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4474 badNb += _simplices.size() - nbOkAfter;
4475 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4478 //================================================================================
4480 * \brief Computes new UV using angle based smoothing technic
4482 //================================================================================
4484 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4485 const gp_XY& uvToFix,
4486 const double refSign)
4488 uv.push_back( uv.front() );
4490 vector< gp_XY > edgeDir ( uv.size() );
4491 vector< double > edgeSize( uv.size() );
4492 for ( size_t i = 1; i < edgeDir.size(); ++i )
4494 edgeDir [i-1] = uv[i] - uv[i-1];
4495 edgeSize[i-1] = edgeDir[i-1].Modulus();
4496 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4497 edgeDir[i-1].SetX( 100 );
4499 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4501 edgeDir.back() = edgeDir.front();
4502 edgeSize.back() = edgeSize.front();
4507 for ( size_t i = 1; i < edgeDir.size(); ++i )
4509 if ( edgeDir[i-1].X() > 1. ) continue;
4511 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4512 if ( i == edgeDir.size() ) break;
4514 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4515 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4516 gp_XY bisec = norm1 + norm2;
4517 double bisecSize = bisec.Modulus();
4518 if ( bisecSize < numeric_limits<double>::min() )
4520 bisec = -edgeDir[i1] + edgeDir[i];
4521 bisecSize = bisec.Modulus();
4525 gp_XY dirToN = uvToFix - p;
4526 double distToN = dirToN.Modulus();
4527 if ( bisec * dirToN < 0 )
4530 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4532 sumSize += edgeSize[i1] + edgeSize[i];
4534 newPos /= /*nbEdges * */sumSize;
4538 //================================================================================
4540 * \brief Delete _SolidData
4542 //================================================================================
4544 _SolidData::~_SolidData()
4546 for ( size_t i = 0; i < _edges.size(); ++i )
4548 if ( _edges[i] && _edges[i]->_2neibors )
4549 delete _edges[i]->_2neibors;
4554 //================================================================================
4556 * \brief Add a _LayerEdge inflated along the EDGE
4558 //================================================================================
4560 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4563 if ( _nodes.empty() )
4565 _edges[0] = _edges[1] = 0;
4569 if ( e == _edges[0] || e == _edges[1] )
4571 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4572 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4573 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4574 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4577 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4579 BRep_Tool::Range( E, f,l );
4580 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4581 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4585 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4586 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4588 if ( _nodes.empty() )
4590 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4591 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4593 TopLoc_Location loc;
4594 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4595 GeomAdaptor_Curve aCurve(C, f,l);
4596 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4598 int nbExpectNodes = eSubMesh->NbNodes();
4599 _initU .reserve( nbExpectNodes );
4600 _normPar.reserve( nbExpectNodes );
4601 _nodes .reserve( nbExpectNodes );
4602 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4603 while ( nIt->more() )
4605 const SMDS_MeshNode* node = nIt->next();
4606 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4607 node == tgtNode0 || node == tgtNode1 )
4608 continue; // refinement nodes
4609 _nodes.push_back( node );
4610 _initU.push_back( helper.GetNodeU( E, node ));
4611 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4612 _normPar.push_back( len / totLen );
4617 // remove target node of the _LayerEdge from _nodes
4619 for ( size_t i = 0; i < _nodes.size(); ++i )
4620 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4621 _nodes[i] = 0, nbFound++;
4622 if ( nbFound == _nodes.size() )
4627 //================================================================================
4629 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4631 //================================================================================
4633 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4635 if ( _done || _nodes.empty())
4637 const _LayerEdge* e = _edges[0];
4638 if ( !e ) e = _edges[1];
4641 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4642 ( !_edges[1] || _edges[1]->_pos.empty() ));
4644 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4646 if ( set3D || _done )
4648 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4649 GeomAdaptor_Curve aCurve(C, f,l);
4652 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4654 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4655 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4657 for ( size_t i = 0; i < _nodes.size(); ++i )
4659 if ( !_nodes[i] ) continue;
4660 double len = totLen * _normPar[i];
4661 GCPnts_AbscissaPoint discret( aCurve, len, f );
4662 if ( !discret.IsDone() )
4663 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4664 double u = discret.Parameter();
4665 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4666 pos->SetUParameter( u );
4667 gp_Pnt p = C->Value( u );
4668 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4673 BRep_Tool::Range( E, f,l );
4675 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4677 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4679 for ( size_t i = 0; i < _nodes.size(); ++i )
4681 if ( !_nodes[i] ) continue;
4682 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4683 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4684 pos->SetUParameter( u );
4689 //================================================================================
4691 * \brief Restore initial parameters of nodes on EDGE
4693 //================================================================================
4695 void _Shrinker1D::RestoreParams()
4698 for ( size_t i = 0; i < _nodes.size(); ++i )
4700 if ( !_nodes[i] ) continue;
4701 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4702 pos->SetUParameter( _initU[i] );
4707 //================================================================================
4709 * \brief Replace source nodes by target nodes in shrinked mesh edges
4711 //================================================================================
4713 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4715 const SMDS_MeshNode* nodes[3];
4716 for ( int i = 0; i < 2; ++i )
4718 if ( !_edges[i] ) continue;
4720 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4721 if ( !eSubMesh ) return;
4722 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4723 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4724 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4725 while ( eIt->more() )
4727 const SMDS_MeshElement* e = eIt->next();
4728 if ( !eSubMesh->Contains( e ))
4730 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4731 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4733 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4734 nodes[iN] = ( n == srcNode ? tgtNode : n );
4736 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4741 //================================================================================
4743 * \brief Creates 2D and 1D elements on boundaries of new prisms
4745 //================================================================================
4747 bool _ViscousBuilder::addBoundaryElements()
4749 SMESH_MesherHelper helper( *_mesh );
4751 for ( size_t i = 0; i < _sdVec.size(); ++i )
4753 _SolidData& data = _sdVec[i];
4754 TopTools_IndexedMapOfShape geomEdges;
4755 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4756 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4758 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4760 // Get _LayerEdge's based on E
4762 map< double, const SMDS_MeshNode* > u2nodes;
4763 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4766 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4767 TNode2Edge & n2eMap = data._n2eMap;
4768 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4770 //check if 2D elements are needed on E
4771 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4772 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4773 ledges.push_back( n2e->second );
4775 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4776 continue; // no layers on E
4777 ledges.push_back( n2eMap[ u2n->second ]);
4779 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4780 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4781 int nbSharedPyram = 0;
4782 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4783 while ( vIt->more() )
4785 const SMDS_MeshElement* v = vIt->next();
4786 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4788 if ( nbSharedPyram > 1 )
4789 continue; // not free border of the pyramid
4791 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4792 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4793 continue; // faces already created
4795 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4796 ledges.push_back( n2eMap[ u2n->second ]);
4798 // Find out orientation and type of face to create
4800 bool reverse = false, isOnFace;
4802 map< TGeomID, TopoDS_Shape >::iterator e2f =
4803 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4805 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4807 F = e2f->second.Oriented( TopAbs_FORWARD );
4808 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4809 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4810 reverse = !reverse, F.Reverse();
4811 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
4816 // find FACE with layers sharing E
4817 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4818 while ( fIt->more() && F.IsNull() )
4820 const TopoDS_Shape* pF = fIt->next();
4821 if ( helper.IsSubShape( *pF, data._solid) &&
4822 !data._ignoreFaceIds.count( e2f->first ))
4826 // Find the sub-mesh to add new faces
4827 SMESHDS_SubMesh* sm = 0;
4829 sm = getMeshDS()->MeshElements( F );
4831 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4833 return error("error in addBoundaryElements()", data._index);
4836 const int dj1 = reverse ? 0 : 1;
4837 const int dj2 = reverse ? 1 : 0;
4838 for ( size_t j = 1; j < ledges.size(); ++j )
4840 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4841 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4843 for ( size_t z = 1; z < nn1.size(); ++z )
4844 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4846 for ( size_t z = 1; z < nn1.size(); ++z )
4847 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4851 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4853 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4854 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4856 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4857 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4859 helper.SetSubShape( edge->_sWOL );
4860 helper.SetElementsOnShape( true );
4861 for ( size_t z = 1; z < nn.size(); ++z )
4862 helper.AddEdge( nn[z-1], nn[z] );