1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B2d.hxx>
50 #include <Bnd_B3d.hxx>
52 #include <GCPnts_AbscissaPoint.hxx>
53 #include <Geom2d_Circle.hxx>
54 #include <Geom2d_Line.hxx>
55 #include <Geom2d_TrimmedCurve.hxx>
56 #include <GeomAdaptor_Curve.hxx>
57 #include <GeomLib.hxx>
58 #include <Geom_Circle.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Line.hxx>
61 #include <Geom_TrimmedCurve.hxx>
62 #include <Precision.hxx>
63 #include <Standard_ErrorHandler.hxx>
64 #include <TColStd_Array1OfReal.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_IndexedMapOfShape.hxx>
68 #include <TopTools_ListOfShape.hxx>
69 #include <TopTools_MapOfShape.hxx>
71 #include <TopoDS_Edge.hxx>
72 #include <TopoDS_Face.hxx>
73 #include <TopoDS_Vertex.hxx>
87 //================================================================================
92 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
95 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
96 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
98 struct _MeshOfSolid : public SMESH_ProxyMesh,
99 public SMESH_subMeshEventListenerData
101 bool _n2nMapComputed;
103 _MeshOfSolid( SMESH_Mesh* mesh)
104 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
106 SMESH_ProxyMesh::setMesh( *mesh );
109 // returns submesh for a geom face
110 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
112 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
113 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
115 void setNode2Node(const SMDS_MeshNode* srcNode,
116 const SMDS_MeshNode* proxyNode,
117 const SMESH_ProxyMesh::SubMesh* subMesh)
119 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
122 //--------------------------------------------------------------------------------
124 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
125 * It is used to clear an inferior dim sub-meshes modified by viscous layers
127 class _ShrinkShapeListener : SMESH_subMeshEventListener
129 _ShrinkShapeListener()
130 : SMESH_subMeshEventListener(/*isDeletable=*/false,
131 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
133 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
134 virtual void ProcessEvent(const int event,
136 SMESH_subMesh* solidSM,
137 SMESH_subMeshEventListenerData* data,
138 const SMESH_Hypothesis* hyp)
140 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
142 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
146 //--------------------------------------------------------------------------------
148 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
149 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
150 * delete the data as soon as it has been used
152 class _ViscousListener : SMESH_subMeshEventListener
155 SMESH_subMeshEventListener(/*isDeletable=*/false,
156 "StdMeshers_ViscousLayers::_ViscousListener") {}
157 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
159 virtual void ProcessEvent(const int event,
161 SMESH_subMesh* subMesh,
162 SMESH_subMeshEventListenerData* data,
163 const SMESH_Hypothesis* hyp)
165 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
167 // delete SMESH_ProxyMesh containing temporary faces
168 subMesh->DeleteEventListener( this );
171 // Finds or creates proxy mesh of the solid
172 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
173 const TopoDS_Shape& solid,
176 if ( !mesh ) return 0;
177 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
178 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
179 if ( !data && toCreate )
181 data = new _MeshOfSolid(mesh);
182 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
183 sm->SetEventListener( Get(), data, sm );
187 // Removes proxy mesh of the solid
188 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
190 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
194 //================================================================================
196 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
197 * the main shape when sub-mesh of the main shape is cleared,
198 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
201 //================================================================================
203 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
205 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
206 SMESH_subMeshEventListenerData* data =
207 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
210 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
211 data->mySubMeshes.end())
212 data->mySubMeshes.push_back( sub );
216 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
217 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
220 //--------------------------------------------------------------------------------
222 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
223 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
224 * The class is used to check validity of face or volumes around a smoothed node;
225 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
229 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
230 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
231 _Simplex(const SMDS_MeshNode* nPrev=0,
232 const SMDS_MeshNode* nNext=0,
233 const SMDS_MeshNode* nOpp=0)
234 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
235 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
237 const double M[3][3] =
238 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
239 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
240 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
241 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
242 + M[0][1]*M[1][2]*M[2][0]
243 + M[0][2]*M[1][0]*M[2][1]
244 - M[0][0]*M[1][2]*M[2][1]
245 - M[0][1]*M[1][0]*M[2][2]
246 - M[0][2]*M[1][1]*M[2][0]);
247 return determinant > 1e-100;
249 bool IsForward(const gp_XY& tgtUV,
250 const SMDS_MeshNode* smoothedNode,
251 const TopoDS_Face& face,
252 SMESH_MesherHelper& helper,
253 const double refSign) const
255 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
256 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
257 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
259 return d*refSign > 1e-100;
261 bool IsNeighbour(const _Simplex& other) const
263 return _nPrev == other._nNext || _nNext == other._nPrev;
266 //--------------------------------------------------------------------------------
268 * Structure used to take into account surface curvature while smoothing
273 double _k; // factor to correct node smoothed position
274 double _h2lenRatio; // avgNormProj / (2*avgDist)
276 static _Curvature* New( double avgNormProj, double avgDist )
279 if ( fabs( avgNormProj / avgDist ) > 1./200 )
282 c->_r = avgDist * avgDist / avgNormProj;
283 c->_k = avgDist * avgDist / c->_r / c->_r;
284 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
285 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
289 double lenDelta(double len) const { return _k * ( _r + len ); }
290 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
293 //--------------------------------------------------------------------------------
295 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
299 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
300 const SMDS_MeshNode* _nodes[2];
301 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
303 double _wgt[2]; // weights of _nodes
304 _LayerEdge* _edges[2];
306 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
309 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
311 std::swap( _nodes[0], _nodes[1] );
312 std::swap( _wgt[0], _wgt[1] );
315 //--------------------------------------------------------------------------------
317 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
318 * and a node of the most internal layer (_nodes.back())
322 vector< const SMDS_MeshNode*> _nodes;
324 gp_XYZ _normal; // to solid surface
325 vector<gp_XYZ> _pos; // points computed during inflation
326 double _len; // length achived with the last step
327 double _cosin; // of angle (_normal ^ surface)
328 double _lenFactor; // to compute _len taking _cosin into account
330 // face or edge w/o layer along or near which _LayerEdge is inflated
332 // simplices connected to the source node (_nodes[0]);
333 // used for smoothing and quality check of _LayerEdge's based on the FACE
334 vector<_Simplex> _simplices;
335 // data for smoothing of _LayerEdge's based on the EDGE
336 _2NearEdges* _2neibors;
338 _Curvature* _curvature;
339 // TODO:: detele _Curvature, _plnNorm
341 void SetNewLength( double len, SMESH_MesherHelper& helper );
342 bool SetNewLength2d( Handle(Geom_Surface)& surface,
343 const TopoDS_Face& F,
344 SMESH_MesherHelper& helper );
345 void SetDataByNeighbors( const SMDS_MeshNode* n1,
346 const SMDS_MeshNode* n2,
347 SMESH_MesherHelper& helper);
348 void InvalidateStep( int curStep );
349 bool Smooth(int& badNb);
350 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
351 const TopoDS_Face& F,
352 SMESH_MesherHelper& helper);
353 bool FindIntersection( SMESH_ElementSearcher& searcher,
355 const double& epsilon,
356 const SMDS_MeshElement** face = 0);
357 bool SegTriaInter( const gp_Ax1& lastSegment,
358 const SMDS_MeshNode* n0,
359 const SMDS_MeshNode* n1,
360 const SMDS_MeshNode* n2,
362 const double& epsilon) const;
363 gp_Ax1 LastSegment(double& segLen) const;
364 bool IsOnEdge() const { return _2neibors; }
365 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
366 void SetCosin( double cosin );
370 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
372 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
373 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
376 //--------------------------------------------------------------------------------
378 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
380 //--------------------------------------------------------------------------------
382 * \brief Data of a SOLID
387 const StdMeshers_ViscousLayers* _hyp;
388 TopoDS_Shape _hypShape;
389 _MeshOfSolid* _proxyMesh;
390 set<TGeomID> _reversedFaceIds;
391 set<TGeomID> _ignoreFaceIds;
393 double _stepSize, _stepSizeCoeff;
394 const SMDS_MeshNode* _stepSizeNodes[2];
397 // edges of _n2eMap. We keep same data in two containers because
398 // iteration over the map is 5 time longer than over the vector
399 vector< _LayerEdge* > _edges;
401 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
402 // layers and a FACE w/o layers
403 // value: the shape (FACE or EDGE) to shrink mesh on.
404 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
405 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
407 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
408 set< TGeomID > _noShrinkFaces;
410 // <EDGE to smooth on> to <it's curve>
411 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
413 // end indices in _edges of _LayerEdge on one shape to smooth
414 vector< int > _endEdgeToSmooth;
416 double _epsilon; // precision for SegTriaInter()
418 int _index; // for debug
420 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
421 const StdMeshers_ViscousLayers* h=0,
422 const TopoDS_Shape& hs=TopoDS_Shape(),
424 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
427 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
430 Handle(Geom_Surface)& surface,
431 const TopoDS_Face& F,
432 SMESH_MesherHelper& helper);
434 //--------------------------------------------------------------------------------
436 * \brief Data of node on a shrinked FACE
440 const SMDS_MeshNode* _node;
441 //vector<const SMDS_MeshNode*> _nodesAround;
442 vector<_Simplex> _simplices; // for quality check
444 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
446 bool Smooth(int& badNb,
447 Handle(Geom_Surface)& surface,
448 SMESH_MesherHelper& helper,
449 const double refSign,
453 gp_XY computeAngularPos(vector<gp_XY>& uv,
454 const gp_XY& uvToFix,
455 const double refSign );
457 //--------------------------------------------------------------------------------
459 * \brief Builder of viscous layers
461 class _ViscousBuilder
466 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
467 const TopoDS_Shape& shape);
469 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
470 void RestoreListeners();
472 // computes SMESH_ProxyMesh::SubMesh::_n2n;
473 bool MakeN2NMap( _MeshOfSolid* pm );
477 bool findSolidsWithLayers();
478 bool findFacesWithLayers();
479 bool makeLayer(_SolidData& data);
480 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
481 SMESH_MesherHelper& helper, _SolidData& data);
482 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
483 std::pair< TGeomID, gp_XYZ > fId2Normal[],
485 bool findNeiborsOnEdge(const _LayerEdge* edge,
486 const SMDS_MeshNode*& n1,
487 const SMDS_MeshNode*& n2,
489 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
490 const set<TGeomID>& ingnoreShapes,
491 const _SolidData* dataToCheckOri = 0,
492 const bool toSort = false);
493 bool sortEdges( _SolidData& data,
494 vector< vector<_LayerEdge*> >& edgesByGeom);
495 void limitStepSize( _SolidData& data,
496 const SMDS_MeshElement* face,
498 void limitStepSize( _SolidData& data, const double minSize);
499 bool inflate(_SolidData& data);
500 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
501 bool smoothAnalyticEdge( _SolidData& data,
504 Handle(Geom_Surface)& surface,
505 const TopoDS_Face& F,
506 SMESH_MesherHelper& helper);
507 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
508 bool refine(_SolidData& data);
510 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
511 SMESH_MesherHelper& helper,
512 const SMESHDS_SubMesh* faceSubMesh );
513 void fixBadFaces(const TopoDS_Face& F,
514 SMESH_MesherHelper& helper,
517 set<const SMDS_MeshNode*> * involvedNodes=NULL);
518 bool addBoundaryElements();
520 bool error( const string& text, int solidID=-1 );
521 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
524 void makeGroupOfLE();
527 SMESH_ComputeErrorPtr _error;
529 vector< _SolidData > _sdVec;
532 //--------------------------------------------------------------------------------
534 * \brief Shrinker of nodes on the EDGE
538 vector<double> _initU;
539 vector<double> _normPar;
540 vector<const SMDS_MeshNode*> _nodes;
541 const _LayerEdge* _edges[2];
544 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
545 void Compute(bool set3D, SMESH_MesherHelper& helper);
546 void RestoreParams();
547 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
549 //--------------------------------------------------------------------------------
551 * \brief Class of temporary mesh face.
552 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
553 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
555 struct TmpMeshFace : public SMDS_MeshElement
557 vector<const SMDS_MeshNode* > _nn;
558 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
559 SMDS_MeshElement(id), _nn(nodes) {}
560 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
561 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
562 virtual vtkIdType GetVtkType() const { return -1; }
563 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
564 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
565 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
566 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
568 //--------------------------------------------------------------------------------
570 * \brief Class of temporary mesh face storing _LayerEdge it's based on
572 struct TmpMeshFaceOnEdge : public TmpMeshFace
574 _LayerEdge *_le1, *_le2;
575 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
576 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
578 _nn[0]=_le1->_nodes[0];
579 _nn[1]=_le1->_nodes.back();
580 _nn[2]=_le2->_nodes.back();
581 _nn[3]=_le2->_nodes[0];
584 //--------------------------------------------------------------------------------
586 * \brief Retriever of node coordinates either directly of from a surface by node UV.
587 * \warning Location of a surface is ignored
589 struct NodeCoordHelper
591 SMESH_MesherHelper& _helper;
592 const TopoDS_Face& _face;
593 Handle(Geom_Surface) _surface;
594 gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
596 NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
597 : _helper( helper ), _face( F )
602 _surface = BRep_Tool::Surface( _face, loc );
604 if ( _surface.IsNull() )
605 _fun = & NodeCoordHelper::direct;
607 _fun = & NodeCoordHelper::byUV;
609 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
612 gp_XYZ direct(const SMDS_MeshNode* n) const
614 return SMESH_TNodeXYZ( n );
616 gp_XYZ byUV (const SMDS_MeshNode* n) const
618 gp_XY uv = _helper.GetNodeUV( _face, n );
619 return _surface->Value( uv.X(), uv.Y() ).XYZ();
622 } // namespace VISCOUS_3D
624 //================================================================================
625 // StdMeshers_ViscousLayers hypothesis
627 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
628 :SMESH_Hypothesis(hypId, studyId, gen),
629 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
631 _name = StdMeshers_ViscousLayers::GetHypType();
632 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
633 } // --------------------------------------------------------------------------------
634 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
636 if ( faceIds != _shapeIds )
637 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
638 if ( _isToIgnoreShapes != toIgnore )
639 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
640 } // --------------------------------------------------------------------------------
641 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
643 if ( thickness != _thickness )
644 _thickness = thickness, NotifySubMeshesHypothesisModification();
645 } // --------------------------------------------------------------------------------
646 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
648 if ( _nbLayers != nb )
649 _nbLayers = nb, NotifySubMeshesHypothesisModification();
650 } // --------------------------------------------------------------------------------
651 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
653 if ( _stretchFactor != factor )
654 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
655 } // --------------------------------------------------------------------------------
657 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
658 const TopoDS_Shape& theShape,
659 const bool toMakeN2NMap) const
661 using namespace VISCOUS_3D;
662 _ViscousBuilder bulder;
663 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
664 if ( err && !err->IsOK() )
665 return SMESH_ProxyMesh::Ptr();
667 vector<SMESH_ProxyMesh::Ptr> components;
668 TopExp_Explorer exp( theShape, TopAbs_SOLID );
669 for ( ; exp.More(); exp.Next() )
671 if ( _MeshOfSolid* pm =
672 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
674 if ( toMakeN2NMap && !pm->_n2nMapComputed )
675 if ( !bulder.MakeN2NMap( pm ))
676 return SMESH_ProxyMesh::Ptr();
677 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
678 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
680 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
682 switch ( components.size() )
686 case 1: return components[0];
688 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
690 return SMESH_ProxyMesh::Ptr();
691 } // --------------------------------------------------------------------------------
692 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
694 save << " " << _nbLayers
696 << " " << _stretchFactor
697 << " " << _shapeIds.size();
698 for ( size_t i = 0; i < _shapeIds.size(); ++i )
699 save << " " << _shapeIds[i];
700 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
702 } // --------------------------------------------------------------------------------
703 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
705 int nbFaces, faceID, shapeToTreat;
706 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
707 while ( _shapeIds.size() < nbFaces && load >> faceID )
708 _shapeIds.push_back( faceID );
709 if ( load >> shapeToTreat )
710 _isToIgnoreShapes = !shapeToTreat;
712 _isToIgnoreShapes = true; // old behavior
714 } // --------------------------------------------------------------------------------
715 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
716 const TopoDS_Shape& theShape)
721 // END StdMeshers_ViscousLayers hypothesis
722 //================================================================================
726 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
730 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
731 gp_Pnt p = BRep_Tool::Pnt( fromV );
732 double distF = p.SquareDistance( c->Value( f ));
733 double distL = p.SquareDistance( c->Value( l ));
734 c->D1(( distF < distL ? f : l), p, dir );
735 if ( distL < distF ) dir.Reverse();
738 //--------------------------------------------------------------------------------
739 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
740 SMESH_MesherHelper& helper)
743 double f,l; gp_Pnt p;
744 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
745 double u = helper.GetNodeU( E, atNode );
749 //--------------------------------------------------------------------------------
750 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
751 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
753 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
754 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
755 gp_Pnt p; gp_Vec du, dv, norm;
756 surface->D1( uv.X(),uv.Y(), p, du,dv );
760 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
761 double u = helper.GetNodeU( fromE, node, 0, &ok );
763 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
764 if ( o == TopAbs_REVERSED )
767 gp_Vec dir = norm ^ du;
769 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
770 helper.IsClosedEdge( fromE ))
772 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
773 else c->D1( f, p, dv );
774 if ( o == TopAbs_REVERSED )
776 gp_Vec dir2 = norm ^ dv;
777 dir = dir.Normalized() + dir2.Normalized();
781 //--------------------------------------------------------------------------------
782 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
783 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
784 bool& ok, double* cosin=0)
786 double f,l; TopLoc_Location loc;
787 vector< TopoDS_Edge > edges; // sharing a vertex
788 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
791 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
792 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
793 edges.push_back( *e );
796 if ( !( ok = ( edges.size() > 0 ))) return dir;
797 // get average dir of edges going fromV
799 //if ( edges.size() > 1 )
800 for ( size_t i = 0; i < edges.size(); ++i )
802 edgeDir = getEdgeDir( edges[i], fromV );
803 double size2 = edgeDir.SquareModulus();
804 if ( size2 > numeric_limits<double>::min() )
805 edgeDir /= sqrt( size2 );
810 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
811 if ( edges.size() == 1 )
813 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
814 dir = fromEdgeDir + getFaceDir( F, edges[1], node, helper, ok );
815 else if ( dir * fromEdgeDir < 0 )
819 //dir /= edges.size();
821 double angle = gp_Vec( edgeDir ).Angle( dir );
822 *cosin = cos( angle );
827 //================================================================================
829 * \brief Returns true if a FACE is bound by a concave EDGE
831 //================================================================================
833 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
835 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
839 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
840 for ( ; eExp.More(); eExp.Next() )
842 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
843 if ( SMESH_Algo::isDegenerated( E )) continue;
844 // check if 2D curve is concave
845 BRepAdaptor_Curve2d curve( E, F );
846 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
847 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
848 curve.Intervals( intervals, GeomAbs_C2 );
849 bool isConvex = true;
850 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
852 double u1 = intervals( i );
853 double u2 = intervals( i+1 );
854 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
855 double cross = drv2 ^ drv1;
856 if ( E.Orientation() == TopAbs_REVERSED )
858 isConvex = ( cross > 0.1 ); //-1e-9 );
860 // check if concavity is strong enough to care about it
861 //const double maxAngle = 5 * Standard_PI180;
864 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
866 // map< double, const SMDS_MeshNode* > u2nodes;
867 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
868 // /*ignoreMedium=*/true, u2nodes))
870 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
871 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
872 // double uPrev = u2n->first;
873 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
875 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
876 // gp_Vec2d segmentDir( uvPrev, uv );
877 // curve.D1( uPrev, p, drv1 );
879 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
884 // uPrev = u2n->first;
888 // check angles at VERTEXes
890 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
891 for ( size_t iW = 0; iW < wires.size(); ++iW )
893 const int nbEdges = wires[iW]->NbEdges();
894 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
896 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
898 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
899 int iE2 = ( iE1 + 1 ) % nbEdges;
900 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
901 iE2 = ( iE2 + 1 ) % nbEdges;
902 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
903 wires[iW]->Edge( iE2 ), F );
904 if ( angle < -5. * M_PI / 180. )
910 //--------------------------------------------------------------------------------
911 // DEBUG. Dump intermediate node positions into a python script
916 const char* fname = "/tmp/viscous.py";
917 cout << "execfile('"<<fname<<"')"<<endl;
918 py = new ofstream(fname);
919 *py << "import SMESH" << endl
920 << "from salome.smesh import smeshBuilder" << endl
921 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
922 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
923 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
927 *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
930 ~PyDump() { Finish(); }
932 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
933 #define dumpMove(n) { _dumpMove(n, __LINE__);}
934 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
935 void _dumpFunction(const string& fun, int ln)
936 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
937 void _dumpMove(const SMDS_MeshNode* n, int ln)
938 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
939 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
940 void _dumpCmd(const string& txt, int ln)
941 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
942 void dumpFunctionEnd()
943 { if (py) *py<< " return"<< endl; }
944 void dumpChangeNodes( const SMDS_MeshElement* f )
945 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
946 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
947 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
949 struct PyDump { void Finish() {} };
950 #define dumpFunction(f) f
953 #define dumpFunctionEnd()
954 #define dumpChangeNodes(f)
958 using namespace VISCOUS_3D;
960 //================================================================================
962 * \brief Constructor of _ViscousBuilder
964 //================================================================================
966 _ViscousBuilder::_ViscousBuilder()
968 _error = SMESH_ComputeError::New(COMPERR_OK);
972 //================================================================================
974 * \brief Stores error description and returns false
976 //================================================================================
978 bool _ViscousBuilder::error(const string& text, int solidId )
980 _error->myName = COMPERR_ALGO_FAILED;
981 _error->myComment = string("Viscous layers builder: ") + text;
984 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
985 if ( !sm && !_sdVec.empty() )
986 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
987 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
989 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
990 if ( smError && smError->myAlgo )
991 _error->myAlgo = smError->myAlgo;
995 makeGroupOfLE(); // debug
1000 //================================================================================
1002 * \brief At study restoration, restore event listeners used to clear an inferior
1003 * dim sub-mesh modified by viscous layers
1005 //================================================================================
1007 void _ViscousBuilder::RestoreListeners()
1012 //================================================================================
1014 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1016 //================================================================================
1018 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1020 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1021 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1022 for ( ; fExp.More(); fExp.Next() )
1024 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1025 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1027 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1029 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1032 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1033 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1035 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1036 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1037 while( prxIt->more() )
1039 const SMDS_MeshElement* fSrc = srcIt->next();
1040 const SMDS_MeshElement* fPrx = prxIt->next();
1041 if ( fSrc->NbNodes() != fPrx->NbNodes())
1042 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1043 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1044 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1047 pm->_n2nMapComputed = true;
1051 //================================================================================
1053 * \brief Does its job
1055 //================================================================================
1057 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1058 const TopoDS_Shape& theShape)
1060 // TODO: set priority of solids during Gen::Compute()
1064 // check if proxy mesh already computed
1065 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1067 return error("No SOLID's in theShape"), _error;
1069 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1070 return SMESH_ComputeErrorPtr(); // everything already computed
1074 // TODO: ignore already computed SOLIDs
1075 if ( !findSolidsWithLayers())
1078 if ( !findFacesWithLayers() )
1081 for ( size_t i = 0; i < _sdVec.size(); ++i )
1083 if ( ! makeLayer(_sdVec[i]) )
1086 if ( _sdVec[i]._edges.size() == 0 )
1089 if ( ! inflate(_sdVec[i]) )
1092 if ( ! refine(_sdVec[i]) )
1098 addBoundaryElements();
1100 makeGroupOfLE(); // debug
1106 //================================================================================
1108 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1110 //================================================================================
1112 bool _ViscousBuilder::findSolidsWithLayers()
1115 TopTools_IndexedMapOfShape allSolids;
1116 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1117 _sdVec.reserve( allSolids.Extent());
1119 SMESH_Gen* gen = _mesh->GetGen();
1120 SMESH_HypoFilter filter;
1121 for ( int i = 1; i <= allSolids.Extent(); ++i )
1123 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1124 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1125 if ( !algo ) continue;
1126 // TODO: check if algo is hidden
1127 const list <const SMESHDS_Hypothesis *> & allHyps =
1128 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1129 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1130 const StdMeshers_ViscousLayers* viscHyp = 0;
1131 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1132 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1135 TopoDS_Shape hypShape;
1136 filter.Init( filter.Is( viscHyp ));
1137 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1139 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1142 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1143 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1146 if ( _sdVec.empty() )
1148 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1153 //================================================================================
1157 //================================================================================
1159 bool _ViscousBuilder::findFacesWithLayers()
1161 SMESH_MesherHelper helper( *_mesh );
1162 TopExp_Explorer exp;
1163 TopTools_IndexedMapOfShape solids;
1165 // collect all faces to ignore defined by hyp
1166 for ( size_t i = 0; i < _sdVec.size(); ++i )
1168 solids.Add( _sdVec[i]._solid );
1170 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1171 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1173 for ( size_t ii = 0; ii < ids.size(); ++ii )
1175 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1176 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1177 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1180 else // FACEs with layers are given
1182 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1183 for ( ; exp.More(); exp.Next() )
1185 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1186 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1187 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1191 // ignore internal FACEs if inlets and outlets are specified
1193 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1194 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1195 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1196 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1198 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1199 for ( ; exp.More(); exp.Next() )
1201 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1202 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1205 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1206 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1208 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1210 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1213 if ( helper.IsReversedSubMesh( face ))
1215 _sdVec[i]._reversedFaceIds.insert( faceInd );
1221 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1222 TopTools_IndexedMapOfShape shapes;
1223 for ( size_t i = 0; i < _sdVec.size(); ++i )
1226 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1227 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1229 const TopoDS_Shape& edge = shapes(iE);
1230 // find 2 faces sharing an edge
1232 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1233 while ( fIt->more())
1235 const TopoDS_Shape* f = fIt->next();
1236 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1237 FF[ int( !FF[0].IsNull()) ] = *f;
1239 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1240 // check presence of layers on them
1242 for ( int j = 0; j < 2; ++j )
1243 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1244 if ( ignore[0] == ignore[1] )
1245 continue; // nothing interesting
1246 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1247 // check presence of layers on fWOL within an adjacent SOLID
1248 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1249 while ( const TopoDS_Shape* solid = sIt->next() )
1250 if ( !solid->IsSame( _sdVec[i]._solid ))
1252 int iSolid = solids.FindIndex( *solid );
1253 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1254 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1256 _sdVec[i]._noShrinkFaces.insert( iFace );
1261 if ( !fWOL.IsNull())
1263 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1264 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1268 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1269 // the algo of the SOLID sharing the FACE does not support it
1270 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1271 for ( size_t i = 0; i < _sdVec.size(); ++i )
1273 TopTools_MapOfShape noShrinkVertices;
1274 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1275 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1277 const TopoDS_Shape& fWOL = e2f->second;
1278 TGeomID edgeID = e2f->first;
1279 bool notShrinkFace = false;
1280 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1281 while ( soIt->more())
1283 const TopoDS_Shape* solid = soIt->next();
1284 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1285 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1286 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1287 notShrinkFace = true;
1288 for ( size_t j = 0; j < _sdVec.size(); ++j )
1290 if ( _sdVec[j]._solid.IsSame( *solid ) )
1291 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1292 notShrinkFace = false;
1295 if ( notShrinkFace )
1297 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1298 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1299 noShrinkVertices.Add( vExp.Current() );
1302 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1303 // to the found not shrinked fWOL's
1304 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1305 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1307 TGeomID edgeID = e2f->first;
1308 TopoDS_Vertex VV[2];
1309 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1310 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1312 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1313 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1322 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1324 for ( size_t i = 0; i < _sdVec.size(); ++i )
1327 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1328 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1330 const TopoDS_Shape& vertex = shapes(iV);
1331 // find faces WOL sharing the vertex
1332 vector< TopoDS_Shape > facesWOL;
1333 int totalNbFaces = 0;
1334 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1335 while ( fIt->more())
1337 const TopoDS_Shape* f = fIt->next();
1338 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1341 const int fID = getMeshDS()->ShapeToIndex( *f );
1342 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1343 !_sdVec[i]._noShrinkFaces.count( fID ))
1344 facesWOL.push_back( *f );
1347 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1348 continue; // no layers at this vertex or no WOL
1349 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1350 switch ( facesWOL.size() )
1354 helper.SetSubShape( facesWOL[0] );
1355 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1357 TopoDS_Shape seamEdge;
1358 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1359 while ( eIt->more() && seamEdge.IsNull() )
1361 const TopoDS_Shape* e = eIt->next();
1362 if ( helper.IsRealSeam( *e ) )
1365 if ( !seamEdge.IsNull() )
1367 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1371 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1376 // find an edge shared by 2 faces
1377 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1378 while ( eIt->more())
1380 const TopoDS_Shape* e = eIt->next();
1381 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1382 helper.IsSubShape( *e, facesWOL[1]))
1384 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1390 return error("Not yet supported case", _sdVec[i]._index);
1398 //================================================================================
1400 * \brief Create the inner surface of the viscous layer and prepare data for infation
1402 //================================================================================
1404 bool _ViscousBuilder::makeLayer(_SolidData& data)
1406 // get all sub-shapes to make layers on
1407 set<TGeomID> subIds, faceIds;
1408 subIds = data._noShrinkFaces;
1409 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1410 for ( ; exp.More(); exp.Next() )
1412 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1413 if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1414 faceIds.insert( fSubM->GetId() );
1415 SMESH_subMeshIteratorPtr subIt =
1416 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1417 while ( subIt->more() )
1418 subIds.insert( subIt->next()->GetId() );
1421 // make a map to find new nodes on sub-shapes shared with other SOLID
1422 map< TGeomID, TNode2Edge* > s2neMap;
1423 map< TGeomID, TNode2Edge* >::iterator s2ne;
1424 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1425 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1427 TGeomID shapeInd = s2s->first;
1428 for ( size_t i = 0; i < _sdVec.size(); ++i )
1430 if ( _sdVec[i]._index == data._index ) continue;
1431 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1432 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1433 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1435 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1441 // Create temporary faces and _LayerEdge's
1443 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1445 data._stepSize = Precision::Infinite();
1446 data._stepSizeNodes[0] = 0;
1448 SMESH_MesherHelper helper( *_mesh );
1449 helper.SetSubShape( data._solid );
1450 helper.SetElementsOnShape(true);
1452 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1453 TNode2Edge::iterator n2e2;
1455 // collect _LayerEdge's of shapes they are based on
1456 const int nbShapes = getMeshDS()->MaxShapeIndex();
1457 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1459 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1461 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1462 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1464 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1465 SMESH_ProxyMesh::SubMesh* proxySub =
1466 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1468 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1469 while ( eIt->more() )
1471 const SMDS_MeshElement* face = eIt->next();
1472 newNodes.resize( face->NbCornerNodes() );
1473 double faceMaxCosin = -1;
1474 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1476 const SMDS_MeshNode* n = face->GetNode(i);
1477 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1478 if ( !(*n2e).second )
1481 _LayerEdge* edge = new _LayerEdge();
1483 edge->_nodes.push_back( n );
1484 const int shapeID = n->getshapeId();
1485 edgesByGeom[ shapeID ].push_back( edge );
1487 // set edge data or find already refined _LayerEdge and get data from it
1488 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1489 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1490 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1492 _LayerEdge* foundEdge = (*n2e2).second;
1493 edge->Copy( *foundEdge, helper );
1494 // location of the last node is modified but we can restore
1495 // it by node position on _sWOL stored by the node
1496 const_cast< SMDS_MeshNode* >
1497 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1501 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1502 if ( !setEdgeData( *edge, subIds, helper, data ))
1505 dumpMove(edge->_nodes.back());
1506 if ( edge->_cosin > 0.01 )
1508 if ( edge->_cosin > faceMaxCosin )
1509 faceMaxCosin = edge->_cosin;
1512 newNodes[ i ] = n2e->second->_nodes.back();
1514 // create a temporary face
1515 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1516 proxySub->AddElement( newFace );
1518 // compute inflation step size by min size of element on a convex surface
1519 if ( faceMaxCosin > 0.1 )
1520 limitStepSize( data, face, faceMaxCosin );
1521 } // loop on 2D elements on a FACE
1522 } // loop on FACEs of a SOLID
1524 data._epsilon = 1e-7;
1525 if ( data._stepSize < 1. )
1526 data._epsilon *= data._stepSize;
1528 // Put _LayerEdge's into the vector data._edges
1530 if ( !sortEdges( data, edgesByGeom ))
1533 // Set target nodes into _Simplex and _2NearEdges
1534 TNode2Edge::iterator n2e;
1535 for ( size_t i = 0; i < data._edges.size(); ++i )
1537 if ( data._edges[i]->IsOnEdge())
1538 for ( int j = 0; j < 2; ++j )
1540 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1541 break; // _LayerEdge is shared by two _SolidData's
1542 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1543 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1544 return error("_LayerEdge not found by src node", data._index);
1545 n = (*n2e).second->_nodes.back();
1546 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1549 for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1551 _Simplex& s = data._edges[i]->_simplices[j];
1552 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1553 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1561 //================================================================================
1563 * \brief Compute inflation step size by min size of element on a convex surface
1565 //================================================================================
1567 void _ViscousBuilder::limitStepSize( _SolidData& data,
1568 const SMDS_MeshElement* face,
1572 double minSize = 10 * data._stepSize;
1573 const int nbNodes = face->NbCornerNodes();
1574 for ( int i = 0; i < nbNodes; ++i )
1576 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1577 const SMDS_MeshNode* curN = face->GetNode( i );
1578 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1579 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1581 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1582 if ( dist < minSize )
1583 minSize = dist, iN = i;
1586 double newStep = 0.8 * minSize / cosin;
1587 if ( newStep < data._stepSize )
1589 data._stepSize = newStep;
1590 data._stepSizeCoeff = 0.8 / cosin;
1591 data._stepSizeNodes[0] = face->GetNode( iN );
1592 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1596 //================================================================================
1598 * \brief Compute inflation step size by min size of element on a convex surface
1600 //================================================================================
1602 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1604 if ( minSize < data._stepSize )
1606 data._stepSize = minSize;
1607 if ( data._stepSizeNodes[0] )
1610 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1611 data._stepSizeCoeff = data._stepSize / dist;
1616 //================================================================================
1618 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1620 //================================================================================
1622 bool _ViscousBuilder::sortEdges( _SolidData& data,
1623 vector< vector<_LayerEdge*> >& edgesByGeom)
1625 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1626 // boundry inclined at a sharp angle to the shape
1628 list< TGeomID > shapesToSmooth;
1630 SMESH_MesherHelper helper( *_mesh );
1633 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1635 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1636 if ( eS.empty() ) continue;
1637 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1638 bool needSmooth = false;
1639 switch ( S.ShapeType() )
1643 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1644 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1646 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1647 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1648 if ( eV.empty() ) continue;
1649 double cosin = eV[0]->_cosin;
1651 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1655 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1656 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1658 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1659 eV[0]->_nodes[0], helper, ok);
1660 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1661 double angle = dir1.Angle( dir2 );
1662 cosin = cos( angle );
1664 needSmooth = ( cosin > 0.1 );
1670 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1672 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1673 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1674 if ( eE.empty() ) continue;
1675 if ( eE[0]->_sWOL.IsNull() )
1677 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1678 needSmooth = ( eE[i]->_cosin > 0.1 );
1682 const TopoDS_Face& F1 = TopoDS::Face( S );
1683 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1684 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1685 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1687 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1688 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1689 double angle = dir1.Angle( dir2 );
1690 double cosin = cos( angle );
1691 needSmooth = ( cosin > 0.1 );
1703 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1704 else shapesToSmooth.push_back ( iS );
1707 } // loop on edgesByGeom
1709 data._edges.reserve( data._n2eMap.size() );
1710 data._endEdgeToSmooth.clear();
1712 // first we put _LayerEdge's on shapes to smooth
1713 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1714 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1716 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1717 if ( eVec.empty() ) continue;
1718 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1719 data._endEdgeToSmooth.push_back( data._edges.size() );
1723 // then the rest _LayerEdge's
1724 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1726 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1727 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1734 //================================================================================
1736 * \brief Set data of _LayerEdge needed for smoothing
1737 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1739 //================================================================================
1741 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1742 const set<TGeomID>& subIds,
1743 SMESH_MesherHelper& helper,
1746 SMESH_MeshEditor editor(_mesh);
1748 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1749 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1753 edge._curvature = 0;
1755 // --------------------------
1756 // Compute _normal and _cosin
1757 // --------------------------
1760 edge._normal.SetCoord(0,0,0);
1762 int totalNbFaces = 0;
1764 gp_Vec du, dv, geomNorm;
1767 TGeomID shapeInd = node->getshapeId();
1768 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1769 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1770 TopoDS_Shape vertEdge;
1772 if ( onShrinkShape ) // one of faces the node is on has no layers
1774 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1775 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1777 // inflate from VERTEX along EDGE
1778 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1780 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1782 // inflate from VERTEX along FACE
1783 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1784 node, helper, normOK, &edge._cosin);
1788 // inflate from EDGE along FACE
1789 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1790 node, helper, normOK);
1793 else // layers are on all faces of SOLID the node is on
1795 // find indices of geom faces the node lies on
1796 set<TGeomID> faceIds;
1797 if ( posType == SMDS_TOP_FACE )
1799 faceIds.insert( node->getshapeId() );
1803 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1804 while ( fIt->more() )
1805 faceIds.insert( editor.FindShape(fIt->next()));
1808 set<TGeomID>::iterator id = faceIds.begin();
1810 std::pair< TGeomID, gp_XYZ > id2Norm[20];
1811 for ( ; id != faceIds.end(); ++id )
1813 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1814 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1816 F = TopoDS::Face( s );
1818 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1819 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1822 if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1827 else // hard singularity
1829 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1830 while ( fIt->more() )
1832 const SMDS_MeshElement* f = fIt->next();
1833 if ( editor.FindShape( f ) == *id )
1835 SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1836 if ( helper.IsReversedSubMesh( F ))
1841 double size2 = geomNorm.SquareMagnitude();
1842 if ( size2 > numeric_limits<double>::min() )
1843 geomNorm /= sqrt( size2 );
1848 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1850 id2Norm[ totalNbFaces ].first = *id;
1851 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
1853 edge._normal += geomNorm.XYZ();
1855 if ( totalNbFaces == 0 )
1856 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1858 if ( totalNbFaces < 3 )
1860 edge._normal /= totalNbFaces;
1864 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
1870 edge._cosin = 0; break;
1872 case SMDS_TOP_EDGE: {
1873 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1874 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1875 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1876 edge._cosin = cos( angle );
1877 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1880 case SMDS_TOP_VERTEX: {
1881 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1882 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1883 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
1884 edge._cosin = cos( angle );
1885 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1889 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1893 double normSize = edge._normal.SquareModulus();
1894 if ( normSize < numeric_limits<double>::min() )
1895 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1897 edge._normal /= sqrt( normSize );
1899 // TODO: if ( !normOK ) then get normal by mesh faces
1901 // Set the rest data
1902 // --------------------
1903 if ( onShrinkShape )
1905 edge._sWOL = (*s2s).second;
1907 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1908 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1909 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1911 // set initial position which is parameters on _sWOL in this case
1912 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1914 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1915 edge._pos.push_back( gp_XYZ( u, 0, 0));
1916 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1920 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1921 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1922 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1927 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1929 if ( posType == SMDS_TOP_FACE )
1931 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
1932 double avgNormProj = 0, avgLen = 0;
1933 for ( size_t i = 0; i < edge._simplices.size(); ++i )
1935 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1936 avgNormProj += edge._normal * vec;
1937 avgLen += vec.Modulus();
1939 avgNormProj /= edge._simplices.size();
1940 avgLen /= edge._simplices.size();
1941 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1945 // Set neighbour nodes for a _LayerEdge based on EDGE
1947 if ( posType == SMDS_TOP_EDGE /*||
1948 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1950 edge._2neibors = new _2NearEdges;
1951 // target node instead of source ones will be set later
1952 if ( ! findNeiborsOnEdge( &edge,
1953 edge._2neibors->_nodes[0],
1954 edge._2neibors->_nodes[1],
1957 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1958 edge._2neibors->_nodes[1],
1962 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1967 //================================================================================
1969 * \brief Return normal at a node weighted with angles taken by FACEs
1970 * \param [in] n - the node
1971 * \param [in] fId2Normal - FACE ids and normals
1972 * \param [in] nbFaces - nb of FACEs meeting at the node
1973 * \return gp_XYZ - computed normal
1975 //================================================================================
1977 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
1978 std::pair< TGeomID, gp_XYZ > fId2Normal[],
1981 gp_XYZ resNorm(0,0,0);
1982 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
1983 if ( V.ShapeType() != TopAbs_VERTEX )
1985 for ( int i = 0; i < nbFaces; ++i )
1986 resNorm += fId2Normal[i].second / nbFaces ;
1991 for ( int i = 0; i < nbFaces; ++i )
1993 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
1995 // look for two EDGEs shared by F and other FACEs within fId2Normal
1998 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
1999 while ( const TopoDS_Shape* E = eIt->next() )
2001 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2003 bool isSharedEdge = false;
2004 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2006 if ( i == j ) continue;
2007 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2008 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2010 if ( !isSharedEdge )
2012 ee[ nbE ] = TopoDS::Edge( *E );
2013 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2018 // get an angle between the two EDGEs
2020 if ( nbE < 1 ) continue;
2027 TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2028 TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2029 if ( !v10.IsSame( v01 ))
2030 std::swap( ee[0], ee[1] );
2032 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2035 // compute a weighted normal
2036 double sumAngle = 0;
2037 for ( int i = 0; i < nbFaces; ++i )
2039 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
2040 sumAngle += angles[i];
2042 for ( int i = 0; i < nbFaces; ++i )
2043 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2048 //================================================================================
2050 * \brief Find 2 neigbor nodes of a node on EDGE
2052 //================================================================================
2054 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
2055 const SMDS_MeshNode*& n1,
2056 const SMDS_MeshNode*& n2,
2059 const SMDS_MeshNode* node = edge->_nodes[0];
2060 const int shapeInd = node->getshapeId();
2061 SMESHDS_SubMesh* edgeSM = 0;
2062 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2065 edgeSM = getMeshDS()->MeshElements( shapeInd );
2066 if ( !edgeSM || edgeSM->NbElements() == 0 )
2067 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2071 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2072 while ( eIt->more() && !n2 )
2074 const SMDS_MeshElement* e = eIt->next();
2075 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
2076 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2079 if (!edgeSM->Contains(e)) continue;
2083 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2084 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2086 ( iN++ ? n2 : n1 ) = nNeibor;
2089 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2093 //================================================================================
2095 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2097 //================================================================================
2099 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2100 const SMDS_MeshNode* n2,
2101 SMESH_MesherHelper& helper)
2103 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2106 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2107 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2108 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2112 double sumLen = vec1.Modulus() + vec2.Modulus();
2113 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2114 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2115 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2116 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2117 if ( _curvature ) delete _curvature;
2118 _curvature = _Curvature::New( avgNormProj, avgLen );
2120 // if ( _curvature )
2121 // cout << _nodes[0]->GetID()
2122 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2123 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2124 // << _curvature->lenDelta(0) << endl;
2129 if ( _sWOL.IsNull() )
2131 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2132 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2133 gp_XYZ plnNorm = dirE ^ _normal;
2134 double proj0 = plnNorm * vec1;
2135 double proj1 = plnNorm * vec2;
2136 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2138 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2139 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2144 //================================================================================
2146 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2147 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2149 //================================================================================
2151 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2153 _nodes = other._nodes;
2154 _normal = other._normal;
2156 _lenFactor = other._lenFactor;
2157 _cosin = other._cosin;
2158 _sWOL = other._sWOL;
2159 _2neibors = other._2neibors;
2160 _curvature = 0; std::swap( _curvature, other._curvature );
2161 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2163 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2165 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2166 _pos.push_back( gp_XYZ( u, 0, 0));
2170 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2171 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2175 //================================================================================
2177 * \brief Set _cosin and _lenFactor
2179 //================================================================================
2181 void _LayerEdge::SetCosin( double cosin )
2184 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
2187 //================================================================================
2189 * \brief Fills a vector<_Simplex >
2191 //================================================================================
2193 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2194 vector<_Simplex>& simplices,
2195 const set<TGeomID>& ingnoreShapes,
2196 const _SolidData* dataToCheckOri,
2200 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2201 while ( fIt->more() )
2203 const SMDS_MeshElement* f = fIt->next();
2204 const TGeomID shapeInd = f->getshapeId();
2205 if ( ingnoreShapes.count( shapeInd )) continue;
2206 const int nbNodes = f->NbCornerNodes();
2207 const int srcInd = f->GetNodeIndex( node );
2208 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2209 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2210 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2211 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2212 std::swap( nPrev, nNext );
2213 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2218 vector<_Simplex> sortedSimplices( simplices.size() );
2219 sortedSimplices[0] = simplices[0];
2221 for ( size_t i = 1; i < simplices.size(); ++i )
2223 for ( size_t j = 1; j < simplices.size(); ++j )
2224 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2226 sortedSimplices[i] = simplices[j];
2231 if ( nbFound == simplices.size() - 1 )
2232 simplices.swap( sortedSimplices );
2236 //================================================================================
2238 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2240 //================================================================================
2242 void _ViscousBuilder::makeGroupOfLE()
2245 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2247 if ( _sdVec[i]._edges.empty() ) continue;
2248 // string name = SMESH_Comment("_LayerEdge's_") << i;
2250 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2251 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2252 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2254 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2255 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2257 _LayerEdge* le = _sdVec[i]._edges[j];
2258 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2259 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2260 << ", " << le->_nodes[iN]->GetID() <<"])");
2261 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2265 dumpFunction( SMESH_Comment("makeNormals") << i );
2266 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2268 _LayerEdge& edge = *_sdVec[i]._edges[j];
2269 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2270 nXYZ += edge._normal * _sdVec[i]._stepSize;
2271 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2272 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2276 // name = SMESH_Comment("tmp_faces ") << i;
2277 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2278 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2279 // SMESH_MeshEditor editor( _mesh );
2280 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2281 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2282 for ( ; fExp.More(); fExp.Next() )
2284 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2286 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2287 while ( fIt->more())
2289 const SMDS_MeshElement* e = fIt->next();
2290 SMESH_Comment cmd("mesh.AddFace([");
2291 for ( int j=0; j < e->NbCornerNodes(); ++j )
2292 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2294 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2295 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2304 //================================================================================
2306 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2308 //================================================================================
2310 bool _ViscousBuilder::inflate(_SolidData& data)
2312 SMESH_MesherHelper helper( *_mesh );
2314 // Limit inflation step size by geometry size found by itersecting
2315 // normals of _LayerEdge's with mesh faces
2316 double geomSize = Precision::Infinite(), intersecDist;
2317 auto_ptr<SMESH_ElementSearcher> searcher
2318 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2319 data._proxyMesh->GetFaces( data._solid )) );
2320 for ( size_t i = 0; i < data._edges.size(); ++i )
2322 if ( data._edges[i]->IsOnEdge() ) continue;
2323 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2324 if ( geomSize > intersecDist && intersecDist > 0 )
2325 geomSize = intersecDist;
2327 if ( data._stepSize > 0.3 * geomSize )
2328 limitStepSize( data, 0.3 * geomSize );
2330 const double tgtThick = data._hyp->GetTotalThickness();
2331 if ( data._stepSize > tgtThick )
2332 limitStepSize( data, tgtThick );
2334 if ( data._stepSize < 1. )
2335 data._epsilon = data._stepSize * 1e-7;
2338 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2341 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2342 int nbSteps = 0, nbRepeats = 0;
2343 while ( 1.01 * avgThick < tgtThick )
2345 // new target length
2346 curThick += data._stepSize;
2347 if ( curThick > tgtThick )
2349 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2353 // Elongate _LayerEdge's
2354 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2355 for ( size_t i = 0; i < data._edges.size(); ++i )
2357 data._edges[i]->SetNewLength( curThick, helper );
2362 if ( !updateNormals( data, helper ) )
2365 // Improve and check quality
2366 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2370 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2371 for ( size_t i = 0; i < data._edges.size(); ++i )
2373 data._edges[i]->InvalidateStep( nbSteps+1 );
2377 break; // no more inflating possible
2381 // Evaluate achieved thickness
2383 for ( size_t i = 0; i < data._edges.size(); ++i )
2384 avgThick += data._edges[i]->_len;
2385 avgThick /= data._edges.size();
2387 cout << "-- Thickness " << avgThick << " reached" << endl;
2390 if ( distToIntersection < avgThick*1.5 )
2393 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2394 << avgThick << " ) * 1.5" << endl;
2399 limitStepSize( data, 0.25 * distToIntersection );
2400 if ( data._stepSizeNodes[0] )
2401 data._stepSize = data._stepSizeCoeff *
2402 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2406 return error("failed at the very first inflation step", data._index);
2411 //================================================================================
2413 * \brief Improve quality of layer inner surface and check intersection
2415 //================================================================================
2417 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2419 double & distToIntersection)
2421 if ( data._endEdgeToSmooth.empty() )
2422 return true; // no shapes needing smoothing
2424 bool moved, improved;
2426 SMESH_MesherHelper helper(*_mesh);
2427 Handle(Geom_Surface) surface;
2431 for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2434 iEnd = data._endEdgeToSmooth[ iS ];
2436 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2437 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2439 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2440 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2441 helper.SetSubShape( F );
2442 surface = BRep_Tool::Surface( F );
2447 F.Nullify(); surface.Nullify();
2449 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2451 if ( data._edges[ iBeg ]->IsOnEdge() )
2453 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2455 // try a simple solution on an analytic EDGE
2456 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2462 for ( int i = iBeg; i < iEnd; ++i )
2464 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2466 dumpCmd( SMESH_Comment("# end step ")<<step);
2468 while ( moved && step++ < 5 );
2469 //cout << " NB STEPS: " << step << endl;
2476 int step = 0, stepLimit = 5, badNb = 0; moved = true;
2477 while (( ++step <= stepLimit && moved ) || improved )
2479 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2480 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2481 int oldBadNb = badNb;
2484 for ( int i = iBeg; i < iEnd; ++i )
2485 moved |= data._edges[i]->Smooth(badNb);
2486 improved = ( badNb < oldBadNb );
2488 // issue 22576. no bad faces but still there are intersections to fix
2489 if ( improved && badNb == 0 )
2490 stepLimit = step + 3;
2497 for ( int i = iBeg; i < iEnd; ++i )
2499 _LayerEdge* edge = data._edges[i];
2500 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2501 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2502 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2504 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2505 << " "<< edge->_simplices[j]._nPrev->GetID()
2506 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2514 } // loop on shapes to smooth
2516 // Check if the last segments of _LayerEdge intersects 2D elements;
2517 // checked elements are either temporary faces or faces on surfaces w/o the layers
2519 auto_ptr<SMESH_ElementSearcher> searcher
2520 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2521 data._proxyMesh->GetFaces( data._solid )) );
2523 distToIntersection = Precision::Infinite();
2525 const SMDS_MeshElement* intFace = 0;
2527 const SMDS_MeshElement* closestFace = 0;
2530 for ( size_t i = 0; i < data._edges.size(); ++i )
2532 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2534 if ( distToIntersection > dist )
2536 distToIntersection = dist;
2539 closestFace = intFace;
2546 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2547 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2548 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2549 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2550 << ") distance = " << distToIntersection<< endl;
2557 //================================================================================
2559 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2560 * _LayerEdge's to be in a consequent order
2562 //================================================================================
2564 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2567 Handle(Geom_Surface)& surface,
2568 const TopoDS_Face& F,
2569 SMESH_MesherHelper& helper)
2571 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2573 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2575 if ( i2curve == _edge2curve.end() )
2577 // sort _LayerEdge's by position on the EDGE
2579 map< double, _LayerEdge* > u2edge;
2580 for ( int i = iFrom; i < iTo; ++i )
2581 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2583 ASSERT( u2edge.size() == iTo - iFrom );
2584 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2585 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2586 _edges[i] = u2e->second;
2588 // set _2neibors according to the new order
2589 for ( int i = iFrom; i < iTo-1; ++i )
2590 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2591 _edges[i]->_2neibors->reverse();
2592 if ( u2edge.size() > 1 &&
2593 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2594 _edges[iTo-1]->_2neibors->reverse();
2597 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2599 TopLoc_Location loc; double f,l;
2601 Handle(Geom_Line) line;
2602 Handle(Geom_Circle) circle;
2603 bool isLine, isCirc;
2604 if ( F.IsNull() ) // 3D case
2606 // check if the EDGE is a line
2607 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2608 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2609 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2611 line = Handle(Geom_Line)::DownCast( curve );
2612 circle = Handle(Geom_Circle)::DownCast( curve );
2613 isLine = (!line.IsNull());
2614 isCirc = (!circle.IsNull());
2616 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2619 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2620 while ( nIt->more() )
2621 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2622 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2624 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2625 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2626 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2627 for ( int i = 0; i < 3 && !isLine; ++i )
2628 isLine = ( size.Coord( i+1 ) <= lineTol );
2630 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2637 // check if the EDGE is a line
2638 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2639 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2640 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2642 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2643 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2644 isLine = (!line2d.IsNull());
2645 isCirc = (!circle2d.IsNull());
2647 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2650 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2651 while ( nIt->more() )
2652 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2653 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2655 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2656 for ( int i = 0; i < 2 && !isLine; ++i )
2657 isLine = ( size.Coord( i+1 ) <= lineTol );
2659 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2665 line = new Geom_Line( gp::OX() ); // only type does matter
2669 gp_Pnt2d p = circle2d->Location();
2670 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2671 circle = new Geom_Circle( ax, 1.); // only center position does matter
2675 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2683 return i2curve->second;
2686 //================================================================================
2688 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2690 //================================================================================
2692 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2695 Handle(Geom_Surface)& surface,
2696 const TopoDS_Face& F,
2697 SMESH_MesherHelper& helper)
2699 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2700 helper.GetMeshDS());
2701 TopoDS_Edge E = TopoDS::Edge( S );
2703 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2704 if ( curve.IsNull() ) return false;
2706 // compute a relative length of segments
2707 vector< double > len( iTo-iFrom+1 );
2709 double curLen, prevLen = len[0] = 1.0;
2710 for ( int i = iFrom; i < iTo; ++i )
2712 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2713 len[i-iFrom+1] = len[i-iFrom] + curLen;
2718 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2720 if ( F.IsNull() ) // 3D
2722 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2723 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2724 for ( int i = iFrom; i < iTo; ++i )
2726 double r = len[i-iFrom] / len.back();
2727 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2728 data._edges[i]->_pos.back() = newPos;
2729 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2730 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2731 dumpMove( tgtNode );
2736 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2737 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2738 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2739 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2741 int iPeriodic = helper.GetPeriodicIndex();
2742 if ( iPeriodic == 1 || iPeriodic == 2 )
2744 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2745 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2746 std::swap( uv0, uv1 );
2749 const gp_XY rangeUV = uv1 - uv0;
2750 for ( int i = iFrom; i < iTo; ++i )
2752 double r = len[i-iFrom] / len.back();
2753 gp_XY newUV = uv0 + r * rangeUV;
2754 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2756 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2757 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2758 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2759 dumpMove( tgtNode );
2761 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2762 pos->SetUParameter( newUV.X() );
2763 pos->SetVParameter( newUV.Y() );
2769 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2771 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2772 gp_Pnt center3D = circle->Location();
2774 if ( F.IsNull() ) // 3D
2776 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2777 data._edges[iTo-1]->_2neibors->_nodes[1] )
2778 return true; // closed EDGE - nothing to do
2780 return false; // TODO ???
2784 const gp_XY center( center3D.X(), center3D.Y() );
2786 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2787 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2788 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2789 gp_Vec2d vec0( center, uv0 );
2790 gp_Vec2d vecM( center, uvM );
2791 gp_Vec2d vec1( center, uv1 );
2792 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2793 double uMidl = vec0.Angle( vecM );
2794 if ( uLast * uMidl < 0. )
2795 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2796 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2798 gp_Ax2d axis( center, vec0 );
2799 gp_Circ2d circ( axis, radius );
2800 for ( int i = iFrom; i < iTo; ++i )
2802 double newU = uLast * len[i-iFrom] / len.back();
2803 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2804 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2806 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2807 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2808 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2809 dumpMove( tgtNode );
2811 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2812 pos->SetUParameter( newUV.X() );
2813 pos->SetVParameter( newUV.Y() );
2822 //================================================================================
2824 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2825 * _LayerEdge's on neighbor EDGE's
2827 //================================================================================
2829 bool _ViscousBuilder::updateNormals( _SolidData& data,
2830 SMESH_MesherHelper& helper )
2832 // make temporary quadrangles got by extrusion of
2833 // mesh edges along _LayerEdge._normal's
2835 vector< const SMDS_MeshElement* > tmpFaces;
2837 set< SMESH_TLink > extrudedLinks; // contains target nodes
2838 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2840 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2841 for ( size_t i = 0; i < data._edges.size(); ++i )
2843 _LayerEdge* edge = data._edges[i];
2844 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2845 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2846 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2848 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2849 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2850 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2851 if ( !link_isnew.second )
2853 extrudedLinks.erase( link_isnew.first );
2854 continue; // already extruded and will no more encounter
2856 // look for a _LayerEdge containg tgt2
2857 // _LayerEdge* neiborEdge = 0;
2858 // size_t di = 0; // check _edges[i+di] and _edges[i-di]
2859 // while ( !neiborEdge && ++di <= data._edges.size() )
2861 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2862 // neiborEdge = data._edges[i+di];
2863 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2864 // neiborEdge = data._edges[i-di];
2866 // if ( !neiborEdge )
2867 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2868 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2870 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2871 tmpFaces.push_back( f );
2873 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2874 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2875 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2880 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2881 // Perform two loops on _LayerEdge on EDGE's:
2882 // 1) to find and fix intersection
2883 // 2) to check that no new intersection appears as result of 1)
2885 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2887 auto_ptr<SMESH_ElementSearcher> searcher
2888 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
2890 // 1) Find intersections
2892 const SMDS_MeshElement* face;
2893 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2894 TLEdge2LEdgeSet edge2CloseEdge;
2896 const double eps = data._epsilon * data._epsilon;
2897 for ( size_t i = 0; i < data._edges.size(); ++i )
2899 _LayerEdge* edge = data._edges[i];
2900 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2901 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2903 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2904 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2905 ee.insert( f->_le1 );
2906 ee.insert( f->_le2 );
2907 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2908 edge2CloseEdge[ f->_le1 ].insert( edge );
2909 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2910 edge2CloseEdge[ f->_le2 ].insert( edge );
2914 // Set _LayerEdge._normal
2916 if ( !edge2CloseEdge.empty() )
2918 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2920 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2921 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2923 _LayerEdge* edge1 = e2ee->first;
2924 _LayerEdge* edge2 = 0;
2925 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2927 // find EDGEs the edges reside
2929 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2930 if ( S.ShapeType() != TopAbs_EDGE )
2931 continue; // TODO: find EDGE by VERTEX
2932 E1 = TopoDS::Edge( S );
2933 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2934 while ( E2.IsNull() && eIt != ee.end())
2936 _LayerEdge* e2 = *eIt++;
2937 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2938 if ( S.ShapeType() == TopAbs_EDGE )
2939 E2 = TopoDS::Edge( S ), edge2 = e2;
2941 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2943 // find 3 FACEs sharing 2 EDGEs
2945 TopoDS_Face FF1[2], FF2[2];
2946 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2947 while ( fIt->more() && FF1[1].IsNull())
2949 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2950 if ( helper.IsSubShape( *F, data._solid))
2951 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2953 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2954 while ( fIt->more() && FF2[1].IsNull())
2956 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2957 if ( helper.IsSubShape( *F, data._solid))
2958 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2960 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2961 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2962 std::swap( FF1[0], FF1[1] );
2963 if ( FF2[0].IsSame( FF1[0]) )
2964 std::swap( FF2[0], FF2[1] );
2965 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2968 // // get a new normal for edge1
2970 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2971 if ( edge1->_cosin < 0 )
2972 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2973 if ( edge2->_cosin < 0 )
2974 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2975 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2976 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2977 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2978 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2979 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2980 // newNorm.Normalize();
2982 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2983 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2984 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2985 newNorm.Normalize();
2987 edge1->_normal = newNorm.XYZ();
2989 // update data of edge1 depending on _normal
2990 const SMDS_MeshNode *n1, *n2;
2991 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2992 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2993 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2995 edge1->SetDataByNeighbors( n1, n2, helper );
2997 if ( edge1->_cosin < 0 )
3000 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3001 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3002 edge1->SetCosin( cos( angle ));
3004 // limit data._stepSize
3005 if ( edge1->_cosin > 0.1 )
3007 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3008 while ( fIt->more() )
3009 limitStepSize( data, fIt->next(), edge1->_cosin );
3011 // set new XYZ of target node
3012 edge1->InvalidateStep( 1 );
3014 edge1->SetNewLength( data._stepSize, helper );
3017 // Update normals and other dependent data of not intersecting _LayerEdge's
3018 // neighboring the intersecting ones
3020 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3022 _LayerEdge* edge1 = e2ee->first;
3023 if ( !edge1->_2neibors )
3025 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3027 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3028 if ( edge2CloseEdge.count ( neighbor ))
3029 continue; // j-th neighbor is also intersected
3030 _LayerEdge* prevEdge = edge1;
3031 const int nbSteps = 6;
3032 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3034 if ( !neighbor->_2neibors )
3035 break; // neighbor is on VERTEX
3037 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3038 if ( nextEdge == prevEdge )
3039 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3040 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
3041 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
3042 double r = double(step-1)/nbSteps;
3043 if ( !nextEdge->_2neibors )
3046 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3047 newNorm.Normalize();
3049 neighbor->_normal = newNorm;
3050 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3051 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3053 neighbor->InvalidateStep( 1 );
3055 neighbor->SetNewLength( data._stepSize, helper );
3057 // goto the next neighbor
3058 prevEdge = neighbor;
3059 neighbor = nextEdge;
3065 // 2) Check absence of intersections
3068 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3074 //================================================================================
3076 * \brief Looks for intersection of it's last segment with faces
3077 * \param distance - returns shortest distance from the last node to intersection
3079 //================================================================================
3081 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
3083 const double& epsilon,
3084 const SMDS_MeshElement** face)
3086 vector< const SMDS_MeshElement* > suspectFaces;
3088 gp_Ax1 lastSegment = LastSegment(segLen);
3089 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
3091 bool segmentIntersected = false;
3092 distance = Precision::Infinite();
3093 int iFace = -1; // intersected face
3094 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3096 const SMDS_MeshElement* face = suspectFaces[j];
3097 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3098 face->GetNodeIndex( _nodes[0] ) >= 0 )
3099 continue; // face sharing _LayerEdge node
3100 const int nbNodes = face->NbCornerNodes();
3101 bool intFound = false;
3103 SMDS_MeshElement::iterator nIt = face->begin_nodes();
3106 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3110 const SMDS_MeshNode* tria[3];
3113 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3116 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3122 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3123 segmentIntersected = true;
3124 if ( distance > dist )
3125 distance = dist, iFace = j;
3128 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3129 // if ( distance && iFace > -1 )
3131 // // distance is used to limit size of inflation step which depends on
3132 // // whether the intersected face bears viscous layers or not
3133 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3137 if ( segmentIntersected )
3140 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3141 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3142 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3143 << ", intersection with face ("
3144 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3145 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3146 << ") distance = " << distance - segLen<< endl;
3152 return segmentIntersected;
3155 //================================================================================
3157 * \brief Returns size and direction of the last segment
3159 //================================================================================
3161 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3163 // find two non-coincident positions
3164 gp_XYZ orig = _pos.back();
3166 int iPrev = _pos.size() - 2;
3167 while ( iPrev >= 0 )
3169 dir = orig - _pos[iPrev];
3170 if ( dir.SquareModulus() > 1e-100 )
3180 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3181 segDir.SetDirection( _normal );
3186 gp_Pnt pPrev = _pos[ iPrev ];
3187 if ( !_sWOL.IsNull() )
3189 TopLoc_Location loc;
3190 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3193 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3194 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3198 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3199 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3201 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3203 segDir.SetLocation( pPrev );
3204 segDir.SetDirection( dir );
3205 segLen = dir.Modulus();
3211 //================================================================================
3213 * \brief Test intersection of the last segment with a given triangle
3214 * using Moller-Trumbore algorithm
3215 * Intersection is detected if distance to intersection is less than _LayerEdge._len
3217 //================================================================================
3219 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
3220 const SMDS_MeshNode* n0,
3221 const SMDS_MeshNode* n1,
3222 const SMDS_MeshNode* n2,
3224 const double& EPSILON) const
3226 //const double EPSILON = 1e-6;
3228 gp_XYZ orig = lastSegment.Location().XYZ();
3229 gp_XYZ dir = lastSegment.Direction().XYZ();
3231 SMESH_TNodeXYZ vert0( n0 );
3232 SMESH_TNodeXYZ vert1( n1 );
3233 SMESH_TNodeXYZ vert2( n2 );
3235 /* calculate distance from vert0 to ray origin */
3236 gp_XYZ tvec = orig - vert0;
3238 if ( tvec * dir > EPSILON )
3239 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3242 gp_XYZ edge1 = vert1 - vert0;
3243 gp_XYZ edge2 = vert2 - vert0;
3245 /* begin calculating determinant - also used to calculate U parameter */
3246 gp_XYZ pvec = dir ^ edge2;
3248 /* if determinant is near zero, ray lies in plane of triangle */
3249 double det = edge1 * pvec;
3251 if (det > -EPSILON && det < EPSILON)
3253 double inv_det = 1.0 / det;
3255 /* calculate U parameter and test bounds */
3256 double u = ( tvec * pvec ) * inv_det;
3257 if (u < 0.0 || u > 1.0)
3260 /* prepare to test V parameter */
3261 gp_XYZ qvec = tvec ^ edge1;
3263 /* calculate V parameter and test bounds */
3264 double v = (dir * qvec) * inv_det;
3265 if ( v < 0.0 || u + v > 1.0 )
3268 /* calculate t, ray intersects triangle */
3269 t = (edge2 * qvec) * inv_det;
3271 // if (det < EPSILON)
3274 // /* calculate distance from vert0 to ray origin */
3275 // gp_XYZ tvec = orig - vert0;
3277 // /* calculate U parameter and test bounds */
3278 // double u = tvec * pvec;
3279 // if (u < 0.0 || u > det)
3282 // /* prepare to test V parameter */
3283 // gp_XYZ qvec = tvec ^ edge1;
3285 // /* calculate V parameter and test bounds */
3286 // double v = dir * qvec;
3287 // if (v < 0.0 || u + v > det)
3290 // /* calculate t, scale parameters, ray intersects triangle */
3291 // double t = edge2 * qvec;
3292 // double inv_det = 1.0 / det;
3300 //================================================================================
3302 * \brief Perform smooth of _LayerEdge's based on EDGE's
3303 * \retval bool - true if node has been moved
3305 //================================================================================
3307 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3308 const TopoDS_Face& F,
3309 SMESH_MesherHelper& helper)
3311 ASSERT( IsOnEdge() );
3313 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3314 SMESH_TNodeXYZ oldPos( tgtNode );
3315 double dist01, distNewOld;
3317 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3318 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3319 dist01 = p0.Distance( _2neibors->_nodes[1] );
3321 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3322 double lenDelta = 0;
3325 //lenDelta = _curvature->lenDelta( _len );
3326 lenDelta = _curvature->lenDeltaByDist( dist01 );
3327 newPos.ChangeCoord() += _normal * lenDelta;
3330 distNewOld = newPos.Distance( oldPos );
3334 if ( _2neibors->_plnNorm )
3336 // put newPos on the plane defined by source node and _plnNorm
3337 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3338 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3339 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3341 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3342 _pos.back() = newPos.XYZ();
3346 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3347 gp_XY uv( Precision::Infinite(), 0 );
3348 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3349 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3351 newPos = surface->Value( uv.X(), uv.Y() );
3352 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3355 if ( _curvature && lenDelta < 0 )
3357 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3358 _len -= prevPos.Distance( oldPos );
3359 _len += prevPos.Distance( newPos );
3361 bool moved = distNewOld > dist01/50;
3363 dumpMove( tgtNode ); // debug
3368 //================================================================================
3370 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3371 * \retval bool - true if _tgtNode has been moved
3373 //================================================================================
3375 bool _LayerEdge::Smooth(int& badNb)
3377 if ( _simplices.size() < 2 )
3378 return false; // _LayerEdge inflated along EDGE or FACE
3380 // compute new position for the last _pos
3381 gp_XYZ newPos (0,0,0);
3382 for ( size_t i = 0; i < _simplices.size(); ++i )
3383 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3384 newPos /= _simplices.size();
3387 newPos += _normal * _curvature->lenDelta( _len );
3389 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3390 // if ( _cosin < -0.1)
3392 // // Avoid decreasing length of edge on concave surface
3393 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3394 // gp_Vec newMove( prevPos, newPos );
3395 // newPos = _pos.back() + newMove.XYZ();
3397 // else if ( _cosin > 0.3 )
3399 // // Avoid increasing length of edge too much
3402 // count quality metrics (orientation) of tetras around _tgtNode
3404 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3405 for ( size_t i = 0; i < _simplices.size(); ++i )
3406 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3409 for ( size_t i = 0; i < _simplices.size(); ++i )
3410 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3412 if ( nbOkAfter < nbOkBefore )
3415 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3417 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3418 _len += prevPos.Distance(newPos);
3420 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3421 _pos.back() = newPos;
3423 badNb += _simplices.size() - nbOkAfter;
3430 //================================================================================
3432 * \brief Add a new segment to _LayerEdge during inflation
3434 //================================================================================
3436 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3438 if ( _len - len > -1e-6 )
3440 _pos.push_back( _pos.back() );
3444 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3445 SMESH_TNodeXYZ oldXYZ( n );
3446 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3447 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3449 _pos.push_back( nXYZ );
3451 if ( !_sWOL.IsNull() )
3454 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3456 double u = Precision::Infinite(); // to force projection w/o distance check
3457 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3458 _pos.back().SetCoord( u, 0, 0 );
3459 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3460 pos->SetUParameter( u );
3464 gp_XY uv( Precision::Infinite(), 0 );
3465 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3466 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3467 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3468 pos->SetUParameter( uv.X() );
3469 pos->SetVParameter( uv.Y() );
3471 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3473 dumpMove( n ); //debug
3476 //================================================================================
3478 * \brief Remove last inflation step
3480 //================================================================================
3482 void _LayerEdge::InvalidateStep( int curStep )
3484 if ( _pos.size() > curStep )
3486 _pos.resize( curStep );
3487 gp_Pnt nXYZ = _pos.back();
3488 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3489 if ( !_sWOL.IsNull() )
3491 TopLoc_Location loc;
3492 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3494 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3495 pos->SetUParameter( nXYZ.X() );
3497 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3498 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3502 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3503 pos->SetUParameter( nXYZ.X() );
3504 pos->SetVParameter( nXYZ.Y() );
3505 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3506 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3509 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3514 //================================================================================
3516 * \brief Create layers of prisms
3518 //================================================================================
3520 bool _ViscousBuilder::refine(_SolidData& data)
3522 SMESH_MesherHelper helper( *_mesh );
3523 helper.SetSubShape( data._solid );
3524 helper.SetElementsOnShape(false);
3526 Handle(Geom_Curve) curve;
3527 Handle(Geom_Surface) surface;
3528 TopoDS_Edge geomEdge;
3529 TopoDS_Face geomFace;
3530 TopLoc_Location loc;
3531 double f,l, u/*, distXYZ[4]*/;
3535 for ( size_t i = 0; i < data._edges.size(); ++i )
3537 _LayerEdge& edge = *data._edges[i];
3539 // get accumulated length of segments
3540 vector< double > segLen( edge._pos.size() );
3542 for ( size_t j = 1; j < edge._pos.size(); ++j )
3543 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3545 // allocate memory for new nodes if it is not yet refined
3546 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3547 if ( edge._nodes.size() == 2 )
3549 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3551 edge._nodes.back() = tgtNode;
3553 if ( !edge._sWOL.IsNull() )
3555 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3556 // restore position of the last node
3560 geomEdge = TopoDS::Edge( edge._sWOL );
3561 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3562 // double u = helper.GetNodeU( tgtNode );
3563 // p = curve->Value( u );
3567 geomFace = TopoDS::Face( edge._sWOL );
3568 surface = BRep_Tool::Surface( geomFace, loc );
3569 // gp_XY uv = helper.GetNodeUV( tgtNode );
3570 // p = surface->Value( uv.X(), uv.Y() );
3572 // p.Transform( loc );
3573 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3575 // calculate height of the first layer
3577 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3578 const double f = data._hyp->GetStretchFactor();
3579 const int N = data._hyp->GetNumberLayers();
3580 const double fPowN = pow( f, N );
3581 if ( fPowN - 1 <= numeric_limits<double>::min() )
3584 h0 = T * ( f - 1 )/( fPowN - 1 );
3586 const double zeroLen = std::numeric_limits<double>::min();
3588 // create intermediate nodes
3589 double hSum = 0, hi = h0/f;
3591 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3593 // compute an intermediate position
3596 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3598 int iPrevSeg = iSeg-1;
3599 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3601 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3602 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3604 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3605 if ( !edge._sWOL.IsNull() )
3607 // compute XYZ by parameters <pos>
3611 pos = curve->Value( u ).Transformed(loc);
3615 uv.SetCoord( pos.X(), pos.Y() );
3616 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3619 // create or update the node
3622 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3623 if ( !edge._sWOL.IsNull() )
3626 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3628 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3632 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3637 if ( !edge._sWOL.IsNull() )
3639 // make average pos from new and current parameters
3642 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3643 pos = curve->Value( u ).Transformed(loc);
3647 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3648 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3651 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3656 if ( !getMeshDS()->IsEmbeddedMode() )
3657 // Log node movement
3658 for ( size_t i = 0; i < data._edges.size(); ++i )
3660 _LayerEdge& edge = *data._edges[i];
3661 SMESH_TNodeXYZ p ( edge._nodes.back() );
3662 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3665 // TODO: make quadratic prisms and polyhedrons(?)
3667 helper.SetElementsOnShape(true);
3669 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3670 for ( ; exp.More(); exp.Next() )
3672 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3674 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3675 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3676 vector< vector<const SMDS_MeshNode*>* > nnVec;
3677 while ( fIt->more() )
3679 const SMDS_MeshElement* face = fIt->next();
3680 int nbNodes = face->NbCornerNodes();
3681 nnVec.resize( nbNodes );
3682 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3683 for ( int iN = 0; iN < nbNodes; ++iN )
3685 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3686 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3689 int nbZ = nnVec[0]->size();
3693 for ( int iZ = 1; iZ < nbZ; ++iZ )
3694 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3695 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3698 for ( int iZ = 1; iZ < nbZ; ++iZ )
3699 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3700 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3701 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3702 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3705 return error("Not supported type of element", data._index);
3712 //================================================================================
3714 * \brief Shrink 2D mesh on faces to let space for inflated layers
3716 //================================================================================
3718 bool _ViscousBuilder::shrink()
3720 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3721 // inflated along FACE or EDGE)
3722 map< TGeomID, _SolidData* > f2sdMap;
3723 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3725 _SolidData& data = _sdVec[i];
3726 TopTools_MapOfShape FFMap;
3727 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3728 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3729 if ( s2s->second.ShapeType() == TopAbs_FACE )
3731 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3733 if ( FFMap.Add( (*s2s).second ))
3734 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3735 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3736 // by StdMeshers_QuadToTriaAdaptor
3737 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3739 SMESH_ProxyMesh::SubMesh* proxySub =
3740 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3741 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3742 while ( fIt->more() )
3743 proxySub->AddElement( fIt->next() );
3744 // as a result 3D algo will use elements from proxySub and not from smDS
3749 SMESH_MesherHelper helper( *_mesh );
3750 helper.ToFixNodeParameters( true );
3753 map< TGeomID, _Shrinker1D > e2shrMap;
3755 // loop on FACES to srink mesh on
3756 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3757 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3759 _SolidData& data = *f2sd->second;
3760 TNode2Edge& n2eMap = data._n2eMap;
3761 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3763 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3765 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3766 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3768 helper.SetSubShape(F);
3770 // ===========================
3771 // Prepare data for shrinking
3772 // ===========================
3774 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3775 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3776 vector < const SMDS_MeshNode* > smoothNodes;
3778 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3779 while ( nIt->more() )
3781 const SMDS_MeshNode* n = nIt->next();
3782 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3783 smoothNodes.push_back( n );
3786 // Find out face orientation
3788 const set<TGeomID> ignoreShapes;
3790 if ( !smoothNodes.empty() )
3792 vector<_Simplex> simplices;
3793 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3794 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3795 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3796 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3797 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3801 // Find _LayerEdge's inflated along F
3802 vector< _LayerEdge* > lEdges;
3804 SMESH_subMeshIteratorPtr subIt =
3805 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3806 while ( subIt->more() )
3808 SMESH_subMesh* sub = subIt->next();
3809 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3810 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3812 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3813 while ( nIt->more() )
3815 _LayerEdge* edge = n2eMap[ nIt->next() ];
3816 lEdges.push_back( edge );
3817 prepareEdgeToShrink( *edge, F, helper, smDS );
3822 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3823 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3824 while ( fIt->more() )
3825 if ( const SMDS_MeshElement* f = fIt->next() )
3826 dumpChangeNodes( f );
3828 // Replace source nodes by target nodes in mesh faces to shrink
3829 const SMDS_MeshNode* nodes[20];
3830 for ( size_t i = 0; i < lEdges.size(); ++i )
3832 _LayerEdge& edge = *lEdges[i];
3833 const SMDS_MeshNode* srcNode = edge._nodes[0];
3834 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3835 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3836 while ( fIt->more() )
3838 const SMDS_MeshElement* f = fIt->next();
3839 if ( !smDS->Contains( f ))
3841 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
3842 for ( int iN = 0; nIt->more(); ++iN )
3844 const SMDS_MeshNode* n = nIt->next();
3845 nodes[iN] = ( n == srcNode ? tgtNode : n );
3847 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3851 // find out if a FACE is concave
3852 const bool isConcaveFace = isConcave( F, helper );
3854 // Create _SmoothNode's on face F
3855 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3857 const bool sortSimplices = isConcaveFace;
3858 for ( size_t i = 0; i < smoothNodes.size(); ++i )
3860 const SMDS_MeshNode* n = smoothNodes[i];
3861 nodesToSmooth[ i ]._node = n;
3862 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3863 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
3864 // fix up incorrect uv of nodes on the FACE
3865 helper.GetNodeUV( F, n, 0, &isOkUV);
3869 //if ( nodesToSmooth.empty() ) continue;
3871 // Find EDGE's to shrink and set simpices to LayerEdge's
3872 set< _Shrinker1D* > eShri1D;
3874 for ( size_t i = 0; i < lEdges.size(); ++i )
3876 _LayerEdge* edge = lEdges[i];
3877 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3879 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3880 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3881 eShri1D.insert( & srinker );
3882 srinker.AddEdge( edge, helper );
3883 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3884 // restore params of nodes on EGDE if the EDGE has been already
3885 // srinked while srinking another FACE
3886 srinker.RestoreParams();
3888 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
3892 bool toFixTria = false; // to improve quality of trias by diagonal swap
3893 if ( isConcaveFace )
3895 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3896 if ( hasTria != hasQuad ) {
3897 toFixTria = hasTria;
3900 set<int> nbNodesSet;
3901 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3902 while ( fIt->more() && nbNodesSet.size() < 2 )
3903 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3904 toFixTria = ( *nbNodesSet.begin() == 3 );
3908 // ==================
3909 // Perform shrinking
3910 // ==================
3912 bool shrinked = true;
3913 int badNb, shriStep=0, smooStep=0;
3914 _SmoothNode::SmoothType smoothType
3915 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
3919 // Move boundary nodes (actually just set new UV)
3920 // -----------------------------------------------
3921 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
3923 for ( size_t i = 0; i < lEdges.size(); ++i )
3925 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3929 // Move nodes on EDGE's
3930 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
3931 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3932 for ( ; shr != eShri1D.end(); ++shr )
3933 (*shr)->Compute( /*set3D=*/false, helper );
3936 // -----------------
3937 int nbNoImpSteps = 0;
3940 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3942 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3944 int oldBadNb = badNb;
3947 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
3949 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3950 smoothType, /*set3D=*/isConcaveFace);
3952 if ( badNb < oldBadNb )
3960 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3961 if ( shriStep > 200 )
3962 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
3964 // Fix narrow triangles by swapping diagonals
3965 // ---------------------------------------
3968 set<const SMDS_MeshNode*> usedNodes;
3969 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
3971 // update working data
3972 set<const SMDS_MeshNode*>::iterator n;
3973 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
3975 n = usedNodes.find( nodesToSmooth[ i ]._node );
3976 if ( n != usedNodes.end())
3978 getSimplices( nodesToSmooth[ i ]._node,
3979 nodesToSmooth[ i ]._simplices,
3981 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
3982 usedNodes.erase( n );
3985 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
3987 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
3988 if ( n != usedNodes.end())
3990 getSimplices( lEdges[i]->_nodes.back(),
3991 lEdges[i]->_simplices,
3993 usedNodes.erase( n );
3997 } // while ( shrinked )
3999 // No wrongly shaped faces remain; final smooth. Set node XYZ.
4000 bool isStructuredFixed = false;
4001 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4002 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4003 if ( !isStructuredFixed )
4005 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4006 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4008 for ( int st = 3; st; --st )
4011 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4012 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4013 case 3: smoothType = _SmoothNode::ANGULAR; break;
4015 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4016 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4018 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4019 smoothType,/*set3D=*/st==1 );
4024 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4025 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4027 if ( !getMeshDS()->IsEmbeddedMode() )
4028 // Log node movement
4029 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4031 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4032 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4035 } // loop on FACES to srink mesh on
4038 // Replace source nodes by target nodes in shrinked mesh edges
4040 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4041 for ( ; e2shr != e2shrMap.end(); ++e2shr )
4042 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4047 //================================================================================
4049 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4051 //================================================================================
4053 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
4054 const TopoDS_Face& F,
4055 SMESH_MesherHelper& helper,
4056 const SMESHDS_SubMesh* faceSubMesh)
4058 const SMDS_MeshNode* srcNode = edge._nodes[0];
4059 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4063 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4065 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4066 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4067 gp_Vec2d uvDir( srcUV, tgtUV );
4068 double uvLen = uvDir.Magnitude();
4070 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4073 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4074 // vector<const SMDS_MeshElement*> faces;
4075 // multimap< double, const SMDS_MeshNode* > proj2node;
4076 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4077 // while ( fIt->more() )
4079 // const SMDS_MeshElement* f = fIt->next();
4080 // if ( faceSubMesh->Contains( f ))
4081 // faces.push_back( f );
4083 // for ( size_t i = 0; i < faces.size(); ++i )
4085 // const int nbNodes = faces[i]->NbCornerNodes();
4086 // for ( int j = 0; j < nbNodes; ++j )
4088 // const SMDS_MeshNode* n = faces[i]->GetNode(j);
4089 // if ( n == srcNode ) continue;
4090 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
4091 // ( faces.size() > 1 || nbNodes > 3 ))
4093 // gp_Pnt2d uv = helper.GetNodeUV( F, n );
4094 // gp_Vec2d uvDirN( srcUV, uv );
4095 // double proj = uvDirN * uvDir;
4096 // proj2node.insert( make_pair( proj, n ));
4100 // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4101 // const double minProj = p2n->first;
4102 // const double projThreshold = 1.1 * uvLen;
4103 // if ( minProj > projThreshold )
4105 // // tgtNode is located so that it does not make faces with wrong orientation
4108 edge._pos.resize(1);
4109 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4111 // store most risky nodes in _simplices
4112 // p2nEnd = proj2node.lower_bound( projThreshold );
4113 // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4114 // edge._simplices.resize( nbSimpl );
4115 // for ( int i = 0; i < nbSimpl; ++i )
4117 // edge._simplices[i]._nPrev = p2n->second;
4118 // if ( ++p2n != p2nEnd )
4119 // edge._simplices[i]._nNext = p2n->second;
4121 // set UV of source node to target node
4122 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4123 pos->SetUParameter( srcUV.X() );
4124 pos->SetVParameter( srcUV.Y() );
4126 else // _sWOL is TopAbs_EDGE
4128 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4129 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4130 if ( !edgeSM || edgeSM->NbElements() == 0 )
4131 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4133 const SMDS_MeshNode* n2 = 0;
4134 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4135 while ( eIt->more() && !n2 )
4137 const SMDS_MeshElement* e = eIt->next();
4138 if ( !edgeSM->Contains(e)) continue;
4139 n2 = e->GetNode( 0 );
4140 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4143 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4145 double uSrc = helper.GetNodeU( E, srcNode, n2 );
4146 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4147 double u2 = helper.GetNodeU( E, n2, srcNode );
4149 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4151 // tgtNode is located so that it does not make faces with wrong orientation
4154 edge._pos.resize(1);
4155 edge._pos[0].SetCoord( U_TGT, uTgt );
4156 edge._pos[0].SetCoord( U_SRC, uSrc );
4157 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4159 edge._simplices.resize( 1 );
4160 edge._simplices[0]._nPrev = n2;
4162 // set UV of source node to target node
4163 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4164 pos->SetUParameter( uSrc );
4168 //================================================================================
4170 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4172 //================================================================================
4174 // Compute UV to follow during shrinking
4176 // const SMDS_MeshNode* srcNode = edge._nodes[0];
4177 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
4179 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4180 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4181 // gp_Vec2d uvDir( srcUV, tgtUV );
4182 // double uvLen = uvDir.Magnitude();
4185 // // Select shrinking step such that not to make faces with wrong orientation.
4186 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4187 // const double minStepSize = uvLen / 20;
4188 // double stepSize = uvLen;
4189 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4190 // while ( fIt->more() )
4192 // const SMDS_MeshElement* f = fIt->next();
4193 // if ( !faceSubMesh->Contains( f )) continue;
4194 // const int nbNodes = f->NbCornerNodes();
4195 // for ( int i = 0; i < nbNodes; ++i )
4197 // const SMDS_MeshNode* n = f->GetNode(i);
4198 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4200 // gp_XY uv = helper.GetNodeUV( F, n );
4201 // gp_Vec2d uvDirN( srcUV, uv );
4202 // double proj = uvDirN * uvDir;
4203 // if ( proj < stepSize && proj > minStepSize )
4209 // const int nbSteps = ceil( uvLen / stepSize );
4210 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4211 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4212 // edge._pos.resize( nbSteps );
4213 // edge._pos[0] = tgtUV0;
4214 // for ( int i = 1; i < nbSteps; ++i )
4216 // double r = i / double( nbSteps );
4217 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4222 //================================================================================
4224 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4226 //================================================================================
4228 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
4229 SMESH_MesherHelper& helper,
4232 set<const SMDS_MeshNode*> * involvedNodes)
4234 SMESH::Controls::AspectRatio qualifier;
4235 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4236 const double maxAspectRatio = is2D ? 4. : 2;
4237 NodeCoordHelper xyz( F, helper, is2D );
4239 // find bad triangles
4241 vector< const SMDS_MeshElement* > badTrias;
4242 vector< double > badAspects;
4243 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
4244 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4245 while ( fIt->more() )
4247 const SMDS_MeshElement * f = fIt->next();
4248 if ( f->NbCornerNodes() != 3 ) continue;
4249 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4250 double aspect = qualifier.GetValue( points );
4251 if ( aspect > maxAspectRatio )
4253 badTrias.push_back( f );
4254 badAspects.push_back( aspect );
4259 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4260 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4261 while ( fIt->more() )
4263 const SMDS_MeshElement * f = fIt->next();
4264 if ( f->NbCornerNodes() == 3 )
4265 dumpChangeNodes( f );
4269 if ( badTrias.empty() )
4272 // find couples of faces to swap diagonal
4274 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4275 vector< T2Trias > triaCouples;
4277 TIDSortedElemSet involvedFaces, emptySet;
4278 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4281 double aspRatio [3];
4284 if ( !involvedFaces.insert( badTrias[iTia] ).second )
4286 for ( int iP = 0; iP < 3; ++iP )
4287 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4289 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4290 int bestCouple = -1;
4291 for ( int iSide = 0; iSide < 3; ++iSide )
4293 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4294 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4295 trias [iSide].first = badTrias[iTia];
4296 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4298 if (( ! trias[iSide].second ) ||
4299 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4300 ( ! sm->Contains( trias[iSide].second )))
4303 // aspect ratio of an adjacent tria
4304 for ( int iP = 0; iP < 3; ++iP )
4305 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4306 double aspectInit = qualifier.GetValue( points2 );
4308 // arrange nodes as after diag-swaping
4309 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4310 i3 = helper.WrapIndex( i1-1, 3 );
4312 i3 = helper.WrapIndex( i1+1, 3 );
4314 points1( 1+ iSide ) = points2( 1+ i3 );
4315 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
4317 // aspect ratio after diag-swaping
4318 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4319 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4322 // prevent inversion of a triangle
4323 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4324 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4325 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4328 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4332 if ( bestCouple >= 0 )
4334 triaCouples.push_back( trias[bestCouple] );
4335 involvedFaces.insert ( trias[bestCouple].second );
4339 involvedFaces.erase( badTrias[iTia] );
4342 if ( triaCouples.empty() )
4347 SMESH_MeshEditor editor( helper.GetMesh() );
4348 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4349 for ( size_t i = 0; i < triaCouples.size(); ++i )
4351 dumpChangeNodes( triaCouples[i].first );
4352 dumpChangeNodes( triaCouples[i].second );
4353 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4356 if ( involvedNodes )
4357 for ( size_t i = 0; i < triaCouples.size(); ++i )
4359 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4360 triaCouples[i].first->end_nodes() );
4361 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4362 triaCouples[i].second->end_nodes() );
4365 // just for debug dump resulting triangles
4366 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4367 for ( size_t i = 0; i < triaCouples.size(); ++i )
4369 dumpChangeNodes( triaCouples[i].first );
4370 dumpChangeNodes( triaCouples[i].second );
4374 //================================================================================
4376 * \brief Move target node to it's final position on the FACE during shrinking
4378 //================================================================================
4380 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4381 const TopoDS_Face& F,
4382 SMESH_MesherHelper& helper )
4385 return false; // already at the target position
4387 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4389 if ( _sWOL.ShapeType() == TopAbs_FACE )
4391 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4392 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4393 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4394 const double uvLen = tgtUV.Distance( curUV );
4395 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4397 // Select shrinking step such that not to make faces with wrong orientation.
4398 double stepSize = uvLen;
4399 for ( size_t i = 0; i < _simplices.size(); ++i )
4401 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4402 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4403 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4404 gp_XY dirN = uvN2 - uvN1;
4405 double det = uvDir.Crossed( dirN );
4406 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
4407 gp_XY dirN2Cur = curUV - uvN1;
4408 double step = dirN.Crossed( dirN2Cur ) / det;
4410 stepSize = Min( step, stepSize );
4413 if ( uvLen - stepSize < _len / 200. )
4418 else if ( stepSize > 0 )
4420 newUV = curUV + uvDir.XY() * stepSize * kSafe;
4426 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4427 pos->SetUParameter( newUV.X() );
4428 pos->SetVParameter( newUV.Y() );
4431 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4432 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4433 dumpMove( tgtNode );
4436 else // _sWOL is TopAbs_EDGE
4438 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4439 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4440 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4442 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4443 const double uSrc = _pos[0].Coord( U_SRC );
4444 const double lenTgt = _pos[0].Coord( LEN_TGT );
4446 double newU = _pos[0].Coord( U_TGT );
4447 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4453 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4455 tgtPos->SetUParameter( newU );
4457 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4458 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4459 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4460 dumpMove( tgtNode );
4466 //================================================================================
4468 * \brief Perform smooth on the FACE
4469 * \retval bool - true if the node has been moved
4471 //================================================================================
4473 bool _SmoothNode::Smooth(int& badNb,
4474 Handle(Geom_Surface)& surface,
4475 SMESH_MesherHelper& helper,
4476 const double refSign,
4480 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4482 // get uv of surrounding nodes
4483 vector<gp_XY> uv( _simplices.size() );
4484 for ( size_t i = 0; i < _simplices.size(); ++i )
4485 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4487 // compute new UV for the node
4489 if ( how == TFI && _simplices.size() == 4 )
4492 for ( size_t i = 0; i < _simplices.size(); ++i )
4493 if ( _simplices[i]._nOpp )
4494 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4496 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4498 newPos = helper.calcTFI ( 0.5, 0.5,
4499 corners[0], corners[1], corners[2], corners[3],
4500 uv[1], uv[2], uv[3], uv[0] );
4502 else if ( how == ANGULAR )
4504 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4506 else if ( how == CENTROIDAL && _simplices.size() > 3 )
4508 // average centers of diagonals wieghted with their reciprocal lengths
4509 if ( _simplices.size() == 4 )
4511 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4512 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4513 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4517 double sumWeight = 0;
4518 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4519 for ( int i = 0; i < nb; ++i )
4522 int iTo = i + _simplices.size() - 1;
4523 for ( int j = iFrom; j < iTo; ++j )
4525 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4526 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4528 newPos += w * ( uv[i]+uv[i2] );
4531 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4537 for ( size_t i = 0; i < _simplices.size(); ++i )
4539 newPos /= _simplices.size();
4542 // count quality metrics (orientation) of triangles around the node
4544 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4545 for ( size_t i = 0; i < _simplices.size(); ++i )
4546 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4549 for ( size_t i = 0; i < _simplices.size(); ++i )
4550 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4552 if ( nbOkAfter < nbOkBefore )
4554 badNb += _simplices.size() - nbOkBefore;
4558 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4559 pos->SetUParameter( newPos.X() );
4560 pos->SetVParameter( newPos.Y() );
4567 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4568 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4572 badNb += _simplices.size() - nbOkAfter;
4573 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4576 //================================================================================
4578 * \brief Computes new UV using angle based smoothing technic
4580 //================================================================================
4582 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4583 const gp_XY& uvToFix,
4584 const double refSign)
4586 uv.push_back( uv.front() );
4588 vector< gp_XY > edgeDir ( uv.size() );
4589 vector< double > edgeSize( uv.size() );
4590 for ( size_t i = 1; i < edgeDir.size(); ++i )
4592 edgeDir [i-1] = uv[i] - uv[i-1];
4593 edgeSize[i-1] = edgeDir[i-1].Modulus();
4594 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4595 edgeDir[i-1].SetX( 100 );
4597 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4599 edgeDir.back() = edgeDir.front();
4600 edgeSize.back() = edgeSize.front();
4605 for ( size_t i = 1; i < edgeDir.size(); ++i )
4607 if ( edgeDir[i-1].X() > 1. ) continue;
4609 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4610 if ( i == edgeDir.size() ) break;
4612 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4613 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4614 gp_XY bisec = norm1 + norm2;
4615 double bisecSize = bisec.Modulus();
4616 if ( bisecSize < numeric_limits<double>::min() )
4618 bisec = -edgeDir[i1] + edgeDir[i];
4619 bisecSize = bisec.Modulus();
4623 gp_XY dirToN = uvToFix - p;
4624 double distToN = dirToN.Modulus();
4625 if ( bisec * dirToN < 0 )
4628 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4630 sumSize += edgeSize[i1] + edgeSize[i];
4632 newPos /= /*nbEdges * */sumSize;
4636 //================================================================================
4638 * \brief Delete _SolidData
4640 //================================================================================
4642 _SolidData::~_SolidData()
4644 for ( size_t i = 0; i < _edges.size(); ++i )
4646 if ( _edges[i] && _edges[i]->_2neibors )
4647 delete _edges[i]->_2neibors;
4652 //================================================================================
4654 * \brief Add a _LayerEdge inflated along the EDGE
4656 //================================================================================
4658 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4661 if ( _nodes.empty() )
4663 _edges[0] = _edges[1] = 0;
4667 if ( e == _edges[0] || e == _edges[1] )
4669 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4670 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4671 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4672 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4675 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4677 BRep_Tool::Range( E, f,l );
4678 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4679 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4683 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4684 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4686 if ( _nodes.empty() )
4688 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4689 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4691 TopLoc_Location loc;
4692 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4693 GeomAdaptor_Curve aCurve(C, f,l);
4694 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4696 int nbExpectNodes = eSubMesh->NbNodes();
4697 _initU .reserve( nbExpectNodes );
4698 _normPar.reserve( nbExpectNodes );
4699 _nodes .reserve( nbExpectNodes );
4700 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4701 while ( nIt->more() )
4703 const SMDS_MeshNode* node = nIt->next();
4704 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4705 node == tgtNode0 || node == tgtNode1 )
4706 continue; // refinement nodes
4707 _nodes.push_back( node );
4708 _initU.push_back( helper.GetNodeU( E, node ));
4709 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4710 _normPar.push_back( len / totLen );
4715 // remove target node of the _LayerEdge from _nodes
4717 for ( size_t i = 0; i < _nodes.size(); ++i )
4718 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4719 _nodes[i] = 0, nbFound++;
4720 if ( nbFound == _nodes.size() )
4725 //================================================================================
4727 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4729 //================================================================================
4731 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4733 if ( _done || _nodes.empty())
4735 const _LayerEdge* e = _edges[0];
4736 if ( !e ) e = _edges[1];
4739 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4740 ( !_edges[1] || _edges[1]->_pos.empty() ));
4742 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4744 if ( set3D || _done )
4746 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4747 GeomAdaptor_Curve aCurve(C, f,l);
4750 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4752 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4753 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4755 for ( size_t i = 0; i < _nodes.size(); ++i )
4757 if ( !_nodes[i] ) continue;
4758 double len = totLen * _normPar[i];
4759 GCPnts_AbscissaPoint discret( aCurve, len, f );
4760 if ( !discret.IsDone() )
4761 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4762 double u = discret.Parameter();
4763 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4764 pos->SetUParameter( u );
4765 gp_Pnt p = C->Value( u );
4766 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4771 BRep_Tool::Range( E, f,l );
4773 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4775 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4777 for ( size_t i = 0; i < _nodes.size(); ++i )
4779 if ( !_nodes[i] ) continue;
4780 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4781 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4782 pos->SetUParameter( u );
4787 //================================================================================
4789 * \brief Restore initial parameters of nodes on EDGE
4791 //================================================================================
4793 void _Shrinker1D::RestoreParams()
4796 for ( size_t i = 0; i < _nodes.size(); ++i )
4798 if ( !_nodes[i] ) continue;
4799 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4800 pos->SetUParameter( _initU[i] );
4805 //================================================================================
4807 * \brief Replace source nodes by target nodes in shrinked mesh edges
4809 //================================================================================
4811 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4813 const SMDS_MeshNode* nodes[3];
4814 for ( int i = 0; i < 2; ++i )
4816 if ( !_edges[i] ) continue;
4818 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4819 if ( !eSubMesh ) return;
4820 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4821 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4822 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4823 while ( eIt->more() )
4825 const SMDS_MeshElement* e = eIt->next();
4826 if ( !eSubMesh->Contains( e ))
4828 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4829 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4831 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4832 nodes[iN] = ( n == srcNode ? tgtNode : n );
4834 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4839 //================================================================================
4841 * \brief Creates 2D and 1D elements on boundaries of new prisms
4843 //================================================================================
4845 bool _ViscousBuilder::addBoundaryElements()
4847 SMESH_MesherHelper helper( *_mesh );
4849 for ( size_t i = 0; i < _sdVec.size(); ++i )
4851 _SolidData& data = _sdVec[i];
4852 TopTools_IndexedMapOfShape geomEdges;
4853 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4854 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4856 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4858 // Get _LayerEdge's based on E
4860 map< double, const SMDS_MeshNode* > u2nodes;
4861 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4864 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4865 TNode2Edge & n2eMap = data._n2eMap;
4866 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4868 //check if 2D elements are needed on E
4869 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4870 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4871 ledges.push_back( n2e->second );
4873 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4874 continue; // no layers on E
4875 ledges.push_back( n2eMap[ u2n->second ]);
4877 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4878 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4879 int nbSharedPyram = 0;
4880 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4881 while ( vIt->more() )
4883 const SMDS_MeshElement* v = vIt->next();
4884 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4886 if ( nbSharedPyram > 1 )
4887 continue; // not free border of the pyramid
4889 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4890 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4891 continue; // faces already created
4893 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4894 ledges.push_back( n2eMap[ u2n->second ]);
4896 // Find out orientation and type of face to create
4898 bool reverse = false, isOnFace;
4900 map< TGeomID, TopoDS_Shape >::iterator e2f =
4901 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4903 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4905 F = e2f->second.Oriented( TopAbs_FORWARD );
4906 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4907 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4908 reverse = !reverse, F.Reverse();
4909 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
4914 // find FACE with layers sharing E
4915 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4916 while ( fIt->more() && F.IsNull() )
4918 const TopoDS_Shape* pF = fIt->next();
4919 if ( helper.IsSubShape( *pF, data._solid) &&
4920 !data._ignoreFaceIds.count( e2f->first ))
4924 // Find the sub-mesh to add new faces
4925 SMESHDS_SubMesh* sm = 0;
4927 sm = getMeshDS()->MeshElements( F );
4929 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4931 return error("error in addBoundaryElements()", data._index);
4934 const int dj1 = reverse ? 0 : 1;
4935 const int dj2 = reverse ? 1 : 0;
4936 for ( size_t j = 1; j < ledges.size(); ++j )
4938 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4939 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4941 for ( size_t z = 1; z < nn1.size(); ++z )
4942 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4944 for ( size_t z = 1; z < nn1.size(); ++z )
4945 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4949 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4951 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4952 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4954 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4955 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4957 helper.SetSubShape( edge->_sWOL );
4958 helper.SetElementsOnShape( true );
4959 for ( size_t z = 1; z < nn.size(); ++z )
4960 helper.AddEdge( nn[z-1], nn[z] );