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 <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
90 //================================================================================
95 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
98 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
99 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
101 struct _MeshOfSolid : public SMESH_ProxyMesh,
102 public SMESH_subMeshEventListenerData
104 bool _n2nMapComputed;
106 _MeshOfSolid( SMESH_Mesh* mesh)
107 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
109 SMESH_ProxyMesh::setMesh( *mesh );
112 // returns submesh for a geom face
113 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
115 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
116 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
118 void setNode2Node(const SMDS_MeshNode* srcNode,
119 const SMDS_MeshNode* proxyNode,
120 const SMESH_ProxyMesh::SubMesh* subMesh)
122 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
125 //--------------------------------------------------------------------------------
127 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
128 * It is used to clear an inferior dim sub-meshes modified by viscous layers
130 class _ShrinkShapeListener : SMESH_subMeshEventListener
132 _ShrinkShapeListener()
133 : SMESH_subMeshEventListener(/*isDeletable=*/false,
134 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
136 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
137 virtual void ProcessEvent(const int event,
139 SMESH_subMesh* solidSM,
140 SMESH_subMeshEventListenerData* data,
141 const SMESH_Hypothesis* hyp)
143 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
145 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
149 //--------------------------------------------------------------------------------
151 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
152 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
153 * delete the data as soon as it has been used
155 class _ViscousListener : SMESH_subMeshEventListener
158 SMESH_subMeshEventListener(/*isDeletable=*/false,
159 "StdMeshers_ViscousLayers::_ViscousListener") {}
160 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
162 virtual void ProcessEvent(const int event,
164 SMESH_subMesh* subMesh,
165 SMESH_subMeshEventListenerData* data,
166 const SMESH_Hypothesis* hyp)
168 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
170 // delete SMESH_ProxyMesh containing temporary faces
171 subMesh->DeleteEventListener( this );
174 // Finds or creates proxy mesh of the solid
175 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
176 const TopoDS_Shape& solid,
179 if ( !mesh ) return 0;
180 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
181 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
182 if ( !data && toCreate )
184 data = new _MeshOfSolid(mesh);
185 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
186 sm->SetEventListener( Get(), data, sm );
190 // Removes proxy mesh of the solid
191 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
193 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
197 //================================================================================
199 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
200 * the main shape when sub-mesh of the main shape is cleared,
201 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
204 //================================================================================
206 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
208 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
209 SMESH_subMeshEventListenerData* data =
210 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
213 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
214 data->mySubMeshes.end())
215 data->mySubMeshes.push_back( sub );
219 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
220 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
223 //--------------------------------------------------------------------------------
225 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
226 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
227 * The class is used to check validity of face or volumes around a smoothed node;
228 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
232 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
233 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
234 _Simplex(const SMDS_MeshNode* nPrev=0,
235 const SMDS_MeshNode* nNext=0,
236 const SMDS_MeshNode* nOpp=0)
237 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
238 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
240 const double M[3][3] =
241 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
242 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
243 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
244 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
245 + M[0][1]*M[1][2]*M[2][0]
246 + M[0][2]*M[1][0]*M[2][1]
247 - M[0][0]*M[1][2]*M[2][1]
248 - M[0][1]*M[1][0]*M[2][2]
249 - M[0][2]*M[1][1]*M[2][0]);
250 return determinant > 1e-100;
252 bool IsForward(const gp_XY& tgtUV,
253 const SMDS_MeshNode* smoothedNode,
254 const TopoDS_Face& face,
255 SMESH_MesherHelper& helper,
256 const double refSign) const
258 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
259 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
260 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
262 return d*refSign > 1e-100;
264 bool IsNeighbour(const _Simplex& other) const
266 return _nPrev == other._nNext || _nNext == other._nPrev;
269 //--------------------------------------------------------------------------------
271 * Structure used to take into account surface curvature while smoothing
276 double _k; // factor to correct node smoothed position
277 double _h2lenRatio; // avgNormProj / (2*avgDist)
279 static _Curvature* New( double avgNormProj, double avgDist )
282 if ( fabs( avgNormProj / avgDist ) > 1./200 )
285 c->_r = avgDist * avgDist / avgNormProj;
286 c->_k = avgDist * avgDist / c->_r / c->_r;
287 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
288 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
292 double lenDelta(double len) const { return _k * ( _r + len ); }
293 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
296 //--------------------------------------------------------------------------------
298 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
302 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
303 const SMDS_MeshNode* _nodes[2];
304 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
306 double _wgt[2]; // weights of _nodes
307 _LayerEdge* _edges[2];
309 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
312 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
314 std::swap( _nodes[0], _nodes[1] );
315 std::swap( _wgt[0], _wgt[1] );
318 //--------------------------------------------------------------------------------
320 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
321 * and a node of the most internal layer (_nodes.back())
325 vector< const SMDS_MeshNode*> _nodes;
327 gp_XYZ _normal; // to solid surface
328 vector<gp_XYZ> _pos; // points computed during inflation
329 double _len; // length achived with the last inflation step
330 double _cosin; // of angle (_normal ^ surface)
331 double _lenFactor; // to compute _len taking _cosin into account
333 // face or edge w/o layer along or near which _LayerEdge is inflated
335 // simplices connected to the source node (_nodes[0]);
336 // used for smoothing and quality check of _LayerEdge's based on the FACE
337 vector<_Simplex> _simplices;
338 // data for smoothing of _LayerEdge's based on the EDGE
339 _2NearEdges* _2neibors;
341 _Curvature* _curvature;
342 // TODO:: detele _Curvature, _plnNorm
344 void SetNewLength( double len, SMESH_MesherHelper& helper );
345 bool SetNewLength2d( Handle(Geom_Surface)& surface,
346 const TopoDS_Face& F,
347 SMESH_MesherHelper& helper );
348 void SetDataByNeighbors( const SMDS_MeshNode* n1,
349 const SMDS_MeshNode* n2,
350 SMESH_MesherHelper& helper);
351 void InvalidateStep( int curStep );
352 bool Smooth(int& badNb);
353 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
354 const TopoDS_Face& F,
355 SMESH_MesherHelper& helper);
356 bool FindIntersection( SMESH_ElementSearcher& searcher,
358 const double& epsilon,
359 const SMDS_MeshElement** face = 0);
360 bool SegTriaInter( const gp_Ax1& lastSegment,
361 const SMDS_MeshNode* n0,
362 const SMDS_MeshNode* n1,
363 const SMDS_MeshNode* n2,
365 const double& epsilon) const;
366 gp_Ax1 LastSegment(double& segLen) const;
367 bool IsOnEdge() const { return _2neibors; }
368 gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
369 void SetCosin( double cosin );
373 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
375 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
376 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
379 //--------------------------------------------------------------------------------
381 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
383 //--------------------------------------------------------------------------------
385 * \brief Data of a SOLID
390 const StdMeshers_ViscousLayers* _hyp;
391 TopoDS_Shape _hypShape;
392 _MeshOfSolid* _proxyMesh;
393 set<TGeomID> _reversedFaceIds;
394 set<TGeomID> _ignoreFaceIds;
396 double _stepSize, _stepSizeCoeff;
397 const SMDS_MeshNode* _stepSizeNodes[2];
400 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
401 map< TGeomID, TNode2Edge* > _s2neMap;
402 // edges of _n2eMap. We keep same data in two containers because
403 // iteration over the map is 5 time longer than over the vector
404 vector< _LayerEdge* > _edges;
405 // edges on EDGE's with null _sWOL, whose _simplices are used to stop inflation
406 vector< _LayerEdge* > _simplexTestEdges;
408 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
409 // layers and a FACE w/o layers
410 // value: the shape (FACE or EDGE) to shrink mesh on.
411 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
412 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
414 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
415 set< TGeomID > _noShrinkFaces;
417 // <EDGE to smooth on> to <it's curve>
418 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
420 // end indices in _edges of _LayerEdge on one shape to smooth
421 vector< int > _endEdgeToSmooth;
423 double _epsilon; // precision for SegTriaInter()
425 int _index; // for debug
427 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
428 const StdMeshers_ViscousLayers* h=0,
429 const TopoDS_Shape& hs=TopoDS_Shape(),
431 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
434 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
437 Handle(Geom_Surface)& surface,
438 const TopoDS_Face& F,
439 SMESH_MesherHelper& helper);
441 //--------------------------------------------------------------------------------
443 * \brief Data of node on a shrinked FACE
447 const SMDS_MeshNode* _node;
448 //vector<const SMDS_MeshNode*> _nodesAround;
449 vector<_Simplex> _simplices; // for quality check
451 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
453 bool Smooth(int& badNb,
454 Handle(Geom_Surface)& surface,
455 SMESH_MesherHelper& helper,
456 const double refSign,
460 gp_XY computeAngularPos(vector<gp_XY>& uv,
461 const gp_XY& uvToFix,
462 const double refSign );
464 //--------------------------------------------------------------------------------
466 * \brief Builder of viscous layers
468 class _ViscousBuilder
473 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
474 const TopoDS_Shape& shape);
476 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
477 void RestoreListeners();
479 // computes SMESH_ProxyMesh::SubMesh::_n2n;
480 bool MakeN2NMap( _MeshOfSolid* pm );
484 bool findSolidsWithLayers();
485 bool findFacesWithLayers();
486 bool makeLayer(_SolidData& data);
487 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
488 SMESH_MesherHelper& helper, _SolidData& data);
489 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
490 std::pair< TGeomID, gp_XYZ > fId2Normal[],
492 bool findNeiborsOnEdge(const _LayerEdge* edge,
493 const SMDS_MeshNode*& n1,
494 const SMDS_MeshNode*& n2,
496 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
497 const set<TGeomID>& ingnoreShapes,
498 const _SolidData* dataToCheckOri = 0,
499 const bool toSort = false);
500 void findSimplexTestEdges( _SolidData& data,
501 vector< vector<_LayerEdge*> >& edgesByGeom);
502 bool sortEdges( _SolidData& data,
503 vector< vector<_LayerEdge*> >& edgesByGeom);
504 void limitStepSize( _SolidData& data,
505 const SMDS_MeshElement* face,
507 void limitStepSize( _SolidData& data, const double minSize);
508 bool inflate(_SolidData& data);
509 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
510 bool smoothAnalyticEdge( _SolidData& data,
513 Handle(Geom_Surface)& surface,
514 const TopoDS_Face& F,
515 SMESH_MesherHelper& helper);
516 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
517 bool refine(_SolidData& data);
519 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
520 SMESH_MesherHelper& helper,
521 const SMESHDS_SubMesh* faceSubMesh );
522 void fixBadFaces(const TopoDS_Face& F,
523 SMESH_MesherHelper& helper,
526 set<const SMDS_MeshNode*> * involvedNodes=NULL);
527 bool addBoundaryElements();
529 bool error( const string& text, int solidID=-1 );
530 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
533 void makeGroupOfLE();
536 SMESH_ComputeErrorPtr _error;
538 vector< _SolidData > _sdVec;
541 //--------------------------------------------------------------------------------
543 * \brief Shrinker of nodes on the EDGE
547 vector<double> _initU;
548 vector<double> _normPar;
549 vector<const SMDS_MeshNode*> _nodes;
550 const _LayerEdge* _edges[2];
553 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
554 void Compute(bool set3D, SMESH_MesherHelper& helper);
555 void RestoreParams();
556 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
558 //--------------------------------------------------------------------------------
560 * \brief Class of temporary mesh face.
561 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
562 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
564 struct TmpMeshFace : public SMDS_MeshElement
566 vector<const SMDS_MeshNode* > _nn;
567 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
568 SMDS_MeshElement(id), _nn(nodes) {}
569 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
570 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
571 virtual vtkIdType GetVtkType() const { return -1; }
572 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
573 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
574 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
575 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
577 //--------------------------------------------------------------------------------
579 * \brief Class of temporary mesh face storing _LayerEdge it's based on
581 struct TmpMeshFaceOnEdge : public TmpMeshFace
583 _LayerEdge *_le1, *_le2;
584 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
585 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
587 _nn[0]=_le1->_nodes[0];
588 _nn[1]=_le1->_nodes.back();
589 _nn[2]=_le2->_nodes.back();
590 _nn[3]=_le2->_nodes[0];
593 //--------------------------------------------------------------------------------
595 * \brief Retriever of node coordinates either directly of from a surface by node UV.
596 * \warning Location of a surface is ignored
598 struct NodeCoordHelper
600 SMESH_MesherHelper& _helper;
601 const TopoDS_Face& _face;
602 Handle(Geom_Surface) _surface;
603 gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
605 NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
606 : _helper( helper ), _face( F )
611 _surface = BRep_Tool::Surface( _face, loc );
613 if ( _surface.IsNull() )
614 _fun = & NodeCoordHelper::direct;
616 _fun = & NodeCoordHelper::byUV;
618 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
621 gp_XYZ direct(const SMDS_MeshNode* n) const
623 return SMESH_TNodeXYZ( n );
625 gp_XYZ byUV (const SMDS_MeshNode* n) const
627 gp_XY uv = _helper.GetNodeUV( _face, n );
628 return _surface->Value( uv.X(), uv.Y() ).XYZ();
631 } // namespace VISCOUS_3D
633 //================================================================================
634 // StdMeshers_ViscousLayers hypothesis
636 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
637 :SMESH_Hypothesis(hypId, studyId, gen),
638 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
640 _name = StdMeshers_ViscousLayers::GetHypType();
641 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
642 } // --------------------------------------------------------------------------------
643 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
645 if ( faceIds != _shapeIds )
646 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
647 if ( _isToIgnoreShapes != toIgnore )
648 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
649 } // --------------------------------------------------------------------------------
650 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
652 if ( thickness != _thickness )
653 _thickness = thickness, NotifySubMeshesHypothesisModification();
654 } // --------------------------------------------------------------------------------
655 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
657 if ( _nbLayers != nb )
658 _nbLayers = nb, NotifySubMeshesHypothesisModification();
659 } // --------------------------------------------------------------------------------
660 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
662 if ( _stretchFactor != factor )
663 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
664 } // --------------------------------------------------------------------------------
666 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
667 const TopoDS_Shape& theShape,
668 const bool toMakeN2NMap) const
670 using namespace VISCOUS_3D;
671 _ViscousBuilder bulder;
672 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
673 if ( err && !err->IsOK() )
674 return SMESH_ProxyMesh::Ptr();
676 vector<SMESH_ProxyMesh::Ptr> components;
677 TopExp_Explorer exp( theShape, TopAbs_SOLID );
678 for ( ; exp.More(); exp.Next() )
680 if ( _MeshOfSolid* pm =
681 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
683 if ( toMakeN2NMap && !pm->_n2nMapComputed )
684 if ( !bulder.MakeN2NMap( pm ))
685 return SMESH_ProxyMesh::Ptr();
686 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
687 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
689 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
691 switch ( components.size() )
695 case 1: return components[0];
697 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
699 return SMESH_ProxyMesh::Ptr();
700 } // --------------------------------------------------------------------------------
701 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
703 save << " " << _nbLayers
705 << " " << _stretchFactor
706 << " " << _shapeIds.size();
707 for ( size_t i = 0; i < _shapeIds.size(); ++i )
708 save << " " << _shapeIds[i];
709 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
711 } // --------------------------------------------------------------------------------
712 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
714 int nbFaces, faceID, shapeToTreat;
715 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
716 while ( _shapeIds.size() < nbFaces && load >> faceID )
717 _shapeIds.push_back( faceID );
718 if ( load >> shapeToTreat )
719 _isToIgnoreShapes = !shapeToTreat;
721 _isToIgnoreShapes = true; // old behavior
723 } // --------------------------------------------------------------------------------
724 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
725 const TopoDS_Shape& theShape)
730 // END StdMeshers_ViscousLayers hypothesis
731 //================================================================================
735 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
739 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
740 gp_Pnt p = BRep_Tool::Pnt( fromV );
741 double distF = p.SquareDistance( c->Value( f ));
742 double distL = p.SquareDistance( c->Value( l ));
743 c->D1(( distF < distL ? f : l), p, dir );
744 if ( distL < distF ) dir.Reverse();
747 //--------------------------------------------------------------------------------
748 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
749 SMESH_MesherHelper& helper)
752 double f,l; gp_Pnt p;
753 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
754 double u = helper.GetNodeU( E, atNode );
758 //--------------------------------------------------------------------------------
759 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
760 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
762 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
763 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
764 gp_Pnt p; gp_Vec du, dv, norm;
765 surface->D1( uv.X(),uv.Y(), p, du,dv );
769 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
770 double u = helper.GetNodeU( fromE, node, 0, &ok );
772 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
773 if ( o == TopAbs_REVERSED )
776 gp_Vec dir = norm ^ du;
778 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
779 helper.IsClosedEdge( fromE ))
781 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
782 else c->D1( f, p, dv );
783 if ( o == TopAbs_REVERSED )
785 gp_Vec dir2 = norm ^ dv;
786 dir = dir.Normalized() + dir2.Normalized();
790 //--------------------------------------------------------------------------------
791 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
792 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
793 bool& ok, double* cosin=0)
795 double f,l; TopLoc_Location loc;
796 vector< TopoDS_Edge > edges; // sharing a vertex
797 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
800 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
801 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
802 edges.push_back( *e );
805 if ( !( ok = ( edges.size() > 0 ))) return dir;
806 // get average dir of edges going fromV
808 //if ( edges.size() > 1 )
809 for ( size_t i = 0; i < edges.size(); ++i )
811 edgeDir = getEdgeDir( edges[i], fromV );
812 double size2 = edgeDir.SquareModulus();
813 if ( size2 > numeric_limits<double>::min() )
814 edgeDir /= sqrt( size2 );
819 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
821 if ( edges.size() == 1 )
823 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
824 dir = fromEdgeDir.Normalized() + getFaceDir( F, edges[1], node, helper, ok ).Normalized();
825 else if ( dir * fromEdgeDir < 0 )
828 catch ( Standard_Failure )
834 //dir /= edges.size();
836 double angle = gp_Vec( edgeDir ).Angle( dir );
837 *cosin = cos( angle );
842 //================================================================================
844 * \brief Returns true if a FACE is bound by a concave EDGE
846 //================================================================================
848 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
850 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
854 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
855 for ( ; eExp.More(); eExp.Next() )
857 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
858 if ( SMESH_Algo::isDegenerated( E )) continue;
859 // check if 2D curve is concave
860 BRepAdaptor_Curve2d curve( E, F );
861 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
862 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
863 curve.Intervals( intervals, GeomAbs_C2 );
864 bool isConvex = true;
865 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
867 double u1 = intervals( i );
868 double u2 = intervals( i+1 );
869 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
870 double cross = drv2 ^ drv1;
871 if ( E.Orientation() == TopAbs_REVERSED )
873 isConvex = ( cross > 0.1 ); //-1e-9 );
875 // check if concavity is strong enough to care about it
876 //const double maxAngle = 5 * Standard_PI180;
879 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
881 // map< double, const SMDS_MeshNode* > u2nodes;
882 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
883 // /*ignoreMedium=*/true, u2nodes))
885 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
886 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
887 // double uPrev = u2n->first;
888 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
890 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
891 // gp_Vec2d segmentDir( uvPrev, uv );
892 // curve.D1( uPrev, p, drv1 );
894 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
899 // uPrev = u2n->first;
903 // check angles at VERTEXes
905 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
906 for ( size_t iW = 0; iW < wires.size(); ++iW )
908 const int nbEdges = wires[iW]->NbEdges();
909 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
911 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
913 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
914 int iE2 = ( iE1 + 1 ) % nbEdges;
915 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
916 iE2 = ( iE2 + 1 ) % nbEdges;
917 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
918 wires[iW]->Edge( iE2 ), F );
919 if ( angle < -5. * M_PI / 180. )
925 //--------------------------------------------------------------------------------
926 // DEBUG. Dump intermediate node positions into a python script
931 const char* fname = "/tmp/viscous.py";
932 cout << "execfile('"<<fname<<"')"<<endl;
933 py = new ofstream(fname);
934 *py << "import SMESH" << endl
935 << "from salome.smesh import smeshBuilder" << endl
936 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
937 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
938 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
942 *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
945 ~PyDump() { Finish(); }
947 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
948 #define dumpMove(n) { _dumpMove(n, __LINE__);}
949 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
950 void _dumpFunction(const string& fun, int ln)
951 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
952 void _dumpMove(const SMDS_MeshNode* n, int ln)
953 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
954 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
955 void _dumpCmd(const string& txt, int ln)
956 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
957 void dumpFunctionEnd()
958 { if (py) *py<< " return"<< endl; }
959 void dumpChangeNodes( const SMDS_MeshElement* f )
960 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
961 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
962 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
964 struct PyDump { void Finish() {} };
965 #define dumpFunction(f) f
968 #define dumpFunctionEnd()
969 #define dumpChangeNodes(f)
973 using namespace VISCOUS_3D;
975 //================================================================================
977 * \brief Constructor of _ViscousBuilder
979 //================================================================================
981 _ViscousBuilder::_ViscousBuilder()
983 _error = SMESH_ComputeError::New(COMPERR_OK);
987 //================================================================================
989 * \brief Stores error description and returns false
991 //================================================================================
993 bool _ViscousBuilder::error(const string& text, int solidId )
995 _error->myName = COMPERR_ALGO_FAILED;
996 _error->myComment = string("Viscous layers builder: ") + text;
999 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1000 if ( !sm && !_sdVec.empty() )
1001 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1002 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1004 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1005 if ( smError && smError->myAlgo )
1006 _error->myAlgo = smError->myAlgo;
1010 makeGroupOfLE(); // debug
1015 //================================================================================
1017 * \brief At study restoration, restore event listeners used to clear an inferior
1018 * dim sub-mesh modified by viscous layers
1020 //================================================================================
1022 void _ViscousBuilder::RestoreListeners()
1027 //================================================================================
1029 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1031 //================================================================================
1033 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1035 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1036 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1037 for ( ; fExp.More(); fExp.Next() )
1039 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1040 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1042 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1044 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1047 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1048 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1050 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1051 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1052 while( prxIt->more() )
1054 const SMDS_MeshElement* fSrc = srcIt->next();
1055 const SMDS_MeshElement* fPrx = prxIt->next();
1056 if ( fSrc->NbNodes() != fPrx->NbNodes())
1057 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1058 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1059 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1062 pm->_n2nMapComputed = true;
1066 //================================================================================
1068 * \brief Does its job
1070 //================================================================================
1072 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1073 const TopoDS_Shape& theShape)
1075 // TODO: set priority of solids during Gen::Compute()
1079 // check if proxy mesh already computed
1080 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1082 return error("No SOLID's in theShape"), _error;
1084 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1085 return SMESH_ComputeErrorPtr(); // everything already computed
1089 // TODO: ignore already computed SOLIDs
1090 if ( !findSolidsWithLayers())
1093 if ( !findFacesWithLayers() )
1096 for ( size_t i = 0; i < _sdVec.size(); ++i )
1098 if ( ! makeLayer(_sdVec[i]) )
1101 if ( _sdVec[i]._edges.size() == 0 )
1104 if ( ! inflate(_sdVec[i]) )
1107 if ( ! refine(_sdVec[i]) )
1113 addBoundaryElements();
1115 makeGroupOfLE(); // debug
1121 //================================================================================
1123 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1125 //================================================================================
1127 bool _ViscousBuilder::findSolidsWithLayers()
1130 TopTools_IndexedMapOfShape allSolids;
1131 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1132 _sdVec.reserve( allSolids.Extent());
1134 SMESH_Gen* gen = _mesh->GetGen();
1135 SMESH_HypoFilter filter;
1136 for ( int i = 1; i <= allSolids.Extent(); ++i )
1138 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1139 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1140 if ( !algo ) continue;
1141 // TODO: check if algo is hidden
1142 const list <const SMESHDS_Hypothesis *> & allHyps =
1143 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1144 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1145 const StdMeshers_ViscousLayers* viscHyp = 0;
1146 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1147 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1150 TopoDS_Shape hypShape;
1151 filter.Init( filter.Is( viscHyp ));
1152 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1154 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1157 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1158 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1161 if ( _sdVec.empty() )
1163 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1168 //================================================================================
1172 //================================================================================
1174 bool _ViscousBuilder::findFacesWithLayers()
1176 SMESH_MesherHelper helper( *_mesh );
1177 TopExp_Explorer exp;
1178 TopTools_IndexedMapOfShape solids;
1180 // collect all faces to ignore defined by hyp
1181 for ( size_t i = 0; i < _sdVec.size(); ++i )
1183 solids.Add( _sdVec[i]._solid );
1185 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1186 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1188 for ( size_t ii = 0; ii < ids.size(); ++ii )
1190 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1191 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1192 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1195 else // FACEs with layers are given
1197 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1198 for ( ; exp.More(); exp.Next() )
1200 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1201 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1202 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1206 // ignore internal FACEs if inlets and outlets are specified
1208 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1209 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1210 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1211 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1213 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1214 for ( ; exp.More(); exp.Next() )
1216 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1217 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1220 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1221 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1223 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1225 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1228 if ( helper.IsReversedSubMesh( face ))
1230 _sdVec[i]._reversedFaceIds.insert( faceInd );
1236 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1237 TopTools_IndexedMapOfShape shapes;
1238 for ( size_t i = 0; i < _sdVec.size(); ++i )
1241 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1242 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1244 const TopoDS_Shape& edge = shapes(iE);
1245 // find 2 faces sharing an edge
1247 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1248 while ( fIt->more())
1250 const TopoDS_Shape* f = fIt->next();
1251 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1252 FF[ int( !FF[0].IsNull()) ] = *f;
1254 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1255 // check presence of layers on them
1257 for ( int j = 0; j < 2; ++j )
1258 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1259 if ( ignore[0] == ignore[1] )
1260 continue; // nothing interesting
1261 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1262 // check presence of layers on fWOL within an adjacent SOLID
1263 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1264 while ( const TopoDS_Shape* solid = sIt->next() )
1265 if ( !solid->IsSame( _sdVec[i]._solid ))
1267 int iSolid = solids.FindIndex( *solid );
1268 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1269 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1271 _sdVec[i]._noShrinkFaces.insert( iFace );
1276 if ( !fWOL.IsNull())
1278 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1279 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1283 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1284 // the algo of the SOLID sharing the FACE does not support it
1285 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1286 for ( size_t i = 0; i < _sdVec.size(); ++i )
1288 TopTools_MapOfShape noShrinkVertices;
1289 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1290 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1292 const TopoDS_Shape& fWOL = e2f->second;
1293 TGeomID edgeID = e2f->first;
1294 bool notShrinkFace = false;
1295 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1296 while ( soIt->more())
1298 const TopoDS_Shape* solid = soIt->next();
1299 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1300 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1301 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1302 notShrinkFace = true;
1303 for ( size_t j = 0; j < _sdVec.size(); ++j )
1305 if ( _sdVec[j]._solid.IsSame( *solid ) )
1306 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1307 notShrinkFace = false;
1310 if ( notShrinkFace )
1312 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1313 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1314 noShrinkVertices.Add( vExp.Current() );
1317 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1318 // to the found not shrinked fWOL's
1319 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1320 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1322 TGeomID edgeID = e2f->first;
1323 TopoDS_Vertex VV[2];
1324 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1325 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1327 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1328 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1337 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1339 for ( size_t i = 0; i < _sdVec.size(); ++i )
1342 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1343 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1345 const TopoDS_Shape& vertex = shapes(iV);
1346 // find faces WOL sharing the vertex
1347 vector< TopoDS_Shape > facesWOL;
1348 int totalNbFaces = 0;
1349 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1350 while ( fIt->more())
1352 const TopoDS_Shape* f = fIt->next();
1353 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1356 const int fID = getMeshDS()->ShapeToIndex( *f );
1357 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1358 !_sdVec[i]._noShrinkFaces.count( fID ))
1359 facesWOL.push_back( *f );
1362 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1363 continue; // no layers at this vertex or no WOL
1364 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1365 switch ( facesWOL.size() )
1369 helper.SetSubShape( facesWOL[0] );
1370 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1372 TopoDS_Shape seamEdge;
1373 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1374 while ( eIt->more() && seamEdge.IsNull() )
1376 const TopoDS_Shape* e = eIt->next();
1377 if ( helper.IsRealSeam( *e ) )
1380 if ( !seamEdge.IsNull() )
1382 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1386 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1391 // find an edge shared by 2 faces
1392 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1393 while ( eIt->more())
1395 const TopoDS_Shape* e = eIt->next();
1396 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1397 helper.IsSubShape( *e, facesWOL[1]))
1399 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1405 return error("Not yet supported case", _sdVec[i]._index);
1410 // add FACEs of other SOLIDs to _ignoreFaceIds
1411 for ( size_t i = 0; i < _sdVec.size(); ++i )
1414 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1416 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1418 if ( !shapes.Contains( exp.Current() ))
1419 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1426 //================================================================================
1428 * \brief Create the inner surface of the viscous layer and prepare data for infation
1430 //================================================================================
1432 bool _ViscousBuilder::makeLayer(_SolidData& data)
1434 // get all sub-shapes to make layers on
1435 set<TGeomID> subIds, faceIds;
1436 subIds = data._noShrinkFaces;
1437 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1438 for ( ; exp.More(); exp.Next() )
1440 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1441 if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1442 faceIds.insert( fSubM->GetId() );
1443 SMESH_subMeshIteratorPtr subIt =
1444 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1445 while ( subIt->more() )
1446 subIds.insert( subIt->next()->GetId() );
1449 // make a map to find new nodes on sub-shapes shared with other SOLID
1450 map< TGeomID, TNode2Edge* >::iterator s2ne;
1451 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1452 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1454 TGeomID shapeInd = s2s->first;
1455 for ( size_t i = 0; i < _sdVec.size(); ++i )
1457 if ( _sdVec[i]._index == data._index ) continue;
1458 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1459 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1460 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1462 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1468 // Create temporary faces and _LayerEdge's
1470 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1472 data._stepSize = Precision::Infinite();
1473 data._stepSizeNodes[0] = 0;
1475 SMESH_MesherHelper helper( *_mesh );
1476 helper.SetSubShape( data._solid );
1477 helper.SetElementsOnShape(true);
1479 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1480 TNode2Edge::iterator n2e2;
1482 // collect _LayerEdge's of shapes they are based on
1483 const int nbShapes = getMeshDS()->MaxShapeIndex();
1484 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1486 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1488 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1489 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1491 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1492 SMESH_ProxyMesh::SubMesh* proxySub =
1493 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1495 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1496 while ( eIt->more() )
1498 const SMDS_MeshElement* face = eIt->next();
1499 newNodes.resize( face->NbCornerNodes() );
1500 double faceMaxCosin = -1;
1501 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1503 const SMDS_MeshNode* n = face->GetNode(i);
1504 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1505 if ( !(*n2e).second )
1508 _LayerEdge* edge = new _LayerEdge();
1510 edge->_nodes.push_back( n );
1511 const int shapeID = n->getshapeId();
1512 edgesByGeom[ shapeID ].push_back( edge );
1514 SMESH_TNodeXYZ xyz( n );
1516 // set edge data or find already refined _LayerEdge and get data from it
1517 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1518 ( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() &&
1519 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1521 _LayerEdge* foundEdge = (*n2e2).second;
1522 gp_XYZ lastPos = edge->Copy( *foundEdge, helper );
1523 foundEdge->_pos.push_back( lastPos );
1524 // location of the last node is modified and we restore it by foundEdge->_pos.back()
1525 const_cast< SMDS_MeshNode* >
1526 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
1530 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
1531 if ( !setEdgeData( *edge, subIds, helper, data ))
1534 dumpMove(edge->_nodes.back());
1535 if ( edge->_cosin > 0.01 )
1537 if ( edge->_cosin > faceMaxCosin )
1538 faceMaxCosin = edge->_cosin;
1541 newNodes[ i ] = n2e->second->_nodes.back();
1543 // create a temporary face
1544 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1545 proxySub->AddElement( newFace );
1547 // compute inflation step size by min size of element on a convex surface
1548 if ( faceMaxCosin > 0.1 )
1549 limitStepSize( data, face, faceMaxCosin );
1550 } // loop on 2D elements on a FACE
1551 } // loop on FACEs of a SOLID
1553 data._epsilon = 1e-7;
1554 if ( data._stepSize < 1. )
1555 data._epsilon *= data._stepSize;
1557 // fill data._simplexTestEdges
1558 findSimplexTestEdges( data, edgesByGeom );
1560 // Put _LayerEdge's into the vector data._edges
1561 if ( !sortEdges( data, edgesByGeom ))
1564 // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1565 TNode2Edge::iterator n2e;
1566 for ( size_t i = 0; i < data._edges.size(); ++i )
1568 if ( data._edges[i]->IsOnEdge())
1569 for ( int j = 0; j < 2; ++j )
1571 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1572 break; // _LayerEdge is shared by two _SolidData's
1573 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1574 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1575 return error("_LayerEdge not found by src node", data._index);
1576 n = (*n2e).second->_nodes.back();
1577 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1580 for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1582 _Simplex& s = data._edges[i]->_simplices[j];
1583 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1584 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1592 //================================================================================
1594 * \brief Compute inflation step size by min size of element on a convex surface
1596 //================================================================================
1598 void _ViscousBuilder::limitStepSize( _SolidData& data,
1599 const SMDS_MeshElement* face,
1603 double minSize = 10 * data._stepSize;
1604 const int nbNodes = face->NbCornerNodes();
1605 for ( int i = 0; i < nbNodes; ++i )
1607 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1608 const SMDS_MeshNode* curN = face->GetNode( i );
1609 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1610 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1612 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1613 if ( dist < minSize )
1614 minSize = dist, iN = i;
1617 double newStep = 0.8 * minSize / cosin;
1618 if ( newStep < data._stepSize )
1620 data._stepSize = newStep;
1621 data._stepSizeCoeff = 0.8 / cosin;
1622 data._stepSizeNodes[0] = face->GetNode( iN );
1623 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1627 //================================================================================
1629 * \brief Compute inflation step size by min size of element on a convex surface
1631 //================================================================================
1633 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1635 if ( minSize < data._stepSize )
1637 data._stepSize = minSize;
1638 if ( data._stepSizeNodes[0] )
1641 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1642 data._stepSizeCoeff = data._stepSize / dist;
1647 //================================================================================
1649 * Fill data._simplexTestEdges. These _LayerEdge's are used to stop inflation
1650 * in the case where there are no _LayerEdge's on a curved convex FACE,
1651 * as e.g. on a fillet surface with no internal nodes - issue 22580,
1652 * so that collision of viscous internal faces is not detected by check of
1653 * intersection of _LayerEdge's with the viscous internal faces.
1655 //================================================================================
1657 void _ViscousBuilder::findSimplexTestEdges( _SolidData& data,
1658 vector< vector<_LayerEdge*> >& edgesByGeom)
1660 data._simplexTestEdges.clear();
1662 SMESH_MesherHelper helper( *_mesh );
1664 vector< vector<_LayerEdge*> * > ledgesOnEdges;
1665 set< const SMDS_MeshNode* > usedNodes;
1667 const double minCurvature = 1. / data._hyp->GetTotalThickness();
1669 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1671 // look for a FACE with layers and w/o _LayerEdge's
1672 const vector<_LayerEdge*>& eS = edgesByGeom[iS];
1673 if ( !eS.empty() ) continue;
1674 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1675 if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
1676 if ( data._ignoreFaceIds.count( iS )) continue;
1678 const TopoDS_Face& F = TopoDS::Face( S );
1680 // look for _LayerEdge's on EDGEs with null _sWOL
1681 ledgesOnEdges.clear();
1682 TopExp_Explorer eExp( F, TopAbs_EDGE );
1683 for ( ; eExp.More(); eExp.Next() )
1685 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1686 vector<_LayerEdge*>& eE = edgesByGeom[iE];
1687 if ( !eE.empty() && eE[0]->_sWOL.IsNull() )
1688 ledgesOnEdges.push_back( & eE );
1690 if ( ledgesOnEdges.empty() ) continue;
1692 // check FACE convexity
1693 const _LayerEdge* le = ledgesOnEdges[0]->back();
1694 gp_XY uv = helper.GetNodeUV( F, le->_nodes[0] );
1695 BRepAdaptor_Surface surf( F );
1696 BRepLProp_SLProps surfProp( surf, uv.X(), uv.Y(), 2, 1e-6 );
1697 if ( !surfProp.IsCurvatureDefined() )
1699 double surfCurvature = Max( Abs( surfProp.MaxCurvature() ),
1700 Abs( surfProp.MinCurvature() ));
1701 if ( surfCurvature < minCurvature )
1703 gp_Dir minDir, maxDir;
1704 surfProp.CurvatureDirections( maxDir, minDir );
1705 if ( F.Orientation() == TopAbs_REVERSED ) {
1706 maxDir.Reverse(); minDir.Reverse();
1708 const gp_XYZ& inDir = le->_normal;
1709 if ( inDir * maxDir.XYZ() < 0 &&
1710 inDir * minDir.XYZ() < 0 )
1713 limitStepSize( data, 0.9 / surfCurvature );
1715 // add _simplices to the _LayerEdge's
1716 for ( size_t iE = 0; iE < ledgesOnEdges.size(); ++iE )
1718 const vector<_LayerEdge*>& ledges = *ledgesOnEdges[iE];
1719 for ( size_t iLE = 0; iLE < ledges.size(); ++iLE )
1721 _LayerEdge* ledge = ledges[iLE];
1722 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1723 if ( !usedNodes.insert( srcNode ).second ) continue;
1725 getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1726 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1728 usedNodes.insert( ledge->_simplices[i]._nPrev );
1729 usedNodes.insert( ledge->_simplices[i]._nNext );
1731 data._simplexTestEdges.push_back( ledge );
1737 //================================================================================
1739 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1741 //================================================================================
1743 bool _ViscousBuilder::sortEdges( _SolidData& data,
1744 vector< vector<_LayerEdge*> >& edgesByGeom)
1746 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1747 // boundry inclined at a sharp angle to the shape
1749 list< TGeomID > shapesToSmooth;
1751 SMESH_MesherHelper helper( *_mesh );
1754 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1756 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1757 if ( eS.empty() ) continue;
1758 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1759 bool needSmooth = false;
1760 switch ( S.ShapeType() )
1764 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1765 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1767 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1768 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1769 if ( eV.empty() ) continue;
1770 double cosin = eV[0]->_cosin;
1772 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1776 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1777 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1779 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1780 eV[0]->_nodes[0], helper, ok);
1781 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1782 double angle = dir1.Angle( dir2 );
1783 cosin = cos( angle );
1785 needSmooth = ( cosin > 0.1 );
1791 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1793 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1794 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1795 if ( eE.empty() ) continue;
1796 if ( eE[0]->_sWOL.IsNull() )
1798 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1799 needSmooth = ( eE[i]->_cosin > 0.1 );
1803 const TopoDS_Face& F1 = TopoDS::Face( S );
1804 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1805 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1806 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1808 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1809 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1810 double angle = dir1.Angle( dir2 );
1811 double cosin = cos( angle );
1812 needSmooth = ( cosin > 0.1 );
1824 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1825 else shapesToSmooth.push_back ( iS );
1828 } // loop on edgesByGeom
1830 data._edges.reserve( data._n2eMap.size() );
1831 data._endEdgeToSmooth.clear();
1833 // first we put _LayerEdge's on shapes to smooth
1834 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1835 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1837 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1838 if ( eVec.empty() ) continue;
1839 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1840 data._endEdgeToSmooth.push_back( data._edges.size() );
1844 // then the rest _LayerEdge's
1845 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1847 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1848 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1855 //================================================================================
1857 * \brief Set data of _LayerEdge needed for smoothing
1858 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1860 //================================================================================
1862 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1863 const set<TGeomID>& subIds,
1864 SMESH_MesherHelper& helper,
1867 SMESH_MeshEditor editor(_mesh);
1869 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1870 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1874 edge._curvature = 0;
1876 // --------------------------
1877 // Compute _normal and _cosin
1878 // --------------------------
1881 edge._normal.SetCoord(0,0,0);
1883 int totalNbFaces = 0;
1885 gp_Vec du, dv, geomNorm;
1888 TGeomID shapeInd = node->getshapeId();
1889 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1890 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1891 TopoDS_Shape vertEdge;
1893 if ( onShrinkShape ) // one of faces the node is on has no layers
1895 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1896 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1898 // inflate from VERTEX along EDGE
1899 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1901 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1903 // inflate from VERTEX along FACE
1904 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1905 node, helper, normOK, &edge._cosin);
1909 // inflate from EDGE along FACE
1910 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1911 node, helper, normOK);
1914 else // layers are on all faces of SOLID the node is on
1916 // find indices of geom faces the node lies on
1917 set<TGeomID> faceIds;
1918 if ( posType == SMDS_TOP_FACE )
1920 faceIds.insert( node->getshapeId() );
1924 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1925 while ( fIt->more() )
1926 faceIds.insert( editor.FindShape(fIt->next()));
1929 set<TGeomID>::iterator id = faceIds.begin();
1931 std::pair< TGeomID, gp_XYZ > id2Norm[20];
1932 for ( ; id != faceIds.end(); ++id )
1934 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1935 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1937 F = TopoDS::Face( s );
1939 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1940 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1943 if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1948 else // hard singularity
1950 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1951 while ( fIt->more() )
1953 const SMDS_MeshElement* f = fIt->next();
1954 if ( editor.FindShape( f ) == *id )
1956 SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1957 if ( helper.IsReversedSubMesh( F ))
1962 double size2 = geomNorm.SquareMagnitude();
1963 if ( size2 > numeric_limits<double>::min() )
1964 geomNorm /= sqrt( size2 );
1969 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1971 id2Norm[ totalNbFaces ].first = *id;
1972 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
1974 edge._normal += geomNorm.XYZ();
1976 if ( totalNbFaces == 0 )
1977 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1979 if ( totalNbFaces < 3 )
1981 //edge._normal /= totalNbFaces;
1985 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
1991 edge._cosin = 0; break;
1993 case SMDS_TOP_EDGE: {
1994 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1995 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1996 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1997 edge._cosin = cos( angle );
1998 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2001 case SMDS_TOP_VERTEX: {
2002 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2003 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
2004 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
2005 edge._cosin = cos( angle );
2006 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2010 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2014 double normSize = edge._normal.SquareModulus();
2015 if ( normSize < numeric_limits<double>::min() )
2016 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2018 edge._normal /= sqrt( normSize );
2020 // TODO: if ( !normOK ) then get normal by mesh faces
2022 // Set the rest data
2023 // --------------------
2024 if ( onShrinkShape )
2026 edge._sWOL = (*s2s).second;
2028 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2029 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2030 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2032 // set initial position which is parameters on _sWOL in this case
2033 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2035 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2036 edge._pos.push_back( gp_XYZ( u, 0, 0));
2037 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2041 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2042 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2043 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2048 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2050 if ( posType == SMDS_TOP_FACE )
2052 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2053 double avgNormProj = 0, avgLen = 0;
2054 for ( size_t i = 0; i < edge._simplices.size(); ++i )
2056 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2057 avgNormProj += edge._normal * vec;
2058 avgLen += vec.Modulus();
2060 avgNormProj /= edge._simplices.size();
2061 avgLen /= edge._simplices.size();
2062 edge._curvature = _Curvature::New( avgNormProj, avgLen );
2066 // Set neighbour nodes for a _LayerEdge based on EDGE
2068 if ( posType == SMDS_TOP_EDGE /*||
2069 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2071 edge._2neibors = new _2NearEdges;
2072 // target node instead of source ones will be set later
2073 if ( ! findNeiborsOnEdge( &edge,
2074 edge._2neibors->_nodes[0],
2075 edge._2neibors->_nodes[1],
2078 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2079 edge._2neibors->_nodes[1],
2083 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2088 //================================================================================
2090 * \brief Return normal at a node weighted with angles taken by FACEs
2091 * \param [in] n - the node
2092 * \param [in] fId2Normal - FACE ids and normals
2093 * \param [in] nbFaces - nb of FACEs meeting at the node
2094 * \return gp_XYZ - computed normal
2096 //================================================================================
2098 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
2099 std::pair< TGeomID, gp_XYZ > fId2Normal[],
2102 gp_XYZ resNorm(0,0,0);
2103 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2104 if ( V.ShapeType() != TopAbs_VERTEX )
2106 for ( int i = 0; i < nbFaces; ++i )
2107 resNorm += fId2Normal[i].second / nbFaces ;
2112 for ( int i = 0; i < nbFaces; ++i )
2114 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2116 // look for two EDGEs shared by F and other FACEs within fId2Normal
2119 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2120 while ( const TopoDS_Shape* E = eIt->next() )
2122 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2124 bool isSharedEdge = false;
2125 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2127 if ( i == j ) continue;
2128 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2129 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2131 if ( !isSharedEdge )
2133 ee[ nbE ] = TopoDS::Edge( *E );
2134 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2139 // get an angle between the two EDGEs
2141 if ( nbE < 1 ) continue;
2148 TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2149 TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2150 if ( !v10.IsSame( v01 ))
2151 std::swap( ee[0], ee[1] );
2153 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2156 // compute a weighted normal
2157 double sumAngle = 0;
2158 for ( int i = 0; i < nbFaces; ++i )
2160 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
2161 sumAngle += angles[i];
2163 for ( int i = 0; i < nbFaces; ++i )
2164 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2169 //================================================================================
2171 * \brief Find 2 neigbor nodes of a node on EDGE
2173 //================================================================================
2175 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
2176 const SMDS_MeshNode*& n1,
2177 const SMDS_MeshNode*& n2,
2180 const SMDS_MeshNode* node = edge->_nodes[0];
2181 const int shapeInd = node->getshapeId();
2182 SMESHDS_SubMesh* edgeSM = 0;
2183 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2186 edgeSM = getMeshDS()->MeshElements( shapeInd );
2187 if ( !edgeSM || edgeSM->NbElements() == 0 )
2188 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2192 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2193 while ( eIt->more() && !n2 )
2195 const SMDS_MeshElement* e = eIt->next();
2196 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
2197 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2200 if (!edgeSM->Contains(e)) continue;
2204 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2205 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2207 ( iN++ ? n2 : n1 ) = nNeibor;
2210 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2214 //================================================================================
2216 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2218 //================================================================================
2220 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2221 const SMDS_MeshNode* n2,
2222 SMESH_MesherHelper& helper)
2224 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2227 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2228 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2229 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2233 double sumLen = vec1.Modulus() + vec2.Modulus();
2234 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2235 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2236 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2237 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2238 if ( _curvature ) delete _curvature;
2239 _curvature = _Curvature::New( avgNormProj, avgLen );
2241 // if ( _curvature )
2242 // cout << _nodes[0]->GetID()
2243 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2244 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2245 // << _curvature->lenDelta(0) << endl;
2250 if ( _sWOL.IsNull() )
2252 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2253 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2254 gp_XYZ plnNorm = dirE ^ _normal;
2255 double proj0 = plnNorm * vec1;
2256 double proj1 = plnNorm * vec2;
2257 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2259 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2260 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2265 //================================================================================
2267 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2268 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2270 //================================================================================
2272 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2274 _nodes = other._nodes;
2275 _normal = other._normal;
2277 _lenFactor = other._lenFactor;
2278 _cosin = other._cosin;
2279 _sWOL = other._sWOL;
2280 _2neibors = other._2neibors;
2281 _curvature = 0; std::swap( _curvature, other._curvature );
2282 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2284 gp_XYZ lastPos( 0,0,0 );
2285 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2287 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2288 _pos.push_back( gp_XYZ( u, 0, 0));
2290 u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
2295 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2296 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2298 uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
2299 lastPos.SetX( uv.X() );
2300 lastPos.SetY( uv.Y() );
2305 //================================================================================
2307 * \brief Set _cosin and _lenFactor
2309 //================================================================================
2311 void _LayerEdge::SetCosin( double cosin )
2314 _lenFactor = ( Abs( _cosin ) > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
2317 //================================================================================
2319 * \brief Fills a vector<_Simplex >
2321 //================================================================================
2323 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2324 vector<_Simplex>& simplices,
2325 const set<TGeomID>& ingnoreShapes,
2326 const _SolidData* dataToCheckOri,
2330 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2331 while ( fIt->more() )
2333 const SMDS_MeshElement* f = fIt->next();
2334 const TGeomID shapeInd = f->getshapeId();
2335 if ( ingnoreShapes.count( shapeInd )) continue;
2336 const int nbNodes = f->NbCornerNodes();
2337 const int srcInd = f->GetNodeIndex( node );
2338 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2339 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2340 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2341 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2342 std::swap( nPrev, nNext );
2343 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2348 vector<_Simplex> sortedSimplices( simplices.size() );
2349 sortedSimplices[0] = simplices[0];
2351 for ( size_t i = 1; i < simplices.size(); ++i )
2353 for ( size_t j = 1; j < simplices.size(); ++j )
2354 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2356 sortedSimplices[i] = simplices[j];
2361 if ( nbFound == simplices.size() - 1 )
2362 simplices.swap( sortedSimplices );
2366 //================================================================================
2368 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2370 //================================================================================
2372 void _ViscousBuilder::makeGroupOfLE()
2375 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2377 if ( _sdVec[i]._edges.empty() ) continue;
2378 // string name = SMESH_Comment("_LayerEdge's_") << i;
2380 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2381 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2382 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2384 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2385 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2387 _LayerEdge* le = _sdVec[i]._edges[j];
2388 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2389 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2390 << ", " << le->_nodes[iN]->GetID() <<"])");
2391 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2395 dumpFunction( SMESH_Comment("makeNormals") << i );
2396 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2398 _LayerEdge& edge = *_sdVec[i]._edges[j];
2399 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2400 nXYZ += edge._normal * _sdVec[i]._stepSize;
2401 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2402 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2406 // name = SMESH_Comment("tmp_faces ") << i;
2407 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2408 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2409 // SMESH_MeshEditor editor( _mesh );
2410 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2411 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2412 for ( ; fExp.More(); fExp.Next() )
2414 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2416 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2417 while ( fIt->more())
2419 const SMDS_MeshElement* e = fIt->next();
2420 SMESH_Comment cmd("mesh.AddFace([");
2421 for ( int j=0; j < e->NbCornerNodes(); ++j )
2422 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2424 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2425 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2434 //================================================================================
2436 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2438 //================================================================================
2440 bool _ViscousBuilder::inflate(_SolidData& data)
2442 SMESH_MesherHelper helper( *_mesh );
2444 // Limit inflation step size by geometry size found by itersecting
2445 // normals of _LayerEdge's with mesh faces
2446 double geomSize = Precision::Infinite(), intersecDist;
2447 auto_ptr<SMESH_ElementSearcher> searcher
2448 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2449 data._proxyMesh->GetFaces( data._solid )) );
2450 for ( size_t i = 0; i < data._edges.size(); ++i )
2452 if ( data._edges[i]->IsOnEdge() ) continue;
2453 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2454 if ( geomSize > intersecDist && intersecDist > 0 )
2455 geomSize = intersecDist;
2457 if ( data._stepSize > 0.3 * geomSize )
2458 limitStepSize( data, 0.3 * geomSize );
2460 const double tgtThick = data._hyp->GetTotalThickness();
2461 if ( data._stepSize > tgtThick )
2462 limitStepSize( data, tgtThick );
2464 if ( data._stepSize < 1. )
2465 data._epsilon = data._stepSize * 1e-7;
2468 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2471 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2472 int nbSteps = 0, nbRepeats = 0;
2473 while ( 1.01 * avgThick < tgtThick )
2475 // new target length
2476 curThick += data._stepSize;
2477 if ( curThick > tgtThick )
2479 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2483 // Elongate _LayerEdge's
2484 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2485 for ( size_t i = 0; i < data._edges.size(); ++i )
2487 data._edges[i]->SetNewLength( curThick, helper );
2492 if ( !updateNormals( data, helper ) )
2495 // Improve and check quality
2496 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2500 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2501 for ( size_t i = 0; i < data._edges.size(); ++i )
2503 data._edges[i]->InvalidateStep( nbSteps+1 );
2507 break; // no more inflating possible
2511 // Evaluate achieved thickness
2513 for ( size_t i = 0; i < data._edges.size(); ++i )
2514 avgThick += data._edges[i]->_len;
2515 avgThick /= data._edges.size();
2517 cout << "-- Thickness " << avgThick << " reached" << endl;
2520 if ( distToIntersection < avgThick*1.5 )
2523 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2524 << avgThick << " ) * 1.5" << endl;
2529 limitStepSize( data, 0.25 * distToIntersection );
2530 if ( data._stepSizeNodes[0] )
2531 data._stepSize = data._stepSizeCoeff *
2532 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2536 return error("failed at the very first inflation step", data._index);
2541 //================================================================================
2543 * \brief Improve quality of layer inner surface and check intersection
2545 //================================================================================
2547 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2549 double & distToIntersection)
2551 if ( data._endEdgeToSmooth.empty() )
2552 return true; // no shapes needing smoothing
2554 bool moved, improved;
2556 SMESH_MesherHelper helper(*_mesh);
2557 Handle(Geom_Surface) surface;
2561 for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2564 iEnd = data._endEdgeToSmooth[ iS ];
2566 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2567 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2569 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2570 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2571 helper.SetSubShape( F );
2572 surface = BRep_Tool::Surface( F );
2577 F.Nullify(); surface.Nullify();
2579 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2581 if ( data._edges[ iBeg ]->IsOnEdge() )
2583 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2585 // try a simple solution on an analytic EDGE
2586 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2592 for ( int i = iBeg; i < iEnd; ++i )
2594 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2596 dumpCmd( SMESH_Comment("# end step ")<<step);
2598 while ( moved && step++ < 5 );
2599 //cout << " NB STEPS: " << step << endl;
2606 int step = 0, stepLimit = 5, badNb = 0; moved = true;
2607 while (( ++step <= stepLimit && moved ) || improved )
2609 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2610 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2611 int oldBadNb = badNb;
2614 for ( int i = iBeg; i < iEnd; ++i )
2615 moved |= data._edges[i]->Smooth(badNb);
2616 improved = ( badNb < oldBadNb );
2618 // issue 22576. no bad faces but still there are intersections to fix
2619 if ( improved && badNb == 0 )
2620 stepLimit = step + 3;
2627 for ( int i = iBeg; i < iEnd; ++i )
2629 _LayerEdge* edge = data._edges[i];
2630 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2631 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2632 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2634 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2635 << " "<< edge->_simplices[j]._nPrev->GetID()
2636 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2644 } // loop on shapes to smooth
2646 // Check orientation of simplices of _simplexTestEdges
2647 for ( size_t i = 0; i < data._simplexTestEdges.size(); ++i )
2649 const _LayerEdge* edge = data._simplexTestEdges[i];
2650 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2651 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2652 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2655 cout << "Bad simplex of _simplexTestEdges ("
2656 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2657 << " "<< edge->_simplices[j]._nPrev->GetID()
2658 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2664 // Check if the last segments of _LayerEdge intersects 2D elements;
2665 // checked elements are either temporary faces or faces on surfaces w/o the layers
2667 auto_ptr<SMESH_ElementSearcher> searcher
2668 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2669 data._proxyMesh->GetFaces( data._solid )) );
2671 distToIntersection = Precision::Infinite();
2673 const SMDS_MeshElement* intFace = 0;
2675 const SMDS_MeshElement* closestFace = 0;
2678 for ( size_t i = 0; i < data._edges.size(); ++i )
2680 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2682 if ( distToIntersection > dist )
2684 distToIntersection = dist;
2687 closestFace = intFace;
2694 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2695 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2696 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2697 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2698 << ") distance = " << distToIntersection<< endl;
2705 //================================================================================
2707 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2708 * _LayerEdge's to be in a consequent order
2710 //================================================================================
2712 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2715 Handle(Geom_Surface)& surface,
2716 const TopoDS_Face& F,
2717 SMESH_MesherHelper& helper)
2719 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2721 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2723 if ( i2curve == _edge2curve.end() )
2725 // sort _LayerEdge's by position on the EDGE
2727 map< double, _LayerEdge* > u2edge;
2728 for ( int i = iFrom; i < iTo; ++i )
2729 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2731 ASSERT( u2edge.size() == iTo - iFrom );
2732 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2733 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2734 _edges[i] = u2e->second;
2736 // set _2neibors according to the new order
2737 for ( int i = iFrom; i < iTo-1; ++i )
2738 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2739 _edges[i]->_2neibors->reverse();
2740 if ( u2edge.size() > 1 &&
2741 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2742 _edges[iTo-1]->_2neibors->reverse();
2745 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2747 TopLoc_Location loc; double f,l;
2749 Handle(Geom_Line) line;
2750 Handle(Geom_Circle) circle;
2751 bool isLine, isCirc;
2752 if ( F.IsNull() ) // 3D case
2754 // check if the EDGE is a line
2755 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2756 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2757 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2759 line = Handle(Geom_Line)::DownCast( curve );
2760 circle = Handle(Geom_Circle)::DownCast( curve );
2761 isLine = (!line.IsNull());
2762 isCirc = (!circle.IsNull());
2764 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2767 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2768 while ( nIt->more() )
2769 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2770 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2772 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2773 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2774 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2775 for ( int i = 0; i < 3 && !isLine; ++i )
2776 isLine = ( size.Coord( i+1 ) <= lineTol );
2778 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2785 // check if the EDGE is a line
2786 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2787 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2788 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2790 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2791 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2792 isLine = (!line2d.IsNull());
2793 isCirc = (!circle2d.IsNull());
2795 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2798 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2799 while ( nIt->more() )
2800 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2801 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2803 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2804 for ( int i = 0; i < 2 && !isLine; ++i )
2805 isLine = ( size.Coord( i+1 ) <= lineTol );
2807 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2813 line = new Geom_Line( gp::OX() ); // only type does matter
2817 gp_Pnt2d p = circle2d->Location();
2818 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2819 circle = new Geom_Circle( ax, 1.); // only center position does matter
2823 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2831 return i2curve->second;
2834 //================================================================================
2836 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2838 //================================================================================
2840 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2843 Handle(Geom_Surface)& surface,
2844 const TopoDS_Face& F,
2845 SMESH_MesherHelper& helper)
2847 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2848 helper.GetMeshDS());
2849 TopoDS_Edge E = TopoDS::Edge( S );
2851 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2852 if ( curve.IsNull() ) return false;
2854 // compute a relative length of segments
2855 vector< double > len( iTo-iFrom+1 );
2857 double curLen, prevLen = len[0] = 1.0;
2858 for ( int i = iFrom; i < iTo; ++i )
2860 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2861 len[i-iFrom+1] = len[i-iFrom] + curLen;
2866 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2868 if ( F.IsNull() ) // 3D
2870 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2871 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2872 for ( int i = iFrom; i < iTo; ++i )
2874 double r = len[i-iFrom] / len.back();
2875 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2876 data._edges[i]->_pos.back() = newPos;
2877 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2878 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2879 dumpMove( tgtNode );
2884 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2885 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2886 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2887 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2889 int iPeriodic = helper.GetPeriodicIndex();
2890 if ( iPeriodic == 1 || iPeriodic == 2 )
2892 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2893 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2894 std::swap( uv0, uv1 );
2897 const gp_XY rangeUV = uv1 - uv0;
2898 for ( int i = iFrom; i < iTo; ++i )
2900 double r = len[i-iFrom] / len.back();
2901 gp_XY newUV = uv0 + r * rangeUV;
2902 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2904 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2905 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2906 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2907 dumpMove( tgtNode );
2909 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2910 pos->SetUParameter( newUV.X() );
2911 pos->SetVParameter( newUV.Y() );
2917 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2919 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2920 gp_Pnt center3D = circle->Location();
2922 if ( F.IsNull() ) // 3D
2924 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2925 data._edges[iTo-1]->_2neibors->_nodes[1] )
2926 return true; // closed EDGE - nothing to do
2928 return false; // TODO ???
2932 const gp_XY center( center3D.X(), center3D.Y() );
2934 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2935 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2936 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2937 gp_Vec2d vec0( center, uv0 );
2938 gp_Vec2d vecM( center, uvM );
2939 gp_Vec2d vec1( center, uv1 );
2940 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2941 double uMidl = vec0.Angle( vecM );
2942 if ( uLast * uMidl < 0. )
2943 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2944 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2946 gp_Ax2d axis( center, vec0 );
2947 gp_Circ2d circ( axis, radius );
2948 for ( int i = iFrom; i < iTo; ++i )
2950 double newU = uLast * len[i-iFrom] / len.back();
2951 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2952 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2954 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2955 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2956 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2957 dumpMove( tgtNode );
2959 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2960 pos->SetUParameter( newUV.X() );
2961 pos->SetVParameter( newUV.Y() );
2970 //================================================================================
2972 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2973 * _LayerEdge's on neighbor EDGE's
2975 //================================================================================
2977 bool _ViscousBuilder::updateNormals( _SolidData& data,
2978 SMESH_MesherHelper& helper )
2980 // make temporary quadrangles got by extrusion of
2981 // mesh edges along _LayerEdge._normal's
2983 vector< const SMDS_MeshElement* > tmpFaces;
2985 set< SMESH_TLink > extrudedLinks; // contains target nodes
2986 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2988 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2989 for ( size_t i = 0; i < data._edges.size(); ++i )
2991 _LayerEdge* edge = data._edges[i];
2992 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2993 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2994 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2996 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2997 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2998 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2999 if ( !link_isnew.second )
3001 extrudedLinks.erase( link_isnew.first );
3002 continue; // already extruded and will no more encounter
3004 // look for a _LayerEdge containg tgt2
3005 // _LayerEdge* neiborEdge = 0;
3006 // size_t di = 0; // check _edges[i+di] and _edges[i-di]
3007 // while ( !neiborEdge && ++di <= data._edges.size() )
3009 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
3010 // neiborEdge = data._edges[i+di];
3011 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
3012 // neiborEdge = data._edges[i-di];
3014 // if ( !neiborEdge )
3015 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
3016 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3018 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3019 tmpFaces.push_back( f );
3021 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3022 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3023 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3028 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3029 // Perform two loops on _LayerEdge on EDGE's:
3030 // 1) to find and fix intersection
3031 // 2) to check that no new intersection appears as result of 1)
3033 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3035 auto_ptr<SMESH_ElementSearcher> searcher
3036 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3038 // 1) Find intersections
3040 const SMDS_MeshElement* face;
3041 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3042 TLEdge2LEdgeSet edge2CloseEdge;
3044 const double eps = data._epsilon * data._epsilon;
3045 for ( size_t i = 0; i < data._edges.size(); ++i )
3047 _LayerEdge* edge = data._edges[i];
3048 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3049 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3051 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
3052 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3053 ee.insert( f->_le1 );
3054 ee.insert( f->_le2 );
3055 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
3056 edge2CloseEdge[ f->_le1 ].insert( edge );
3057 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
3058 edge2CloseEdge[ f->_le2 ].insert( edge );
3062 // Set _LayerEdge._normal
3064 if ( !edge2CloseEdge.empty() )
3066 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3068 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3069 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3071 _LayerEdge* edge1 = e2ee->first;
3072 _LayerEdge* edge2 = 0;
3073 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
3075 // find EDGEs the edges reside
3077 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3078 if ( S.ShapeType() != TopAbs_EDGE )
3079 continue; // TODO: find EDGE by VERTEX
3080 E1 = TopoDS::Edge( S );
3081 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3082 while ( E2.IsNull() && eIt != ee.end())
3084 _LayerEdge* e2 = *eIt++;
3085 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3086 if ( S.ShapeType() == TopAbs_EDGE )
3087 E2 = TopoDS::Edge( S ), edge2 = e2;
3089 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3091 // find 3 FACEs sharing 2 EDGEs
3093 TopoDS_Face FF1[2], FF2[2];
3094 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3095 while ( fIt->more() && FF1[1].IsNull())
3097 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3098 if ( helper.IsSubShape( *F, data._solid))
3099 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3101 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3102 while ( fIt->more() && FF2[1].IsNull())
3104 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3105 if ( helper.IsSubShape( *F, data._solid))
3106 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3108 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3109 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3110 std::swap( FF1[0], FF1[1] );
3111 if ( FF2[0].IsSame( FF1[0]) )
3112 std::swap( FF2[0], FF2[1] );
3113 if ( FF1[0].IsNull() || FF2[0].IsNull() )
3116 // get a new normal for edge1
3118 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3119 if ( edge1->_cosin < 0 )
3120 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3121 if ( edge2->_cosin < 0 )
3122 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3123 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3124 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3125 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3126 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3127 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3128 // newNorm.Normalize();
3130 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3131 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3132 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3133 newNorm.Normalize();
3135 edge1->_normal = newNorm.XYZ();
3137 // update data of edge1 depending on _normal
3138 const SMDS_MeshNode *n1, *n2;
3139 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3140 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3141 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
3143 edge1->SetDataByNeighbors( n1, n2, helper );
3145 if ( edge1->_cosin < 0 )
3148 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3149 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3150 edge1->SetCosin( cos( angle ));
3152 // limit data._stepSize
3153 if ( edge1->_cosin > 0.1 )
3155 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3156 while ( fIt->more() )
3157 limitStepSize( data, fIt->next(), edge1->_cosin );
3159 // set new XYZ of target node
3160 edge1->InvalidateStep( 1 );
3162 edge1->SetNewLength( data._stepSize, helper );
3165 // Update normals and other dependent data of not intersecting _LayerEdge's
3166 // neighboring the intersecting ones
3168 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3170 _LayerEdge* edge1 = e2ee->first;
3171 if ( !edge1->_2neibors )
3173 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3175 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3176 if ( edge2CloseEdge.count ( neighbor ))
3177 continue; // j-th neighbor is also intersected
3178 _LayerEdge* prevEdge = edge1;
3179 const int nbSteps = 6;
3180 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3182 if ( !neighbor->_2neibors )
3183 break; // neighbor is on VERTEX
3185 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3186 if ( nextEdge == prevEdge )
3187 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3188 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
3189 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
3190 double r = double(step-1)/nbSteps;
3191 if ( !nextEdge->_2neibors )
3194 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3195 newNorm.Normalize();
3197 neighbor->_normal = newNorm;
3198 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3199 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3201 neighbor->InvalidateStep( 1 );
3203 neighbor->SetNewLength( data._stepSize, helper );
3205 // goto the next neighbor
3206 prevEdge = neighbor;
3207 neighbor = nextEdge;
3213 // 2) Check absence of intersections
3216 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3222 //================================================================================
3224 * \brief Looks for intersection of it's last segment with faces
3225 * \param distance - returns shortest distance from the last node to intersection
3227 //================================================================================
3229 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
3231 const double& epsilon,
3232 const SMDS_MeshElement** face)
3234 vector< const SMDS_MeshElement* > suspectFaces;
3236 gp_Ax1 lastSegment = LastSegment(segLen);
3237 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
3239 bool segmentIntersected = false;
3240 distance = Precision::Infinite();
3241 int iFace = -1; // intersected face
3242 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3244 const SMDS_MeshElement* face = suspectFaces[j];
3245 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3246 face->GetNodeIndex( _nodes[0] ) >= 0 )
3247 continue; // face sharing _LayerEdge node
3248 const int nbNodes = face->NbCornerNodes();
3249 bool intFound = false;
3251 SMDS_MeshElement::iterator nIt = face->begin_nodes();
3254 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3258 const SMDS_MeshNode* tria[3];
3261 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3264 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3270 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3271 segmentIntersected = true;
3272 if ( distance > dist )
3273 distance = dist, iFace = j;
3276 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3277 // if ( distance && iFace > -1 )
3279 // // distance is used to limit size of inflation step which depends on
3280 // // whether the intersected face bears viscous layers or not
3281 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3285 if ( segmentIntersected )
3288 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3289 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3290 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3291 << ", intersection with face ("
3292 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3293 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3294 << ") distance = " << distance - segLen<< endl;
3300 return segmentIntersected;
3303 //================================================================================
3305 * \brief Returns size and direction of the last segment
3307 //================================================================================
3309 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3311 // find two non-coincident positions
3312 gp_XYZ orig = _pos.back();
3314 int iPrev = _pos.size() - 2;
3315 while ( iPrev >= 0 )
3317 dir = orig - _pos[iPrev];
3318 if ( dir.SquareModulus() > 1e-100 )
3328 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3329 segDir.SetDirection( _normal );
3334 gp_Pnt pPrev = _pos[ iPrev ];
3335 if ( !_sWOL.IsNull() )
3337 TopLoc_Location loc;
3338 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3341 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3342 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3346 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3347 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3349 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3351 segDir.SetLocation( pPrev );
3352 segDir.SetDirection( dir );
3353 segLen = dir.Modulus();
3359 //================================================================================
3361 * \brief Test intersection of the last segment with a given triangle
3362 * using Moller-Trumbore algorithm
3363 * Intersection is detected if distance to intersection is less than _LayerEdge._len
3365 //================================================================================
3367 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
3368 const SMDS_MeshNode* n0,
3369 const SMDS_MeshNode* n1,
3370 const SMDS_MeshNode* n2,
3372 const double& EPSILON) const
3374 //const double EPSILON = 1e-6;
3376 gp_XYZ orig = lastSegment.Location().XYZ();
3377 gp_XYZ dir = lastSegment.Direction().XYZ();
3379 SMESH_TNodeXYZ vert0( n0 );
3380 SMESH_TNodeXYZ vert1( n1 );
3381 SMESH_TNodeXYZ vert2( n2 );
3383 /* calculate distance from vert0 to ray origin */
3384 gp_XYZ tvec = orig - vert0;
3386 if ( tvec * dir > EPSILON )
3387 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3390 gp_XYZ edge1 = vert1 - vert0;
3391 gp_XYZ edge2 = vert2 - vert0;
3393 /* begin calculating determinant - also used to calculate U parameter */
3394 gp_XYZ pvec = dir ^ edge2;
3396 /* if determinant is near zero, ray lies in plane of triangle */
3397 double det = edge1 * pvec;
3399 if (det > -EPSILON && det < EPSILON)
3401 double inv_det = 1.0 / det;
3403 /* calculate U parameter and test bounds */
3404 double u = ( tvec * pvec ) * inv_det;
3405 if (u < 0.0 || u > 1.0)
3408 /* prepare to test V parameter */
3409 gp_XYZ qvec = tvec ^ edge1;
3411 /* calculate V parameter and test bounds */
3412 double v = (dir * qvec) * inv_det;
3413 if ( v < 0.0 || u + v > 1.0 )
3416 /* calculate t, ray intersects triangle */
3417 t = (edge2 * qvec) * inv_det;
3419 // if (det < EPSILON)
3422 // /* calculate distance from vert0 to ray origin */
3423 // gp_XYZ tvec = orig - vert0;
3425 // /* calculate U parameter and test bounds */
3426 // double u = tvec * pvec;
3427 // if (u < 0.0 || u > det)
3430 // /* prepare to test V parameter */
3431 // gp_XYZ qvec = tvec ^ edge1;
3433 // /* calculate V parameter and test bounds */
3434 // double v = dir * qvec;
3435 // if (v < 0.0 || u + v > det)
3438 // /* calculate t, scale parameters, ray intersects triangle */
3439 // double t = edge2 * qvec;
3440 // double inv_det = 1.0 / det;
3448 //================================================================================
3450 * \brief Perform smooth of _LayerEdge's based on EDGE's
3451 * \retval bool - true if node has been moved
3453 //================================================================================
3455 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3456 const TopoDS_Face& F,
3457 SMESH_MesherHelper& helper)
3459 ASSERT( IsOnEdge() );
3461 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3462 SMESH_TNodeXYZ oldPos( tgtNode );
3463 double dist01, distNewOld;
3465 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3466 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3467 dist01 = p0.Distance( _2neibors->_nodes[1] );
3469 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3470 double lenDelta = 0;
3473 //lenDelta = _curvature->lenDelta( _len );
3474 lenDelta = _curvature->lenDeltaByDist( dist01 );
3475 newPos.ChangeCoord() += _normal * lenDelta;
3478 distNewOld = newPos.Distance( oldPos );
3482 if ( _2neibors->_plnNorm )
3484 // put newPos on the plane defined by source node and _plnNorm
3485 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3486 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3487 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3489 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3490 _pos.back() = newPos.XYZ();
3494 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3495 gp_XY uv( Precision::Infinite(), 0 );
3496 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3497 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3499 newPos = surface->Value( uv.X(), uv.Y() );
3500 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3503 if ( _curvature && lenDelta < 0 )
3505 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3506 _len -= prevPos.Distance( oldPos );
3507 _len += prevPos.Distance( newPos );
3509 bool moved = distNewOld > dist01/50;
3511 dumpMove( tgtNode ); // debug
3516 //================================================================================
3518 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3519 * \retval bool - true if _tgtNode has been moved
3521 //================================================================================
3523 bool _LayerEdge::Smooth(int& badNb)
3525 if ( _simplices.size() < 2 )
3526 return false; // _LayerEdge inflated along EDGE or FACE
3528 // compute new position for the last _pos
3529 gp_XYZ newPos (0,0,0);
3530 for ( size_t i = 0; i < _simplices.size(); ++i )
3531 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3532 newPos /= _simplices.size();
3535 newPos += _normal * _curvature->lenDelta( _len );
3537 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3538 // if ( _cosin < -0.1)
3540 // // Avoid decreasing length of edge on concave surface
3541 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3542 // gp_Vec newMove( prevPos, newPos );
3543 // newPos = _pos.back() + newMove.XYZ();
3545 // else if ( _cosin > 0.3 )
3547 // // Avoid increasing length of edge too much
3550 // count quality metrics (orientation) of tetras around _tgtNode
3552 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3553 for ( size_t i = 0; i < _simplices.size(); ++i )
3554 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3557 for ( size_t i = 0; i < _simplices.size(); ++i )
3558 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3560 if ( nbOkAfter < nbOkBefore )
3563 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3565 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3566 _len += prevPos.Distance(newPos);
3568 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3569 _pos.back() = newPos;
3571 badNb += _simplices.size() - nbOkAfter;
3578 //================================================================================
3580 * \brief Add a new segment to _LayerEdge during inflation
3582 //================================================================================
3584 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3586 if ( _len - len > -1e-6 )
3588 _pos.push_back( _pos.back() );
3592 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3593 SMESH_TNodeXYZ oldXYZ( n );
3594 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3595 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3597 _pos.push_back( nXYZ );
3599 if ( !_sWOL.IsNull() )
3602 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3604 double u = Precision::Infinite(); // to force projection w/o distance check
3605 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3606 _pos.back().SetCoord( u, 0, 0 );
3607 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3608 pos->SetUParameter( u );
3612 gp_XY uv( Precision::Infinite(), 0 );
3613 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3614 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3615 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3616 pos->SetUParameter( uv.X() );
3617 pos->SetVParameter( uv.Y() );
3619 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3621 dumpMove( n ); //debug
3624 //================================================================================
3626 * \brief Remove last inflation step
3628 //================================================================================
3630 void _LayerEdge::InvalidateStep( int curStep )
3632 if ( _pos.size() > curStep )
3634 _pos.resize( curStep );
3635 gp_Pnt nXYZ = _pos.back();
3636 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3637 if ( !_sWOL.IsNull() )
3639 TopLoc_Location loc;
3640 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3642 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3643 pos->SetUParameter( nXYZ.X() );
3645 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3646 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3650 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3651 pos->SetUParameter( nXYZ.X() );
3652 pos->SetVParameter( nXYZ.Y() );
3653 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3654 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3657 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3662 //================================================================================
3664 * \brief Create layers of prisms
3666 //================================================================================
3668 bool _ViscousBuilder::refine(_SolidData& data)
3670 SMESH_MesherHelper helper( *_mesh );
3671 helper.SetSubShape( data._solid );
3672 helper.SetElementsOnShape(false);
3674 Handle(Geom_Curve) curve;
3675 Handle(Geom_Surface) surface;
3676 TopoDS_Edge geomEdge;
3677 TopoDS_Face geomFace;
3678 TopoDS_Shape prevSWOL;
3679 TopLoc_Location loc;
3683 TGeomID prevBaseId = -1;
3684 TNode2Edge* n2eMap = 0;
3685 TNode2Edge::iterator n2e;
3687 for ( size_t i = 0; i < data._edges.size(); ++i )
3689 _LayerEdge& edge = *data._edges[i];
3691 // get accumulated length of segments
3692 vector< double > segLen( edge._pos.size() );
3694 for ( size_t j = 1; j < edge._pos.size(); ++j )
3695 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3697 // allocate memory for new nodes if it is not yet refined
3698 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3699 if ( edge._nodes.size() == 2 )
3701 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3703 edge._nodes.back() = tgtNode;
3705 // get data of a shrink shape
3706 if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
3708 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3711 geomEdge = TopoDS::Edge( edge._sWOL );
3712 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3716 geomFace = TopoDS::Face( edge._sWOL );
3717 surface = BRep_Tool::Surface( geomFace, loc );
3719 prevSWOL = edge._sWOL;
3721 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
3722 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
3723 if ( baseShapeId != prevBaseId )
3725 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
3726 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
3727 prevBaseId = baseShapeId;
3729 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
3731 _LayerEdge* foundEdge = n2e->second;
3732 const gp_XYZ& foundPos = foundEdge->_pos.back();
3733 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
3736 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
3737 epos->SetUParameter( foundPos.X() );
3741 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
3742 fpos->SetUParameter( foundPos.X() );
3743 fpos->SetVParameter( foundPos.Y() );
3746 // calculate height of the first layer
3748 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3749 const double f = data._hyp->GetStretchFactor();
3750 const int N = data._hyp->GetNumberLayers();
3751 const double fPowN = pow( f, N );
3752 if ( fPowN - 1 <= numeric_limits<double>::min() )
3755 h0 = T * ( f - 1 )/( fPowN - 1 );
3757 const double zeroLen = std::numeric_limits<double>::min();
3759 // create intermediate nodes
3760 double hSum = 0, hi = h0/f;
3762 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3764 // compute an intermediate position
3767 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3769 int iPrevSeg = iSeg-1;
3770 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3772 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3773 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3775 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3776 if ( !edge._sWOL.IsNull() )
3778 // compute XYZ by parameters <pos>
3783 pos = curve->Value( u ).Transformed(loc);
3787 uv.SetCoord( pos.X(), pos.Y() );
3789 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3792 // create or update the node
3795 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3796 if ( !edge._sWOL.IsNull() )
3799 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3801 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3805 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3810 if ( !edge._sWOL.IsNull() )
3812 // make average pos from new and current parameters
3815 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3816 pos = curve->Value( u ).Transformed(loc);
3818 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
3819 epos->SetUParameter( u );
3823 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3824 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3826 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
3827 fpos->SetUParameter( uv.X() );
3828 fpos->SetVParameter( uv.Y() );
3831 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3836 if ( !getMeshDS()->IsEmbeddedMode() )
3837 // Log node movement
3838 for ( size_t i = 0; i < data._edges.size(); ++i )
3840 _LayerEdge& edge = *data._edges[i];
3841 SMESH_TNodeXYZ p ( edge._nodes.back() );
3842 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3845 // TODO: make quadratic prisms and polyhedrons(?)
3847 helper.SetElementsOnShape(true);
3849 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3850 for ( ; exp.More(); exp.Next() )
3852 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3854 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3855 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3856 vector< vector<const SMDS_MeshNode*>* > nnVec;
3857 while ( fIt->more() )
3859 const SMDS_MeshElement* face = fIt->next();
3860 int nbNodes = face->NbCornerNodes();
3861 nnVec.resize( nbNodes );
3862 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3863 for ( int iN = 0; iN < nbNodes; ++iN )
3865 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3866 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3869 int nbZ = nnVec[0]->size();
3873 for ( int iZ = 1; iZ < nbZ; ++iZ )
3874 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3875 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3878 for ( int iZ = 1; iZ < nbZ; ++iZ )
3879 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3880 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3881 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3882 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3885 return error("Not supported type of element", data._index);
3892 //================================================================================
3894 * \brief Shrink 2D mesh on faces to let space for inflated layers
3896 //================================================================================
3898 bool _ViscousBuilder::shrink()
3900 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3901 // inflated along FACE or EDGE)
3902 map< TGeomID, _SolidData* > f2sdMap;
3903 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3905 _SolidData& data = _sdVec[i];
3906 TopTools_MapOfShape FFMap;
3907 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3908 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3909 if ( s2s->second.ShapeType() == TopAbs_FACE )
3911 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3913 if ( FFMap.Add( (*s2s).second ))
3914 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3915 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3916 // by StdMeshers_QuadToTriaAdaptor
3917 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3919 SMESH_ProxyMesh::SubMesh* proxySub =
3920 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3921 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3922 while ( fIt->more() )
3923 proxySub->AddElement( fIt->next() );
3924 // as a result 3D algo will use elements from proxySub and not from smDS
3929 SMESH_MesherHelper helper( *_mesh );
3930 helper.ToFixNodeParameters( true );
3933 map< TGeomID, _Shrinker1D > e2shrMap;
3935 // loop on FACES to srink mesh on
3936 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3937 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3939 _SolidData& data = *f2sd->second;
3940 TNode2Edge& n2eMap = data._n2eMap;
3941 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3943 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3945 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3946 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3948 helper.SetSubShape(F);
3950 // ===========================
3951 // Prepare data for shrinking
3952 // ===========================
3954 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3955 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3956 vector < const SMDS_MeshNode* > smoothNodes;
3958 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3959 while ( nIt->more() )
3961 const SMDS_MeshNode* n = nIt->next();
3962 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3963 smoothNodes.push_back( n );
3966 // Find out face orientation
3968 const set<TGeomID> ignoreShapes;
3970 if ( !smoothNodes.empty() )
3972 vector<_Simplex> simplices;
3973 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3974 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3975 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3976 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3977 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3981 // Find _LayerEdge's inflated along F
3982 vector< _LayerEdge* > lEdges;
3984 SMESH_subMeshIteratorPtr subIt =
3985 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3986 while ( subIt->more() )
3988 SMESH_subMesh* sub = subIt->next();
3989 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3990 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3992 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3993 while ( nIt->more() )
3995 _LayerEdge* edge = n2eMap[ nIt->next() ];
3996 lEdges.push_back( edge );
3997 prepareEdgeToShrink( *edge, F, helper, smDS );
4002 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
4003 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4004 while ( fIt->more() )
4005 if ( const SMDS_MeshElement* f = fIt->next() )
4006 dumpChangeNodes( f );
4008 // Replace source nodes by target nodes in mesh faces to shrink
4009 const SMDS_MeshNode* nodes[20];
4010 for ( size_t i = 0; i < lEdges.size(); ++i )
4012 _LayerEdge& edge = *lEdges[i];
4013 const SMDS_MeshNode* srcNode = edge._nodes[0];
4014 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4015 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4016 while ( fIt->more() )
4018 const SMDS_MeshElement* f = fIt->next();
4019 if ( !smDS->Contains( f ))
4021 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
4022 for ( int iN = 0; nIt->more(); ++iN )
4024 const SMDS_MeshNode* n = nIt->next();
4025 nodes[iN] = ( n == srcNode ? tgtNode : n );
4027 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
4031 // find out if a FACE is concave
4032 const bool isConcaveFace = isConcave( F, helper );
4034 // Create _SmoothNode's on face F
4035 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
4037 const bool sortSimplices = isConcaveFace;
4038 for ( size_t i = 0; i < smoothNodes.size(); ++i )
4040 const SMDS_MeshNode* n = smoothNodes[i];
4041 nodesToSmooth[ i ]._node = n;
4042 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
4043 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
4044 // fix up incorrect uv of nodes on the FACE
4045 helper.GetNodeUV( F, n, 0, &isOkUV);
4049 //if ( nodesToSmooth.empty() ) continue;
4051 // Find EDGE's to shrink and set simpices to LayerEdge's
4052 set< _Shrinker1D* > eShri1D;
4054 for ( size_t i = 0; i < lEdges.size(); ++i )
4056 _LayerEdge* edge = lEdges[i];
4057 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4059 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4060 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4061 eShri1D.insert( & srinker );
4062 srinker.AddEdge( edge, helper );
4063 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4064 // restore params of nodes on EGDE if the EDGE has been already
4065 // srinked while srinking another FACE
4066 srinker.RestoreParams();
4068 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4072 bool toFixTria = false; // to improve quality of trias by diagonal swap
4073 if ( isConcaveFace )
4075 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4076 if ( hasTria != hasQuad ) {
4077 toFixTria = hasTria;
4080 set<int> nbNodesSet;
4081 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4082 while ( fIt->more() && nbNodesSet.size() < 2 )
4083 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4084 toFixTria = ( *nbNodesSet.begin() == 3 );
4088 // ==================
4089 // Perform shrinking
4090 // ==================
4092 bool shrinked = true;
4093 int badNb, shriStep=0, smooStep=0;
4094 _SmoothNode::SmoothType smoothType
4095 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4099 // Move boundary nodes (actually just set new UV)
4100 // -----------------------------------------------
4101 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4103 for ( size_t i = 0; i < lEdges.size(); ++i )
4105 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4109 // Move nodes on EDGE's
4110 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4111 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4112 for ( ; shr != eShri1D.end(); ++shr )
4113 (*shr)->Compute( /*set3D=*/false, helper );
4116 // -----------------
4117 int nbNoImpSteps = 0;
4120 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4122 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4124 int oldBadNb = badNb;
4127 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4129 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4130 smoothType, /*set3D=*/isConcaveFace);
4132 if ( badNb < oldBadNb )
4140 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4141 if ( shriStep > 200 )
4142 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4144 // Fix narrow triangles by swapping diagonals
4145 // ---------------------------------------
4148 set<const SMDS_MeshNode*> usedNodes;
4149 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4151 // update working data
4152 set<const SMDS_MeshNode*>::iterator n;
4153 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4155 n = usedNodes.find( nodesToSmooth[ i ]._node );
4156 if ( n != usedNodes.end())
4158 getSimplices( nodesToSmooth[ i ]._node,
4159 nodesToSmooth[ i ]._simplices,
4161 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4162 usedNodes.erase( n );
4165 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4167 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4168 if ( n != usedNodes.end())
4170 getSimplices( lEdges[i]->_nodes.back(),
4171 lEdges[i]->_simplices,
4173 usedNodes.erase( n );
4177 } // while ( shrinked )
4179 // No wrongly shaped faces remain; final smooth. Set node XYZ.
4180 bool isStructuredFixed = false;
4181 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4182 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4183 if ( !isStructuredFixed )
4185 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4186 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4188 for ( int st = 3; st; --st )
4191 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4192 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4193 case 3: smoothType = _SmoothNode::ANGULAR; break;
4195 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4196 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4198 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4199 smoothType,/*set3D=*/st==1 );
4204 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4205 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4207 if ( !getMeshDS()->IsEmbeddedMode() )
4208 // Log node movement
4209 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4211 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4212 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4215 } // loop on FACES to srink mesh on
4218 // Replace source nodes by target nodes in shrinked mesh edges
4220 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4221 for ( ; e2shr != e2shrMap.end(); ++e2shr )
4222 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4227 //================================================================================
4229 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4231 //================================================================================
4233 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
4234 const TopoDS_Face& F,
4235 SMESH_MesherHelper& helper,
4236 const SMESHDS_SubMesh* faceSubMesh)
4238 const SMDS_MeshNode* srcNode = edge._nodes[0];
4239 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4243 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4245 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4246 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4247 gp_Vec2d uvDir( srcUV, tgtUV );
4248 double uvLen = uvDir.Magnitude();
4250 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4253 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4254 // vector<const SMDS_MeshElement*> faces;
4255 // multimap< double, const SMDS_MeshNode* > proj2node;
4256 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4257 // while ( fIt->more() )
4259 // const SMDS_MeshElement* f = fIt->next();
4260 // if ( faceSubMesh->Contains( f ))
4261 // faces.push_back( f );
4263 // for ( size_t i = 0; i < faces.size(); ++i )
4265 // const int nbNodes = faces[i]->NbCornerNodes();
4266 // for ( int j = 0; j < nbNodes; ++j )
4268 // const SMDS_MeshNode* n = faces[i]->GetNode(j);
4269 // if ( n == srcNode ) continue;
4270 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
4271 // ( faces.size() > 1 || nbNodes > 3 ))
4273 // gp_Pnt2d uv = helper.GetNodeUV( F, n );
4274 // gp_Vec2d uvDirN( srcUV, uv );
4275 // double proj = uvDirN * uvDir;
4276 // proj2node.insert( make_pair( proj, n ));
4280 // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4281 // const double minProj = p2n->first;
4282 // const double projThreshold = 1.1 * uvLen;
4283 // if ( minProj > projThreshold )
4285 // // tgtNode is located so that it does not make faces with wrong orientation
4288 edge._pos.resize(1);
4289 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4291 // store most risky nodes in _simplices
4292 // p2nEnd = proj2node.lower_bound( projThreshold );
4293 // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4294 // edge._simplices.resize( nbSimpl );
4295 // for ( int i = 0; i < nbSimpl; ++i )
4297 // edge._simplices[i]._nPrev = p2n->second;
4298 // if ( ++p2n != p2nEnd )
4299 // edge._simplices[i]._nNext = p2n->second;
4301 // set UV of source node to target node
4302 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4303 pos->SetUParameter( srcUV.X() );
4304 pos->SetVParameter( srcUV.Y() );
4306 else // _sWOL is TopAbs_EDGE
4308 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4309 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4310 if ( !edgeSM || edgeSM->NbElements() == 0 )
4311 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4313 const SMDS_MeshNode* n2 = 0;
4314 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4315 while ( eIt->more() && !n2 )
4317 const SMDS_MeshElement* e = eIt->next();
4318 if ( !edgeSM->Contains(e)) continue;
4319 n2 = e->GetNode( 0 );
4320 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4323 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4325 double uSrc = helper.GetNodeU( E, srcNode, n2 );
4326 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4327 double u2 = helper.GetNodeU( E, n2, srcNode );
4329 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4331 // tgtNode is located so that it does not make faces with wrong orientation
4334 edge._pos.resize(1);
4335 edge._pos[0].SetCoord( U_TGT, uTgt );
4336 edge._pos[0].SetCoord( U_SRC, uSrc );
4337 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4339 edge._simplices.resize( 1 );
4340 edge._simplices[0]._nPrev = n2;
4342 // set UV of source node to target node
4343 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4344 pos->SetUParameter( uSrc );
4348 //================================================================================
4350 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4352 //================================================================================
4354 // Compute UV to follow during shrinking
4356 // const SMDS_MeshNode* srcNode = edge._nodes[0];
4357 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
4359 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4360 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4361 // gp_Vec2d uvDir( srcUV, tgtUV );
4362 // double uvLen = uvDir.Magnitude();
4365 // // Select shrinking step such that not to make faces with wrong orientation.
4366 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4367 // const double minStepSize = uvLen / 20;
4368 // double stepSize = uvLen;
4369 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4370 // while ( fIt->more() )
4372 // const SMDS_MeshElement* f = fIt->next();
4373 // if ( !faceSubMesh->Contains( f )) continue;
4374 // const int nbNodes = f->NbCornerNodes();
4375 // for ( int i = 0; i < nbNodes; ++i )
4377 // const SMDS_MeshNode* n = f->GetNode(i);
4378 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4380 // gp_XY uv = helper.GetNodeUV( F, n );
4381 // gp_Vec2d uvDirN( srcUV, uv );
4382 // double proj = uvDirN * uvDir;
4383 // if ( proj < stepSize && proj > minStepSize )
4389 // const int nbSteps = ceil( uvLen / stepSize );
4390 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4391 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4392 // edge._pos.resize( nbSteps );
4393 // edge._pos[0] = tgtUV0;
4394 // for ( int i = 1; i < nbSteps; ++i )
4396 // double r = i / double( nbSteps );
4397 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4402 //================================================================================
4404 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4406 //================================================================================
4408 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
4409 SMESH_MesherHelper& helper,
4412 set<const SMDS_MeshNode*> * involvedNodes)
4414 SMESH::Controls::AspectRatio qualifier;
4415 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4416 const double maxAspectRatio = is2D ? 4. : 2;
4417 NodeCoordHelper xyz( F, helper, is2D );
4419 // find bad triangles
4421 vector< const SMDS_MeshElement* > badTrias;
4422 vector< double > badAspects;
4423 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
4424 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4425 while ( fIt->more() )
4427 const SMDS_MeshElement * f = fIt->next();
4428 if ( f->NbCornerNodes() != 3 ) continue;
4429 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4430 double aspect = qualifier.GetValue( points );
4431 if ( aspect > maxAspectRatio )
4433 badTrias.push_back( f );
4434 badAspects.push_back( aspect );
4439 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4440 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4441 while ( fIt->more() )
4443 const SMDS_MeshElement * f = fIt->next();
4444 if ( f->NbCornerNodes() == 3 )
4445 dumpChangeNodes( f );
4449 if ( badTrias.empty() )
4452 // find couples of faces to swap diagonal
4454 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4455 vector< T2Trias > triaCouples;
4457 TIDSortedElemSet involvedFaces, emptySet;
4458 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4461 double aspRatio [3];
4464 if ( !involvedFaces.insert( badTrias[iTia] ).second )
4466 for ( int iP = 0; iP < 3; ++iP )
4467 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4469 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4470 int bestCouple = -1;
4471 for ( int iSide = 0; iSide < 3; ++iSide )
4473 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4474 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4475 trias [iSide].first = badTrias[iTia];
4476 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4478 if (( ! trias[iSide].second ) ||
4479 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4480 ( ! sm->Contains( trias[iSide].second )))
4483 // aspect ratio of an adjacent tria
4484 for ( int iP = 0; iP < 3; ++iP )
4485 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4486 double aspectInit = qualifier.GetValue( points2 );
4488 // arrange nodes as after diag-swaping
4489 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4490 i3 = helper.WrapIndex( i1-1, 3 );
4492 i3 = helper.WrapIndex( i1+1, 3 );
4494 points1( 1+ iSide ) = points2( 1+ i3 );
4495 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
4497 // aspect ratio after diag-swaping
4498 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4499 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4502 // prevent inversion of a triangle
4503 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4504 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4505 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4508 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4512 if ( bestCouple >= 0 )
4514 triaCouples.push_back( trias[bestCouple] );
4515 involvedFaces.insert ( trias[bestCouple].second );
4519 involvedFaces.erase( badTrias[iTia] );
4522 if ( triaCouples.empty() )
4527 SMESH_MeshEditor editor( helper.GetMesh() );
4528 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4529 for ( size_t i = 0; i < triaCouples.size(); ++i )
4531 dumpChangeNodes( triaCouples[i].first );
4532 dumpChangeNodes( triaCouples[i].second );
4533 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4536 if ( involvedNodes )
4537 for ( size_t i = 0; i < triaCouples.size(); ++i )
4539 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4540 triaCouples[i].first->end_nodes() );
4541 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4542 triaCouples[i].second->end_nodes() );
4545 // just for debug dump resulting triangles
4546 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4547 for ( size_t i = 0; i < triaCouples.size(); ++i )
4549 dumpChangeNodes( triaCouples[i].first );
4550 dumpChangeNodes( triaCouples[i].second );
4554 //================================================================================
4556 * \brief Move target node to it's final position on the FACE during shrinking
4558 //================================================================================
4560 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4561 const TopoDS_Face& F,
4562 SMESH_MesherHelper& helper )
4565 return false; // already at the target position
4567 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4569 if ( _sWOL.ShapeType() == TopAbs_FACE )
4571 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4572 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4573 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4574 const double uvLen = tgtUV.Distance( curUV );
4575 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4577 // Select shrinking step such that not to make faces with wrong orientation.
4578 double stepSize = uvLen;
4579 for ( size_t i = 0; i < _simplices.size(); ++i )
4581 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4582 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4583 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4584 gp_XY dirN = uvN2 - uvN1;
4585 double det = uvDir.Crossed( dirN );
4586 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
4587 gp_XY dirN2Cur = curUV - uvN1;
4588 double step = dirN.Crossed( dirN2Cur ) / det;
4590 stepSize = Min( step, stepSize );
4593 if ( uvLen - stepSize < _len / 200. )
4598 else if ( stepSize > 0 )
4600 newUV = curUV + uvDir.XY() * stepSize * kSafe;
4606 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4607 pos->SetUParameter( newUV.X() );
4608 pos->SetVParameter( newUV.Y() );
4611 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4612 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4613 dumpMove( tgtNode );
4616 else // _sWOL is TopAbs_EDGE
4618 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4619 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4620 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4622 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4623 const double uSrc = _pos[0].Coord( U_SRC );
4624 const double lenTgt = _pos[0].Coord( LEN_TGT );
4626 double newU = _pos[0].Coord( U_TGT );
4627 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4633 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4635 tgtPos->SetUParameter( newU );
4637 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4638 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4639 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4640 dumpMove( tgtNode );
4646 //================================================================================
4648 * \brief Perform smooth on the FACE
4649 * \retval bool - true if the node has been moved
4651 //================================================================================
4653 bool _SmoothNode::Smooth(int& badNb,
4654 Handle(Geom_Surface)& surface,
4655 SMESH_MesherHelper& helper,
4656 const double refSign,
4660 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4662 // get uv of surrounding nodes
4663 vector<gp_XY> uv( _simplices.size() );
4664 for ( size_t i = 0; i < _simplices.size(); ++i )
4665 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4667 // compute new UV for the node
4669 if ( how == TFI && _simplices.size() == 4 )
4672 for ( size_t i = 0; i < _simplices.size(); ++i )
4673 if ( _simplices[i]._nOpp )
4674 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4676 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4678 newPos = helper.calcTFI ( 0.5, 0.5,
4679 corners[0], corners[1], corners[2], corners[3],
4680 uv[1], uv[2], uv[3], uv[0] );
4682 else if ( how == ANGULAR )
4684 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4686 else if ( how == CENTROIDAL && _simplices.size() > 3 )
4688 // average centers of diagonals wieghted with their reciprocal lengths
4689 if ( _simplices.size() == 4 )
4691 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4692 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4693 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4697 double sumWeight = 0;
4698 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4699 for ( int i = 0; i < nb; ++i )
4702 int iTo = i + _simplices.size() - 1;
4703 for ( int j = iFrom; j < iTo; ++j )
4705 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4706 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4708 newPos += w * ( uv[i]+uv[i2] );
4711 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4717 for ( size_t i = 0; i < _simplices.size(); ++i )
4719 newPos /= _simplices.size();
4722 // count quality metrics (orientation) of triangles around the node
4724 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4725 for ( size_t i = 0; i < _simplices.size(); ++i )
4726 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4729 for ( size_t i = 0; i < _simplices.size(); ++i )
4730 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4732 if ( nbOkAfter < nbOkBefore )
4734 badNb += _simplices.size() - nbOkBefore;
4738 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4739 pos->SetUParameter( newPos.X() );
4740 pos->SetVParameter( newPos.Y() );
4747 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4748 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4752 badNb += _simplices.size() - nbOkAfter;
4753 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4756 //================================================================================
4758 * \brief Computes new UV using angle based smoothing technic
4760 //================================================================================
4762 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4763 const gp_XY& uvToFix,
4764 const double refSign)
4766 uv.push_back( uv.front() );
4768 vector< gp_XY > edgeDir ( uv.size() );
4769 vector< double > edgeSize( uv.size() );
4770 for ( size_t i = 1; i < edgeDir.size(); ++i )
4772 edgeDir [i-1] = uv[i] - uv[i-1];
4773 edgeSize[i-1] = edgeDir[i-1].Modulus();
4774 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4775 edgeDir[i-1].SetX( 100 );
4777 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4779 edgeDir.back() = edgeDir.front();
4780 edgeSize.back() = edgeSize.front();
4785 for ( size_t i = 1; i < edgeDir.size(); ++i )
4787 if ( edgeDir[i-1].X() > 1. ) continue;
4789 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4790 if ( i == edgeDir.size() ) break;
4792 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4793 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4794 gp_XY bisec = norm1 + norm2;
4795 double bisecSize = bisec.Modulus();
4796 if ( bisecSize < numeric_limits<double>::min() )
4798 bisec = -edgeDir[i1] + edgeDir[i];
4799 bisecSize = bisec.Modulus();
4803 gp_XY dirToN = uvToFix - p;
4804 double distToN = dirToN.Modulus();
4805 if ( bisec * dirToN < 0 )
4808 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4810 sumSize += edgeSize[i1] + edgeSize[i];
4812 newPos /= /*nbEdges * */sumSize;
4816 //================================================================================
4818 * \brief Delete _SolidData
4820 //================================================================================
4822 _SolidData::~_SolidData()
4824 for ( size_t i = 0; i < _edges.size(); ++i )
4826 if ( _edges[i] && _edges[i]->_2neibors )
4827 delete _edges[i]->_2neibors;
4832 //================================================================================
4834 * \brief Add a _LayerEdge inflated along the EDGE
4836 //================================================================================
4838 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4841 if ( _nodes.empty() )
4843 _edges[0] = _edges[1] = 0;
4847 if ( e == _edges[0] || e == _edges[1] )
4849 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4850 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4851 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4852 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4855 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4857 BRep_Tool::Range( E, f,l );
4858 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4859 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4863 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4864 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4866 if ( _nodes.empty() )
4868 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4869 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4871 TopLoc_Location loc;
4872 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4873 GeomAdaptor_Curve aCurve(C, f,l);
4874 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4876 int nbExpectNodes = eSubMesh->NbNodes();
4877 _initU .reserve( nbExpectNodes );
4878 _normPar.reserve( nbExpectNodes );
4879 _nodes .reserve( nbExpectNodes );
4880 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4881 while ( nIt->more() )
4883 const SMDS_MeshNode* node = nIt->next();
4884 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4885 node == tgtNode0 || node == tgtNode1 )
4886 continue; // refinement nodes
4887 _nodes.push_back( node );
4888 _initU.push_back( helper.GetNodeU( E, node ));
4889 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4890 _normPar.push_back( len / totLen );
4895 // remove target node of the _LayerEdge from _nodes
4897 for ( size_t i = 0; i < _nodes.size(); ++i )
4898 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4899 _nodes[i] = 0, nbFound++;
4900 if ( nbFound == _nodes.size() )
4905 //================================================================================
4907 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4909 //================================================================================
4911 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4913 if ( _done || _nodes.empty())
4915 const _LayerEdge* e = _edges[0];
4916 if ( !e ) e = _edges[1];
4919 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4920 ( !_edges[1] || _edges[1]->_pos.empty() ));
4922 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4924 if ( set3D || _done )
4926 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4927 GeomAdaptor_Curve aCurve(C, f,l);
4930 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4932 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4933 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4935 for ( size_t i = 0; i < _nodes.size(); ++i )
4937 if ( !_nodes[i] ) continue;
4938 double len = totLen * _normPar[i];
4939 GCPnts_AbscissaPoint discret( aCurve, len, f );
4940 if ( !discret.IsDone() )
4941 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4942 double u = discret.Parameter();
4943 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4944 pos->SetUParameter( u );
4945 gp_Pnt p = C->Value( u );
4946 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4951 BRep_Tool::Range( E, f,l );
4953 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4955 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4957 for ( size_t i = 0; i < _nodes.size(); ++i )
4959 if ( !_nodes[i] ) continue;
4960 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4961 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4962 pos->SetUParameter( u );
4967 //================================================================================
4969 * \brief Restore initial parameters of nodes on EDGE
4971 //================================================================================
4973 void _Shrinker1D::RestoreParams()
4976 for ( size_t i = 0; i < _nodes.size(); ++i )
4978 if ( !_nodes[i] ) continue;
4979 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4980 pos->SetUParameter( _initU[i] );
4985 //================================================================================
4987 * \brief Replace source nodes by target nodes in shrinked mesh edges
4989 //================================================================================
4991 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4993 const SMDS_MeshNode* nodes[3];
4994 for ( int i = 0; i < 2; ++i )
4996 if ( !_edges[i] ) continue;
4998 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4999 if ( !eSubMesh ) return;
5000 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
5001 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
5002 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5003 while ( eIt->more() )
5005 const SMDS_MeshElement* e = eIt->next();
5006 if ( !eSubMesh->Contains( e ))
5008 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5009 for ( int iN = 0; iN < e->NbNodes(); ++iN )
5011 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
5012 nodes[iN] = ( n == srcNode ? tgtNode : n );
5014 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
5019 //================================================================================
5021 * \brief Creates 2D and 1D elements on boundaries of new prisms
5023 //================================================================================
5025 bool _ViscousBuilder::addBoundaryElements()
5027 SMESH_MesherHelper helper( *_mesh );
5029 for ( size_t i = 0; i < _sdVec.size(); ++i )
5031 _SolidData& data = _sdVec[i];
5032 TopTools_IndexedMapOfShape geomEdges;
5033 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
5034 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
5036 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
5038 // Get _LayerEdge's based on E
5040 map< double, const SMDS_MeshNode* > u2nodes;
5041 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
5044 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
5045 TNode2Edge & n2eMap = data._n2eMap;
5046 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5048 //check if 2D elements are needed on E
5049 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5050 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5051 ledges.push_back( n2e->second );
5053 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5054 continue; // no layers on E
5055 ledges.push_back( n2eMap[ u2n->second ]);
5057 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5058 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5059 int nbSharedPyram = 0;
5060 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5061 while ( vIt->more() )
5063 const SMDS_MeshElement* v = vIt->next();
5064 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5066 if ( nbSharedPyram > 1 )
5067 continue; // not free border of the pyramid
5069 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5070 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5071 continue; // faces already created
5073 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5074 ledges.push_back( n2eMap[ u2n->second ]);
5076 // Find out orientation and type of face to create
5078 bool reverse = false, isOnFace;
5080 map< TGeomID, TopoDS_Shape >::iterator e2f =
5081 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5083 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5085 F = e2f->second.Oriented( TopAbs_FORWARD );
5086 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5087 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5088 reverse = !reverse, F.Reverse();
5089 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5094 // find FACE with layers sharing E
5095 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5096 while ( fIt->more() && F.IsNull() )
5098 const TopoDS_Shape* pF = fIt->next();
5099 if ( helper.IsSubShape( *pF, data._solid) &&
5100 !data._ignoreFaceIds.count( e2f->first ))
5104 // Find the sub-mesh to add new faces
5105 SMESHDS_SubMesh* sm = 0;
5107 sm = getMeshDS()->MeshElements( F );
5109 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5111 return error("error in addBoundaryElements()", data._index);
5114 const int dj1 = reverse ? 0 : 1;
5115 const int dj2 = reverse ? 1 : 0;
5116 for ( size_t j = 1; j < ledges.size(); ++j )
5118 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
5119 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
5121 for ( size_t z = 1; z < nn1.size(); ++z )
5122 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5124 for ( size_t z = 1; z < nn1.size(); ++z )
5125 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5129 for ( int isFirst = 0; isFirst < 2; ++isFirst )
5131 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5132 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5134 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
5135 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5137 helper.SetSubShape( edge->_sWOL );
5138 helper.SetElementsOnShape( true );
5139 for ( size_t z = 1; z < nn.size(); ++z )
5140 helper.AddEdge( nn[z-1], nn[z] );