1 // Copyright (C) 2007-2011 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.
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_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_ProxyMesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_subMeshEventListener.hxx"
44 #include "utilities.h"
46 #include <BRepAdaptor_Curve2d.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_B2d.hxx>
49 #include <Bnd_B3d.hxx>
51 #include <GCPnts_AbscissaPoint.hxx>
52 #include <Geom2d_Circle.hxx>
53 #include <Geom2d_Line.hxx>
54 #include <Geom2d_TrimmedCurve.hxx>
55 #include <GeomAdaptor_Curve.hxx>
56 #include <Geom_Circle.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_TrimmedCurve.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <TColStd_Array1OfReal.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_IndexedMapOfShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_Vertex.hxx>
84 //================================================================================
89 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
92 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
93 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
95 struct _MeshOfSolid : public SMESH_ProxyMesh,
96 public SMESH_subMeshEventListenerData
100 _MeshOfSolid( SMESH_Mesh* mesh)
101 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
103 SMESH_ProxyMesh::setMesh( *mesh );
106 // returns submesh for a geom face
107 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
109 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
110 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
112 void setNode2Node(const SMDS_MeshNode* srcNode,
113 const SMDS_MeshNode* proxyNode,
114 const SMESH_ProxyMesh::SubMesh* subMesh)
116 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
119 //--------------------------------------------------------------------------------
121 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
122 * It is used to clear an inferior dim sub-meshes modified by viscous layers
124 class _SrinkShapeListener : SMESH_subMeshEventListener
126 _SrinkShapeListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
127 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
129 virtual void ProcessEvent(const int event,
131 SMESH_subMesh* solidSM,
132 SMESH_subMeshEventListenerData* data,
133 const SMESH_Hypothesis* hyp)
135 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
137 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
140 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
141 const TopoDS_Shape& solid)
143 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
144 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
147 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
148 data->mySubMeshes.end())
149 data->mySubMeshes.push_back( sm );
153 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
154 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
158 //--------------------------------------------------------------------------------
160 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
161 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
162 * delete the data as soon as it has been used
164 class _ViscousListener : SMESH_subMeshEventListener
166 _ViscousListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
167 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
169 virtual void ProcessEvent(const int event,
171 SMESH_subMesh* subMesh,
172 SMESH_subMeshEventListenerData* data,
173 const SMESH_Hypothesis* hyp)
175 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
177 // delete SMESH_ProxyMesh containing temporary faces
178 subMesh->DeleteEventListener( this );
181 // Finds or creates proxy mesh of the solid
182 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
183 const TopoDS_Shape& solid,
186 if ( !mesh ) return 0;
187 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
188 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
189 if ( !data && toCreate )
191 data = new _MeshOfSolid(mesh);
192 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
193 sm->SetEventListener( Get(), data, sm );
197 // Removes proxy mesh of the solid
198 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
200 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
204 //--------------------------------------------------------------------------------
206 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
207 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
208 * The class is used to check validity of face or volumes around a smoothed node;
209 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
213 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
214 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
215 : _nPrev(nPrev), _nNext(nNext) {}
216 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
218 const double M[3][3] =
219 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
220 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
221 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
222 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
223 + M[0][1]*M[1][2]*M[2][0]
224 + M[0][2]*M[1][0]*M[2][1]
225 - M[0][0]*M[1][2]*M[2][1]
226 - M[0][1]*M[1][0]*M[2][2]
227 - M[0][2]*M[1][1]*M[2][0]);
228 return determinant > 1e-100;
230 bool IsForward(const gp_XY& tgtUV,
231 const SMDS_MeshNode* smoothedNode,
232 const TopoDS_Face& face,
233 SMESH_MesherHelper& helper,
234 const double refSign) const
236 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
237 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
238 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
240 return d*refSign > 1e-100;
242 bool IsNeighbour(const _Simplex& other) const
244 return _nPrev == other._nNext || _nNext == other._nPrev;
247 //--------------------------------------------------------------------------------
249 * Structure used to take into account surface curvature while smoothing
254 double _k; // factor to correct node smoothed position
256 static _Curvature* New( double avgNormProj, double avgDist )
259 if ( fabs( avgNormProj / avgDist ) > 1./200 )
262 c->_r = avgDist * avgDist / avgNormProj;
263 c->_k = avgDist * avgDist / c->_r / c->_r;
264 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
268 double lenDelta(double len) const { return _k * ( _r + len ); }
271 //--------------------------------------------------------------------------------
273 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
277 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
278 const SMDS_MeshNode* _nodes[2];
279 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
281 double _wgt[2]; // weights of _nodes
282 _LayerEdge* _edges[2];
284 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
287 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
289 std::swap( _nodes[0], _nodes[1] );
290 std::swap( _wgt[0], _wgt[1] );
293 //--------------------------------------------------------------------------------
295 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
296 * and a node of the most internal layer (_nodes.back())
300 vector< const SMDS_MeshNode*> _nodes;
302 gp_XYZ _normal; // to solid surface
303 vector<gp_XYZ> _pos; // points computed during inflation
304 double _len; // length achived with the last step
305 double _cosin; // of angle (_normal ^ surface)
306 double _lenFactor; // to compute _len taking _cosin into account
308 // face or edge w/o layer along or near which _LayerEdge is inflated
310 // simplices connected to the source node (_nodes[0]);
311 // used for smoothing and quality check of _LayerEdge's based on the FACE
312 vector<_Simplex> _simplices;
313 // data for smoothing of _LayerEdge's based on the EDGE
314 _2NearEdges* _2neibors;
316 _Curvature* _curvature;
317 // TODO:: detele _Curvature, _plnNorm
319 void SetNewLength( double len, SMESH_MesherHelper& helper );
320 bool SetNewLength2d( Handle(Geom_Surface)& surface,
321 const TopoDS_Face& F,
322 SMESH_MesherHelper& helper );
323 void SetDataByNeighbors( const SMDS_MeshNode* n1,
324 const SMDS_MeshNode* n2,
325 SMESH_MesherHelper& helper);
326 void InvalidateStep( int curStep );
327 bool Smooth(int& badNb);
328 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
329 const TopoDS_Face& F,
330 SMESH_MesherHelper& helper);
331 bool FindIntersection( SMESH_ElementSearcher& searcher,
333 const double& epsilon,
334 const SMDS_MeshElement** face = 0);
335 bool SegTriaInter( const gp_Ax1& lastSegment,
336 const SMDS_MeshNode* n0,
337 const SMDS_MeshNode* n1,
338 const SMDS_MeshNode* n2,
340 const double& epsilon) const;
341 gp_Ax1 LastSegment(double& segLen) const;
342 bool IsOnEdge() const { return _2neibors; }
343 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
344 void SetCosin( double cosin );
348 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
350 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
351 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
354 //--------------------------------------------------------------------------------
356 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
358 //--------------------------------------------------------------------------------
360 * \brief Data of a SOLID
365 const StdMeshers_ViscousLayers* _hyp;
366 _MeshOfSolid* _proxyMesh;
367 set<TGeomID> _reversedFaceIds;
369 double _stepSize, _stepSizeCoeff;
370 const SMDS_MeshNode* _stepSizeNodes[2];
373 // edges of _n2eMap. We keep same data in two containers because
374 // iteration over the map is 5 time longer than over the vector
375 vector< _LayerEdge* > _edges;
377 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
378 // layers and a FACE w/o layers
379 // value: the shape (FACE or EDGE) to shrink mesh on.
380 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
381 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
383 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
384 set< TGeomID > _noShrinkFaces;
386 // <EDGE to smooth on> to <it's curve>
387 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
389 // end indices in _edges of _LayerEdge on one shape to smooth
390 vector< int > _endEdgeToSmooth;
392 double _epsilon; // precision for SegTriaInter()
394 int _index; // for debug
396 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
397 const StdMeshers_ViscousLayers* h=0,
398 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
401 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
404 Handle(Geom_Surface)& surface,
405 const TopoDS_Face& F,
406 SMESH_MesherHelper& helper);
408 //--------------------------------------------------------------------------------
410 * \brief Data of node on a shrinked FACE
414 const SMDS_MeshNode* _node;
415 //vector<const SMDS_MeshNode*> _nodesAround;
416 vector<_Simplex> _simplices; // for quality check
418 bool Smooth(int& badNb,
419 Handle(Geom_Surface)& surface,
420 SMESH_MesherHelper& helper,
421 const double refSign,
425 //--------------------------------------------------------------------------------
427 * \brief Builder of viscous layers
429 class _ViscousBuilder
434 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
435 const TopoDS_Shape& shape);
437 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
438 void RestoreListeners();
440 // computes SMESH_ProxyMesh::SubMesh::_n2n;
441 bool MakeN2NMap( _MeshOfSolid* pm );
445 bool findSolidsWithLayers();
446 bool findFacesWithLayers();
447 bool makeLayer(_SolidData& data);
448 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
449 SMESH_MesherHelper& helper, _SolidData& data);
450 bool findNeiborsOnEdge(const _LayerEdge* edge,
451 const SMDS_MeshNode*& n1,
452 const SMDS_MeshNode*& n2,
454 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
455 const set<TGeomID>& ingnoreShapes,
456 const _SolidData* dataToCheckOri = 0,
457 const bool toSort = false);
458 bool sortEdges( _SolidData& data,
459 vector< vector<_LayerEdge*> >& edgesByGeom);
460 void limitStepSize( _SolidData& data,
461 const SMDS_MeshElement* face,
463 void limitStepSize( _SolidData& data, const double minSize);
464 bool inflate(_SolidData& data);
465 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
466 bool smoothAnalyticEdge( _SolidData& data,
469 Handle(Geom_Surface)& surface,
470 const TopoDS_Face& F,
471 SMESH_MesherHelper& helper);
472 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
473 bool refine(_SolidData& data);
475 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
476 SMESH_MesherHelper& helper,
477 const SMESHDS_SubMesh* faceSubMesh );
478 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
479 bool addBoundaryElements();
481 bool error( const string& text, int solidID=-1 );
482 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
485 void makeGroupOfLE();
488 SMESH_ComputeErrorPtr _error;
490 vector< _SolidData > _sdVec;
491 set<TGeomID> _ignoreShapeIds;
494 //--------------------------------------------------------------------------------
496 * \brief Shrinker of nodes on the EDGE
500 vector<double> _initU;
501 vector<double> _normPar;
502 vector<const SMDS_MeshNode*> _nodes;
503 const _LayerEdge* _edges[2];
506 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
507 void Compute(bool set3D, SMESH_MesherHelper& helper);
508 void RestoreParams();
509 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
511 //--------------------------------------------------------------------------------
513 * \brief Class of temporary mesh face.
514 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
515 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
517 struct TmpMeshFace : public SMDS_MeshElement
519 vector<const SMDS_MeshNode* > _nn;
520 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
521 SMDS_MeshElement(id), _nn(nodes) {}
522 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
523 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
524 virtual vtkIdType GetVtkType() const { return -1; }
525 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
526 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
527 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
529 //--------------------------------------------------------------------------------
531 * \brief Class of temporary mesh face storing _LayerEdge it's based on
533 struct TmpMeshFaceOnEdge : public TmpMeshFace
535 _LayerEdge *_le1, *_le2;
536 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
537 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
539 _nn[0]=_le1->_nodes[0];
540 _nn[1]=_le1->_nodes.back();
541 _nn[2]=_le2->_nodes.back();
542 _nn[3]=_le2->_nodes[0];
545 } // namespace VISCOUS
547 //================================================================================
548 // StdMeshers_ViscousLayers hypothesis
550 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
551 :SMESH_Hypothesis(hypId, studyId, gen),
552 _nbLayers(1), _thickness(1), _stretchFactor(1)
554 _name = StdMeshers_ViscousLayers::GetHypType();
555 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
556 } // --------------------------------------------------------------------------------
557 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
559 if ( faceIds != _ignoreFaceIds )
560 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
561 } // --------------------------------------------------------------------------------
562 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
564 if ( thickness != _thickness )
565 _thickness = thickness, NotifySubMeshesHypothesisModification();
566 } // --------------------------------------------------------------------------------
567 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
569 if ( _nbLayers != nb )
570 _nbLayers = nb, NotifySubMeshesHypothesisModification();
571 } // --------------------------------------------------------------------------------
572 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
574 if ( _stretchFactor != factor )
575 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
576 } // --------------------------------------------------------------------------------
578 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
579 const TopoDS_Shape& theShape,
580 const bool toMakeN2NMap) const
582 using namespace VISCOUS;
583 _ViscousBuilder bulder;
584 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
585 if ( err && !err->IsOK() )
586 return SMESH_ProxyMesh::Ptr();
588 vector<SMESH_ProxyMesh::Ptr> components;
589 TopExp_Explorer exp( theShape, TopAbs_SOLID );
590 for ( ; exp.More(); exp.Next() )
592 if ( _MeshOfSolid* pm =
593 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
595 if ( toMakeN2NMap && !pm->_n2nMapComputed )
596 if ( !bulder.MakeN2NMap( pm ))
597 return SMESH_ProxyMesh::Ptr();
598 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
599 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
601 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
603 switch ( components.size() )
607 case 1: return components[0];
609 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
611 return SMESH_ProxyMesh::Ptr();
612 } // --------------------------------------------------------------------------------
613 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
615 save << " " << _nbLayers
617 << " " << _stretchFactor
618 << " " << _ignoreFaceIds.size();
619 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
620 save << " " << _ignoreFaceIds[i];
622 } // --------------------------------------------------------------------------------
623 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
626 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
627 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
628 _ignoreFaceIds.push_back( faceID );
630 } // --------------------------------------------------------------------------------
631 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
632 const TopoDS_Shape& theShape)
637 // END StdMeshers_ViscousLayers hypothesis
638 //================================================================================
642 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
646 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
647 gp_Pnt p = BRep_Tool::Pnt( fromV );
648 double distF = p.SquareDistance( c->Value( f ));
649 double distL = p.SquareDistance( c->Value( l ));
650 c->D1(( distF < distL ? f : l), p, dir );
651 if ( distL < distF ) dir.Reverse();
654 //--------------------------------------------------------------------------------
655 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
656 SMESH_MesherHelper& helper)
659 double f,l; gp_Pnt p;
660 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
661 double u = helper.GetNodeU( E, atNode );
665 //--------------------------------------------------------------------------------
666 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
667 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
669 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
670 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
671 gp_Pnt p; gp_Vec du, dv, norm;
672 surface->D1( uv.X(),uv.Y(), p, du,dv );
676 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
677 double u = helper.GetNodeU( fromE, node, 0, &ok );
679 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
680 if ( o == TopAbs_REVERSED )
683 gp_Vec dir = norm ^ du;
685 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
686 helper.IsClosedEdge( fromE ))
688 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
689 else c->D1( f, p, dv );
690 if ( o == TopAbs_REVERSED )
692 gp_Vec dir2 = norm ^ dv;
693 dir = dir.Normalized() + dir2.Normalized();
697 //--------------------------------------------------------------------------------
698 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
699 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
700 bool& ok, double* cosin=0)
702 double f,l; TopLoc_Location loc;
703 vector< TopoDS_Edge > edges; // sharing a vertex
704 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
707 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
708 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
709 edges.push_back( *e );
712 if ( !( ok = ( edges.size() > 0 ))) return dir;
713 // get average dir of edges going fromV
715 for ( unsigned i = 0; i < edges.size(); ++i )
717 edgeDir = getEdgeDir( edges[i], fromV );
718 double size2 = edgeDir.SquareMagnitude();
719 if ( size2 > numeric_limits<double>::min() )
720 edgeDir /= sqrt( size2 );
723 dir += edgeDir.XYZ();
725 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
726 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
728 else if ( dir * fromEdgeDir < 0 )
732 //dir /= edges.size();
734 double angle = edgeDir.Angle( dir );
735 *cosin = cos( angle );
740 //================================================================================
742 * \brief Returns true if a FACE is bound by a concave EDGE
744 //================================================================================
746 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
750 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
751 for ( ; eExp.More(); eExp.Next() )
753 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
754 if ( BRep_Tool::Degenerated( E )) continue;
755 // check if 2D curve is concave
756 BRepAdaptor_Curve2d curve( E, F );
757 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
758 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
759 curve.Intervals( intervals, GeomAbs_C2 );
760 bool isConvex = true;
761 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
763 double u1 = intervals( i );
764 double u2 = intervals( i+1 );
765 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
766 double cross = drv2 ^ drv1;
767 if ( E.Orientation() == TopAbs_REVERSED )
769 isConvex = ( cross < 1e-9 );
771 // check if concavity is strong enough to care about it
772 //const double maxAngle = 5 * Standard_PI180;
775 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
777 // map< double, const SMDS_MeshNode* > u2nodes;
778 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
779 // /*ignoreMedium=*/true, u2nodes))
781 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
782 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
783 // double uPrev = u2n->first;
784 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
786 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
787 // gp_Vec2d segmentDir( uvPrev, uv );
788 // curve.D1( uPrev, p, drv1 );
790 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
795 // uPrev = u2n->first;
801 //--------------------------------------------------------------------------------
802 // DEBUG. Dump intermediate node positions into a python script
807 const char* fname = "/tmp/viscous.py";
808 cout << "execfile('"<<fname<<"')"<<endl;
809 py = new ofstream(fname);
810 *py << "from smesh import *" << endl
811 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
812 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
816 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
819 ~PyDump() { Finish(); }
821 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
822 #define dumpMove(n) { _dumpMove(n, __LINE__);}
823 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
824 void _dumpFunction(const string& fun, int ln)
825 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
826 void _dumpMove(const SMDS_MeshNode* n, int ln)
827 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
828 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
829 void _dumpCmd(const string& txt, int ln)
830 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
831 void dumpFunctionEnd()
832 { if (py) *py<< " return"<< endl; }
833 void dumpChangeNodes( const SMDS_MeshElement* f )
834 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
835 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
836 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
838 struct PyDump { void Finish() {} };
839 #define dumpFunction(f) f
842 #define dumpFunctionEnd()
843 #define dumpChangeNodes(f)
847 using namespace VISCOUS;
849 //================================================================================
851 * \brief Constructor of _ViscousBuilder
853 //================================================================================
855 _ViscousBuilder::_ViscousBuilder()
857 _error = SMESH_ComputeError::New(COMPERR_OK);
861 //================================================================================
863 * \brief Stores error description and returns false
865 //================================================================================
867 bool _ViscousBuilder::error(const string& text, int solidId )
869 _error->myName = COMPERR_ALGO_FAILED;
870 _error->myComment = string("Viscous layers builder: ") + text;
873 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
874 if ( !sm && !_sdVec.empty() )
875 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
876 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
878 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
879 if ( smError && smError->myAlgo )
880 _error->myAlgo = smError->myAlgo;
884 makeGroupOfLE(); // debug
889 //================================================================================
891 * \brief At study restoration, restore event listeners used to clear an inferior
892 * dim sub-mesh modified by viscous layers
894 //================================================================================
896 void _ViscousBuilder::RestoreListeners()
901 //================================================================================
903 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
905 //================================================================================
907 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
909 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
910 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
911 for ( ; fExp.More(); fExp.Next() )
913 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
914 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
916 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
918 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
921 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
922 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
924 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
925 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
926 while( prxIt->more() )
928 const SMDS_MeshElement* fSrc = srcIt->next();
929 const SMDS_MeshElement* fPrx = prxIt->next();
930 if ( fSrc->NbNodes() != fPrx->NbNodes())
931 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
932 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
933 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
936 pm->_n2nMapComputed = true;
940 //================================================================================
942 * \brief Does its job
944 //================================================================================
946 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
947 const TopoDS_Shape& theShape)
949 // TODO: set priority of solids during Gen::Compute()
953 // check if proxy mesh already computed
954 TopExp_Explorer exp( theShape, TopAbs_SOLID );
956 return error("No SOLID's in theShape"), _error;
958 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
959 return SMESH_ComputeErrorPtr(); // everything already computed
963 // TODO: ignore already computed SOLIDs
964 if ( !findSolidsWithLayers())
967 if ( !findFacesWithLayers() )
970 for ( unsigned i = 0; i < _sdVec.size(); ++i )
972 if ( ! makeLayer(_sdVec[i]) )
975 if ( ! inflate(_sdVec[i]) )
978 if ( ! refine(_sdVec[i]) )
984 addBoundaryElements();
986 makeGroupOfLE(); // debug
992 //================================================================================
994 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
996 //================================================================================
998 bool _ViscousBuilder::findSolidsWithLayers()
1001 TopTools_IndexedMapOfShape allSolids;
1002 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1003 _sdVec.reserve( allSolids.Extent());
1005 SMESH_Gen* gen = _mesh->GetGen();
1006 for ( int i = 1; i <= allSolids.Extent(); ++i )
1008 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1009 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1010 if ( !algo ) continue;
1011 // TODO: check if algo is hidden
1012 const list <const SMESHDS_Hypothesis *> & allHyps =
1013 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1014 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1015 const StdMeshers_ViscousLayers* viscHyp = 0;
1016 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1017 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1020 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1023 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1024 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1027 if ( _sdVec.empty() )
1029 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1034 //================================================================================
1038 //================================================================================
1040 bool _ViscousBuilder::findFacesWithLayers()
1042 // collect all faces to ignore defined by hyp
1043 vector<TopoDS_Shape> ignoreFaces;
1044 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1046 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
1047 for ( unsigned i = 0; i < ids.size(); ++i )
1049 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1050 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1052 _ignoreShapeIds.insert( ids[i] );
1053 ignoreFaces.push_back( s );
1058 // ignore internal faces
1059 SMESH_MesherHelper helper( *_mesh );
1060 TopExp_Explorer exp;
1061 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1063 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1064 for ( ; exp.More(); exp.Next() )
1066 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1067 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1069 _ignoreShapeIds.insert( faceInd );
1070 ignoreFaces.push_back( exp.Current() );
1071 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1072 _sdVec[i]._reversedFaceIds.insert( faceInd );
1077 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1078 TopTools_IndexedMapOfShape shapes;
1079 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1082 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1083 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1085 const TopoDS_Shape& edge = shapes(iE);
1086 // find 2 faces sharing an edge
1088 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1089 while ( fIt->more())
1091 const TopoDS_Shape* f = fIt->next();
1092 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1093 FF[ int( !FF[0].IsNull()) ] = *f;
1095 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1096 // check presence of layers on them
1098 for ( int j = 0; j < 2; ++j )
1099 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1100 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1101 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1103 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1104 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1107 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1108 // the algo of the SOLID sharing the FACE does not support it
1109 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1110 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1112 TopTools_MapOfShape noShrinkVertices;
1113 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1114 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1116 const TopoDS_Shape& fWOL = e2f->second;
1117 TGeomID edgeID = e2f->first;
1118 bool notShrinkFace = false;
1119 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1120 while ( soIt->more())
1122 const TopoDS_Shape* solid = soIt->next();
1123 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1124 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1125 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1126 notShrinkFace = true;
1127 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1129 if ( _sdVec[j]._solid.IsSame( *solid ) )
1130 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1131 notShrinkFace = false;
1134 if ( notShrinkFace )
1136 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1137 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1138 noShrinkVertices.Add( vExp.Current() );
1141 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1142 // to the found not shrinked fWOL's
1143 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1144 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1146 TGeomID edgeID = e2f->first;
1147 TopoDS_Vertex VV[2];
1148 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1149 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1151 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1152 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1161 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1163 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1166 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1167 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1169 const TopoDS_Shape& vertex = shapes(iV);
1170 // find faces WOL sharing the vertex
1171 vector< TopoDS_Shape > facesWOL;
1172 int totalNbFaces = 0;
1173 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1174 while ( fIt->more())
1176 const TopoDS_Shape* f = fIt->next();
1177 const int fID = getMeshDS()->ShapeToIndex( *f );
1178 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1181 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1182 facesWOL.push_back( *f );
1185 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1186 continue; // no layers at this vertex or no WOL
1187 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1188 switch ( facesWOL.size() )
1192 helper.SetSubShape( facesWOL[0] );
1193 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1195 TopoDS_Shape seamEdge;
1196 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1197 while ( eIt->more() && seamEdge.IsNull() )
1199 const TopoDS_Shape* e = eIt->next();
1200 if ( helper.IsRealSeam( *e ) )
1203 if ( !seamEdge.IsNull() )
1205 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1209 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1214 // find an edge shared by 2 faces
1215 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1216 while ( eIt->more())
1218 const TopoDS_Shape* e = eIt->next();
1219 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1220 helper.IsSubShape( *e, facesWOL[1]))
1222 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1228 return error("Not yet supported case", _sdVec[i]._index);
1236 //================================================================================
1238 * \brief Create the inner surface of the viscous layer and prepare data for infation
1240 //================================================================================
1242 bool _ViscousBuilder::makeLayer(_SolidData& data)
1244 // get all sub-shapes to make layers on
1245 set<TGeomID> subIds, faceIds;
1246 subIds = data._noShrinkFaces;
1247 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1248 for ( ; exp.More(); exp.Next() )
1249 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1251 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1252 faceIds.insert( fSubM->GetId() );
1253 SMESH_subMeshIteratorPtr subIt =
1254 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1255 while ( subIt->more() )
1256 subIds.insert( subIt->next()->GetId() );
1259 // make a map to find new nodes on sub-shapes shared with other SOLID
1260 map< TGeomID, TNode2Edge* > s2neMap;
1261 map< TGeomID, TNode2Edge* >::iterator s2ne;
1262 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1263 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1265 TGeomID shapeInd = s2s->first;
1266 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1268 if ( _sdVec[i]._index == data._index ) continue;
1269 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1270 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1271 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1273 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1279 // Create temporary faces and _LayerEdge's
1281 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1283 data._stepSize = Precision::Infinite();
1284 data._stepSizeNodes[0] = 0;
1286 SMESH_MesherHelper helper( *_mesh );
1287 helper.SetSubShape( data._solid );
1288 helper.SetElementsOnShape(true);
1290 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1291 TNode2Edge::iterator n2e2;
1293 // collect _LayerEdge's of shapes they are based on
1294 const int nbShapes = getMeshDS()->MaxShapeIndex();
1295 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1297 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1299 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1300 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1302 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1303 SMESH_ProxyMesh::SubMesh* proxySub =
1304 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1306 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1307 while ( eIt->more() )
1309 const SMDS_MeshElement* face = eIt->next();
1310 newNodes.resize( face->NbCornerNodes() );
1311 double faceMaxCosin = -1;
1312 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1314 const SMDS_MeshNode* n = face->GetNode(i);
1315 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1316 if ( !(*n2e).second )
1319 _LayerEdge* edge = new _LayerEdge();
1321 edge->_nodes.push_back( n );
1322 const int shapeID = n->getshapeId();
1323 edgesByGeom[ shapeID ].push_back( edge );
1325 // set edge data or find already refined _LayerEdge and get data from it
1326 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1327 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1328 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1330 _LayerEdge* foundEdge = (*n2e2).second;
1331 edge->Copy( *foundEdge, helper );
1332 // location of the last node is modified but we can restore
1333 // it by node position on _sWOL stored by the node
1334 const_cast< SMDS_MeshNode* >
1335 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1339 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1340 if ( !setEdgeData( *edge, subIds, helper, data ))
1343 dumpMove(edge->_nodes.back());
1344 if ( edge->_cosin > 0.01 )
1346 if ( edge->_cosin > faceMaxCosin )
1347 faceMaxCosin = edge->_cosin;
1350 newNodes[ i ] = n2e->second->_nodes.back();
1352 // create a temporary face
1353 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1354 proxySub->AddElement( newFace );
1356 // compute inflation step size by min size of element on a convex surface
1357 if ( faceMaxCosin > 0.1 )
1358 limitStepSize( data, face, faceMaxCosin );
1359 } // loop on 2D elements on a FACE
1360 } // loop on FACEs of a SOLID
1362 data._epsilon = 1e-7;
1363 if ( data._stepSize < 1. )
1364 data._epsilon *= data._stepSize;
1366 // Put _LayerEdge's into a vector
1368 if ( !sortEdges( data, edgesByGeom ))
1371 // Set target nodes into _Simplex and _2NearEdges
1372 TNode2Edge::iterator n2e;
1373 for ( unsigned i = 0; i < data._edges.size(); ++i )
1375 if ( data._edges[i]->IsOnEdge())
1376 for ( int j = 0; j < 2; ++j )
1378 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1379 break; // _LayerEdge is shared by two _SolidData's
1380 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1381 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1382 return error("_LayerEdge not found by src node", data._index);
1383 n = (*n2e).second->_nodes.back();
1384 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1387 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1389 _Simplex& s = data._edges[i]->_simplices[j];
1390 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1391 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1399 //================================================================================
1401 * \brief Compute inflation step size by min size of element on a convex surface
1403 //================================================================================
1405 void _ViscousBuilder::limitStepSize( _SolidData& data,
1406 const SMDS_MeshElement* face,
1410 double minSize = 10 * data._stepSize;
1411 const int nbNodes = face->NbCornerNodes();
1412 for ( int i = 0; i < nbNodes; ++i )
1414 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1415 const SMDS_MeshNode* curN = face->GetNode( i );
1416 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1417 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1419 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1420 if ( dist < minSize )
1421 minSize = dist, iN = i;
1424 double newStep = 0.8 * minSize / cosin;
1425 if ( newStep < data._stepSize )
1427 data._stepSize = newStep;
1428 data._stepSizeCoeff = 0.8 / cosin;
1429 data._stepSizeNodes[0] = face->GetNode( iN );
1430 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1434 //================================================================================
1436 * \brief Compute inflation step size by min size of element on a convex surface
1438 //================================================================================
1440 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1442 if ( minSize < data._stepSize )
1444 data._stepSize = minSize;
1445 if ( data._stepSizeNodes[0] )
1448 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1449 data._stepSizeCoeff = data._stepSize / dist;
1454 //================================================================================
1456 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1458 //================================================================================
1460 bool _ViscousBuilder::sortEdges( _SolidData& data,
1461 vector< vector<_LayerEdge*> >& edgesByGeom)
1463 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1464 // boundry inclined at a sharp angle to the shape
1466 list< TGeomID > shapesToSmooth;
1468 SMESH_MesherHelper helper( *_mesh );
1471 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1473 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1474 if ( eS.empty() ) continue;
1475 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1476 bool needSmooth = false;
1477 switch ( S.ShapeType() )
1481 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1482 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1484 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1485 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1486 if ( eV.empty() ) continue;
1487 double cosin = eV[0]->_cosin;
1489 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1493 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1494 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1496 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1497 eV[0]->_nodes[0], helper, ok);
1498 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1499 double angle = dir1.Angle( dir2 );
1500 cosin = cos( angle );
1502 needSmooth = ( cosin > 0.1 );
1508 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1510 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1511 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1512 if ( eE.empty() ) continue;
1513 if ( eE[0]->_sWOL.IsNull() )
1515 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1516 needSmooth = ( eE[i]->_cosin > 0.1 );
1520 const TopoDS_Face& F1 = TopoDS::Face( S );
1521 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1522 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1523 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1525 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1526 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1527 double angle = dir1.Angle( dir2 );
1528 double cosin = cos( angle );
1529 needSmooth = ( cosin > 0.1 );
1541 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1542 else shapesToSmooth.push_back ( iS );
1545 } // loop on edgesByGeom
1547 data._edges.reserve( data._n2eMap.size() );
1548 data._endEdgeToSmooth.clear();
1550 // first we put _LayerEdge's on shapes to smooth
1551 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1552 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1554 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1555 if ( eVec.empty() ) continue;
1556 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1557 data._endEdgeToSmooth.push_back( data._edges.size() );
1561 // then the rest _LayerEdge's
1562 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1564 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1565 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1572 //================================================================================
1574 * \brief Set data of _LayerEdge needed for smoothing
1575 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1577 //================================================================================
1579 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1580 const set<TGeomID>& subIds,
1581 SMESH_MesherHelper& helper,
1584 SMESH_MeshEditor editor(_mesh);
1586 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1587 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1591 edge._curvature = 0;
1593 // --------------------------
1594 // Compute _normal and _cosin
1595 // --------------------------
1598 edge._normal.SetCoord(0,0,0);
1600 int totalNbFaces = 0;
1602 gp_Vec du, dv, geomNorm;
1605 TGeomID shapeInd = node->getshapeId();
1606 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1607 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1608 TopoDS_Shape vertEdge;
1610 if ( onShrinkShape ) // one of faces the node is on has no layers
1612 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1613 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1615 // inflate from VERTEX along EDGE
1616 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1618 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1620 // inflate from VERTEX along FACE
1621 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1622 node, helper, normOK, &edge._cosin);
1626 // inflate from EDGE along FACE
1627 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1628 node, helper, normOK);
1631 else // layers are on all faces of SOLID the node is on
1633 // find indices of geom faces the node lies on
1634 set<TGeomID> faceIds;
1635 if ( posType == SMDS_TOP_FACE )
1637 faceIds.insert( node->getshapeId() );
1641 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1642 while ( fIt->more() )
1643 faceIds.insert( editor.FindShape(fIt->next()));
1646 set<TGeomID>::iterator id = faceIds.begin();
1648 for ( ; id != faceIds.end(); ++id )
1650 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1651 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1654 //nbLayerFaces += subIds.count( *id );
1655 F = TopoDS::Face( s );
1657 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1658 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1659 surface->D1( uv.X(),uv.Y(), p, du,dv );
1661 double size2 = geomNorm.SquareMagnitude();
1662 if ( size2 > numeric_limits<double>::min() )
1663 geomNorm /= sqrt( size2 );
1666 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1668 edge._normal += geomNorm.XYZ();
1670 if ( totalNbFaces == 0 )
1671 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1673 edge._normal /= totalNbFaces;
1678 edge._cosin = 0; break;
1680 case SMDS_TOP_EDGE: {
1681 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1682 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1683 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1684 edge._cosin = cos( angle );
1685 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1688 case SMDS_TOP_VERTEX: {
1689 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1690 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1691 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1692 edge._cosin = cos( angle );
1693 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1697 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1701 double normSize = edge._normal.SquareModulus();
1702 if ( normSize < numeric_limits<double>::min() )
1703 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1705 edge._normal /= sqrt( normSize );
1707 // TODO: if ( !normOK ) then get normal by mesh faces
1709 // Set the rest data
1710 // --------------------
1711 if ( onShrinkShape )
1713 edge._sWOL = (*s2s).second;
1715 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1716 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1717 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1719 // set initial position which is parameters on _sWOL in this case
1720 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1722 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1723 edge._pos.push_back( gp_XYZ( u, 0, 0));
1724 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1728 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1729 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1730 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1735 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1737 if ( posType == SMDS_TOP_FACE )
1739 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1740 double avgNormProj = 0, avgLen = 0;
1741 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1743 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1744 avgNormProj += edge._normal * vec;
1745 avgLen += vec.Modulus();
1747 avgNormProj /= edge._simplices.size();
1748 avgLen /= edge._simplices.size();
1749 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1753 // Set neighbour nodes for a _LayerEdge based on EDGE
1755 if ( posType == SMDS_TOP_EDGE /*||
1756 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1758 edge._2neibors = new _2NearEdges;
1759 // target node instead of source ones will be set later
1760 if ( ! findNeiborsOnEdge( &edge,
1761 edge._2neibors->_nodes[0],
1762 edge._2neibors->_nodes[1],
1765 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1766 edge._2neibors->_nodes[1],
1770 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1775 //================================================================================
1777 * \brief Find 2 neigbor nodes of a node on EDGE
1779 //================================================================================
1781 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1782 const SMDS_MeshNode*& n1,
1783 const SMDS_MeshNode*& n2,
1786 const SMDS_MeshNode* node = edge->_nodes[0];
1787 const int shapeInd = node->getshapeId();
1788 SMESHDS_SubMesh* edgeSM = 0;
1789 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1792 edgeSM = getMeshDS()->MeshElements( shapeInd );
1793 if ( !edgeSM || edgeSM->NbElements() == 0 )
1794 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1798 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1799 while ( eIt->more() && !n2 )
1801 const SMDS_MeshElement* e = eIt->next();
1802 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1803 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1806 if (!edgeSM->Contains(e)) continue;
1810 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1811 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1813 ( iN++ ? n2 : n1 ) = nNeibor;
1816 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1820 //================================================================================
1822 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1824 //================================================================================
1826 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1827 const SMDS_MeshNode* n2,
1828 SMESH_MesherHelper& helper)
1830 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1833 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1834 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1835 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1839 double sumLen = vec1.Modulus() + vec2.Modulus();
1840 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1841 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1842 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1843 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1844 if ( _curvature ) delete _curvature;
1845 _curvature = _Curvature::New( avgNormProj, avgLen );
1847 // if ( _curvature )
1848 // cout << _nodes[0]->GetID()
1849 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1850 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1851 // << _curvature->lenDelta(0) << endl;
1856 if ( _sWOL.IsNull() )
1858 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1859 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1860 gp_XYZ plnNorm = dirE ^ _normal;
1861 double proj0 = plnNorm * vec1;
1862 double proj1 = plnNorm * vec2;
1863 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1865 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1866 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1871 //================================================================================
1873 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1874 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1876 //================================================================================
1878 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1880 _nodes = other._nodes;
1881 _normal = other._normal;
1883 _lenFactor = other._lenFactor;
1884 _cosin = other._cosin;
1885 _sWOL = other._sWOL;
1886 _2neibors = other._2neibors;
1887 _curvature = 0; std::swap( _curvature, other._curvature );
1888 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1890 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1892 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1893 _pos.push_back( gp_XYZ( u, 0, 0));
1897 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1898 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1902 //================================================================================
1904 * \brief Set _cosin and _lenFactor
1906 //================================================================================
1908 void _LayerEdge::SetCosin( double cosin )
1911 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1914 //================================================================================
1916 * \brief Fills a vector<_Simplex >
1918 //================================================================================
1920 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1921 vector<_Simplex>& simplices,
1922 const set<TGeomID>& ingnoreShapes,
1923 const _SolidData* dataToCheckOri,
1926 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1927 while ( fIt->more() )
1929 const SMDS_MeshElement* f = fIt->next();
1930 const TGeomID shapeInd = f->getshapeId();
1931 if ( ingnoreShapes.count( shapeInd )) continue;
1932 const int nbNodes = f->NbCornerNodes();
1933 int srcInd = f->GetNodeIndex( node );
1934 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1935 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1936 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1937 std::swap( nPrev, nNext );
1938 simplices.push_back( _Simplex( nPrev, nNext ));
1943 vector<_Simplex> sortedSimplices( simplices.size() );
1944 sortedSimplices[0] = simplices[0];
1946 for ( size_t i = 1; i < simplices.size(); ++i )
1948 for ( size_t j = 1; j < simplices.size(); ++j )
1949 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1951 sortedSimplices[i] = simplices[j];
1956 if ( nbFound == simplices.size() - 1 )
1957 simplices.swap( sortedSimplices );
1961 //================================================================================
1963 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1965 //================================================================================
1967 void _ViscousBuilder::makeGroupOfLE()
1970 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1972 if ( _sdVec[i]._edges.empty() ) continue;
1973 // string name = SMESH_Comment("_LayerEdge's_") << i;
1975 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1976 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1977 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1979 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1980 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1982 _LayerEdge* le = _sdVec[i]._edges[j];
1983 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1984 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1985 << ", " << le->_nodes[iN]->GetID() <<"])");
1986 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1990 dumpFunction( SMESH_Comment("makeNormals") << i );
1991 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1993 _LayerEdge& edge = *_sdVec[i]._edges[j];
1994 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1995 nXYZ += edge._normal * _sdVec[i]._stepSize;
1996 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
1997 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2001 // name = SMESH_Comment("tmp_faces ") << i;
2002 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2003 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2004 // SMESH_MeshEditor editor( _mesh );
2005 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2006 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2007 for ( ; fExp.More(); fExp.Next() )
2009 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2011 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2012 while ( fIt->more())
2014 const SMDS_MeshElement* e = fIt->next();
2015 SMESH_Comment cmd("mesh.AddFace([");
2016 for ( int j=0; j < e->NbCornerNodes(); ++j )
2017 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2019 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2020 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2029 //================================================================================
2031 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2033 //================================================================================
2035 bool _ViscousBuilder::inflate(_SolidData& data)
2037 SMESH_MesherHelper helper( *_mesh );
2039 // Limit inflation step size by geometry size found by itersecting
2040 // normals of _LayerEdge's with mesh faces
2041 double geomSize = Precision::Infinite(), intersecDist;
2042 SMESH_MeshEditor editor( _mesh );
2043 auto_ptr<SMESH_ElementSearcher> searcher
2044 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2045 for ( unsigned i = 0; i < data._edges.size(); ++i )
2047 if ( data._edges[i]->IsOnEdge() ) continue;
2048 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2049 if ( geomSize > intersecDist )
2050 geomSize = intersecDist;
2052 if ( data._stepSize > 0.3 * geomSize )
2053 limitStepSize( data, 0.3 * geomSize );
2055 const double tgtThick = data._hyp->GetTotalThickness();
2056 if ( data._stepSize > tgtThick )
2057 limitStepSize( data, tgtThick );
2059 if ( data._stepSize < 1. )
2060 data._epsilon = data._stepSize * 1e-7;
2063 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2066 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2067 int nbSteps = 0, nbRepeats = 0;
2068 while ( 1.01 * avgThick < tgtThick )
2070 // new target length
2071 curThick += data._stepSize;
2072 if ( curThick > tgtThick )
2074 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2078 // Elongate _LayerEdge's
2079 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2080 for ( unsigned i = 0; i < data._edges.size(); ++i )
2082 data._edges[i]->SetNewLength( curThick, helper );
2087 if ( !updateNormals( data, helper ) )
2090 // Improve and check quality
2091 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2095 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2096 for ( unsigned i = 0; i < data._edges.size(); ++i )
2098 data._edges[i]->InvalidateStep( nbSteps+1 );
2102 break; // no more inflating possible
2106 // Evaluate achieved thickness
2108 for ( unsigned i = 0; i < data._edges.size(); ++i )
2109 avgThick += data._edges[i]->_len;
2110 avgThick /= data._edges.size();
2112 cout << "-- Thickness " << avgThick << " reached" << endl;
2115 if ( distToIntersection < avgThick*1.5 )
2118 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2119 << avgThick << " ) * 1.5" << endl;
2124 limitStepSize( data, 0.25 * distToIntersection );
2125 if ( data._stepSizeNodes[0] )
2126 data._stepSize = data._stepSizeCoeff *
2127 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2131 return error("failed at the very first inflation step", data._index);
2136 //================================================================================
2138 * \brief Improve quality of layer inner surface and check intersection
2140 //================================================================================
2142 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2144 double & distToIntersection)
2146 if ( data._endEdgeToSmooth.empty() )
2147 return true; // no shapes needing smoothing
2149 bool moved, improved;
2151 SMESH_MesherHelper helper(*_mesh);
2152 Handle(Geom_Surface) surface;
2156 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2159 iEnd = data._endEdgeToSmooth[ iS ];
2161 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2162 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2164 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2165 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2166 helper.SetSubShape( F );
2167 surface = BRep_Tool::Surface( F );
2172 F.Nullify(); surface.Nullify();
2174 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2176 if ( data._edges[ iBeg ]->IsOnEdge() )
2178 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2180 // try a simple solution on an analytic EDGE
2181 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2187 for ( int i = iBeg; i < iEnd; ++i )
2189 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2191 dumpCmd( SMESH_Comment("# end step ")<<step);
2193 while ( moved && step++ < 5 );
2194 //cout << " NB STEPS: " << step << endl;
2201 int step = 0, badNb = 0; moved = true;
2202 while (( ++step <= 5 && moved ) || improved )
2204 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2205 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2206 int oldBadNb = badNb;
2209 for ( int i = iBeg; i < iEnd; ++i )
2210 moved |= data._edges[i]->Smooth(badNb);
2211 improved = ( badNb < oldBadNb );
2218 for ( int i = iBeg; i < iEnd; ++i )
2220 _LayerEdge* edge = data._edges[i];
2221 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2222 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2223 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2225 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2226 << " "<< edge->_simplices[j]._nPrev->GetID()
2227 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2235 } // loop on shapes to smooth
2237 // Check if the last segments of _LayerEdge intersects 2D elements;
2238 // checked elements are either temporary faces or faces on surfaces w/o the layers
2240 SMESH_MeshEditor editor( _mesh );
2241 auto_ptr<SMESH_ElementSearcher> searcher
2242 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2244 distToIntersection = Precision::Infinite();
2246 const SMDS_MeshElement* intFace = 0;
2248 const SMDS_MeshElement* closestFace = 0;
2251 for ( unsigned i = 0; i < data._edges.size(); ++i )
2253 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2255 if ( distToIntersection > dist )
2257 distToIntersection = dist;
2260 closestFace = intFace;
2267 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2268 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2269 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2270 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2271 << ") distance = " << distToIntersection<< endl;
2278 //================================================================================
2280 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2281 * _LayerEdge's to be in a consequent order
2283 //================================================================================
2285 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2288 Handle(Geom_Surface)& surface,
2289 const TopoDS_Face& F,
2290 SMESH_MesherHelper& helper)
2292 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2294 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2296 if ( i2curve == _edge2curve.end() )
2298 // sort _LayerEdge's by position on the EDGE
2300 map< double, _LayerEdge* > u2edge;
2301 for ( int i = iFrom; i < iTo; ++i )
2302 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2304 ASSERT( u2edge.size() == iTo - iFrom );
2305 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2306 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2307 _edges[i] = u2e->second;
2309 // set _2neibors according to the new order
2310 for ( int i = iFrom; i < iTo-1; ++i )
2311 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2312 _edges[i]->_2neibors->reverse();
2313 if ( u2edge.size() > 1 &&
2314 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2315 _edges[iTo-1]->_2neibors->reverse();
2318 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2320 TopLoc_Location loc; double f,l;
2322 Handle(Geom_Line) line;
2323 Handle(Geom_Circle) circle;
2324 bool isLine, isCirc;
2325 if ( F.IsNull() ) // 3D case
2327 // check if the EDGE is a line
2328 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2329 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2330 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2332 line = Handle(Geom_Line)::DownCast( curve );
2333 circle = Handle(Geom_Circle)::DownCast( curve );
2334 isLine = (!line.IsNull());
2335 isCirc = (!circle.IsNull());
2337 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2340 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2341 while ( nIt->more() )
2342 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2343 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2345 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2346 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2347 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2348 for ( int i = 0; i < 3 && !isLine; ++i )
2349 isLine = ( size.Coord( i+1 ) <= lineTol );
2351 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2358 // check if the EDGE is a line
2359 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2360 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2361 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2363 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2364 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2365 isLine = (!line2d.IsNull());
2366 isCirc = (!circle2d.IsNull());
2368 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2371 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2372 while ( nIt->more() )
2373 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2374 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2376 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2377 for ( int i = 0; i < 2 && !isLine; ++i )
2378 isLine = ( size.Coord( i+1 ) <= lineTol );
2380 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2386 line = new Geom_Line( gp::OX() ); // only type does matter
2390 gp_Pnt2d p = circle2d->Location();
2391 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2392 circle = new Geom_Circle( ax, 1.); // only center position does matter
2396 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2404 return i2curve->second;
2407 //================================================================================
2409 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2411 //================================================================================
2413 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2416 Handle(Geom_Surface)& surface,
2417 const TopoDS_Face& F,
2418 SMESH_MesherHelper& helper)
2420 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2421 helper.GetMeshDS());
2422 TopoDS_Edge E = TopoDS::Edge( S );
2424 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2425 if ( curve.IsNull() ) return false;
2427 // compute a relative length of segments
2428 vector< double > len( iTo-iFrom+1 );
2430 double curLen, prevLen = len[0] = 1.0;
2431 for ( int i = iFrom; i < iTo; ++i )
2433 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2434 len[i-iFrom+1] = len[i-iFrom] + curLen;
2439 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2441 if ( F.IsNull() ) // 3D
2443 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2444 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2445 for ( int i = iFrom; i < iTo; ++i )
2447 double r = len[i-iFrom] / len.back();
2448 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2449 data._edges[i]->_pos.back() = newPos;
2450 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2451 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2452 dumpMove( tgtNode );
2457 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2458 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2459 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2460 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2462 int iPeriodic = helper.GetPeriodicIndex();
2463 if ( iPeriodic == 1 || iPeriodic == 2 )
2465 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2466 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2467 std::swap( uv0, uv1 );
2470 const gp_XY rangeUV = uv1 - uv0;
2471 for ( int i = iFrom; i < iTo; ++i )
2473 double r = len[i-iFrom] / len.back();
2474 gp_XY newUV = uv0 + r * rangeUV;
2475 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2477 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2478 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2479 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2480 dumpMove( tgtNode );
2482 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2483 pos->SetUParameter( newUV.X() );
2484 pos->SetVParameter( newUV.Y() );
2490 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2492 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2493 gp_Pnt center3D = circle->Location();
2495 if ( F.IsNull() ) // 3D
2497 return false; // TODO ???
2501 const gp_XY center( center3D.X(), center3D.Y() );
2503 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2504 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2505 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2506 gp_Vec2d vec0( center, uv0 );
2507 gp_Vec2d vecM( center, uvM);
2508 gp_Vec2d vec1( center, uv1 );
2509 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2510 double uMidl = vec0.Angle( vecM );
2511 if ( uLast < 0 ) uLast += 2*PI; // 0.0 - 2*PI
2512 if ( uMidl < 0 ) uMidl += 2*PI;
2513 const bool sense = ( uMidl < uLast );
2514 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2516 gp_Ax2d axis( center, vec0 );
2517 gp_Circ2d circ ( axis, radius, sense );
2518 for ( int i = iFrom; i < iTo; ++i )
2520 double newU = uLast * len[i-iFrom] / len.back();
2521 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2522 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2524 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2525 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2526 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2527 dumpMove( tgtNode );
2529 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2530 pos->SetUParameter( newUV.X() );
2531 pos->SetVParameter( newUV.Y() );
2540 //================================================================================
2542 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2543 * _LayerEdge's on neighbor EDGE's
2545 //================================================================================
2547 bool _ViscousBuilder::updateNormals( _SolidData& data,
2548 SMESH_MesherHelper& helper )
2550 // make temporary quadrangles got by extrusion of
2551 // mesh edges along _LayerEdge._normal's
2553 vector< const SMDS_MeshElement* > tmpFaces;
2555 set< SMESH_TLink > extrudedLinks; // contains target nodes
2556 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2558 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2559 for ( unsigned i = 0; i < data._edges.size(); ++i )
2561 _LayerEdge* edge = data._edges[i];
2562 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2563 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2564 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2566 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2567 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2568 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2569 if ( !link_isnew.second )
2571 extrudedLinks.erase( link_isnew.first );
2572 continue; // already extruded and will no more encounter
2574 // look for a _LayerEdge containg tgt2
2575 // _LayerEdge* neiborEdge = 0;
2576 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2577 // while ( !neiborEdge && ++di <= data._edges.size() )
2579 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2580 // neiborEdge = data._edges[i+di];
2581 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2582 // neiborEdge = data._edges[i-di];
2584 // if ( !neiborEdge )
2585 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2586 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2588 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2589 tmpFaces.push_back( f );
2591 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2592 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2593 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2598 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2599 // Perform two loops on _LayerEdge on EDGE's:
2600 // 1) to find and fix intersection
2601 // 2) to check that no new intersection appears as result of 1)
2603 SMESH_MeshEditor editor( _mesh );
2604 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2606 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2608 // 1) Find intersections
2610 const SMDS_MeshElement* face;
2611 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2612 TLEdge2LEdgeSet edge2CloseEdge;
2614 const double eps = data._epsilon * data._epsilon;
2615 for ( unsigned i = 0; i < data._edges.size(); ++i )
2617 _LayerEdge* edge = data._edges[i];
2618 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2619 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2621 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2622 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2623 ee.insert( f->_le1 );
2624 ee.insert( f->_le2 );
2625 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2626 edge2CloseEdge[ f->_le1 ].insert( edge );
2627 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2628 edge2CloseEdge[ f->_le2 ].insert( edge );
2632 // Set _LayerEdge._normal
2634 if ( !edge2CloseEdge.empty() )
2636 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2638 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2639 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2641 _LayerEdge* edge1 = e2ee->first;
2642 _LayerEdge* edge2 = 0;
2643 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2645 // find EDGEs the edges reside
2647 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2648 if ( S.ShapeType() != TopAbs_EDGE )
2649 continue; // TODO: find EDGE by VERTEX
2650 E1 = TopoDS::Edge( S );
2651 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2652 while ( E2.IsNull() && eIt != ee.end())
2654 _LayerEdge* e2 = *eIt++;
2655 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2656 if ( S.ShapeType() == TopAbs_EDGE )
2657 E2 = TopoDS::Edge( S ), edge2 = e2;
2659 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2661 // find 3 FACEs sharing 2 EDGEs
2663 TopoDS_Face FF1[2], FF2[2];
2664 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2665 while ( fIt->more() && FF1[1].IsNull())
2667 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2668 if ( helper.IsSubShape( *F, data._solid))
2669 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2671 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2672 while ( fIt->more() && FF2[1].IsNull())
2674 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2675 if ( helper.IsSubShape( *F, data._solid))
2676 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2678 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2679 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2680 std::swap( FF1[0], FF1[1] );
2681 if ( FF2[0].IsSame( FF1[0]) )
2682 std::swap( FF2[0], FF2[1] );
2683 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2686 // // get a new normal for edge1
2688 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2689 if ( edge1->_cosin < 0 )
2690 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2691 if ( edge2->_cosin < 0 )
2692 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2693 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2694 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2695 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2696 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2697 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2698 // newNorm.Normalize();
2700 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2701 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2702 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2703 newNorm.Normalize();
2705 edge1->_normal = newNorm.XYZ();
2707 // update data of edge1 depending on _normal
2708 const SMDS_MeshNode *n1, *n2;
2709 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2710 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2711 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2713 edge1->SetDataByNeighbors( n1, n2, helper );
2715 if ( edge1->_cosin < 0 )
2718 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2719 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2720 edge1->SetCosin( cos( angle ));
2722 // limit data._stepSize
2723 if ( edge1->_cosin > 0.1 )
2725 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2726 while ( fIt->more() )
2727 limitStepSize( data, fIt->next(), edge1->_cosin );
2729 // set new XYZ of target node
2730 edge1->InvalidateStep( 1 );
2732 edge1->SetNewLength( data._stepSize, helper );
2735 // Update normals and other dependent data of not intersecting _LayerEdge's
2736 // neighboring the intersecting ones
2738 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2740 _LayerEdge* edge1 = e2ee->first;
2741 if ( !edge1->_2neibors )
2743 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2745 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2746 if ( edge2CloseEdge.count ( neighbor ))
2747 continue; // j-th neighbor is also intersected
2748 _LayerEdge* prevEdge = edge1;
2749 const int nbSteps = 6;
2750 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2752 if ( !neighbor->_2neibors )
2753 break; // neighbor is on VERTEX
2755 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2756 if ( nextEdge == prevEdge )
2757 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2758 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2759 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2760 double r = double(step-1)/nbSteps;
2761 if ( !nextEdge->_2neibors )
2764 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2765 newNorm.Normalize();
2767 neighbor->_normal = newNorm;
2768 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2769 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2771 neighbor->InvalidateStep( 1 );
2773 neighbor->SetNewLength( data._stepSize, helper );
2775 // goto the next neighbor
2776 prevEdge = neighbor;
2777 neighbor = nextEdge;
2783 // 2) Check absence of intersections
2786 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2792 //================================================================================
2794 * \brief Looks for intersection of it's last segment with faces
2795 * \param distance - returns shortest distance from the last node to intersection
2797 //================================================================================
2799 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2801 const double& epsilon,
2802 const SMDS_MeshElement** face)
2804 vector< const SMDS_MeshElement* > suspectFaces;
2806 gp_Ax1 lastSegment = LastSegment(segLen);
2807 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2809 bool segmentIntersected = false;
2810 distance = Precision::Infinite();
2811 int iFace = -1; // intersected face
2812 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2814 const SMDS_MeshElement* face = suspectFaces[j];
2815 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2816 face->GetNodeIndex( _nodes[0] ) >= 0 )
2817 continue; // face sharing _LayerEdge node
2818 const int nbNodes = face->NbCornerNodes();
2819 bool intFound = false;
2821 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2824 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2828 const SMDS_MeshNode* tria[3];
2831 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2834 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2840 if ( dist < segLen*(1.01))
2841 segmentIntersected = true;
2842 if ( distance > dist )
2843 distance = dist, iFace = j;
2846 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2847 // if ( distance && iFace > -1 )
2849 // // distance is used to limit size of inflation step which depends on
2850 // // whether the intersected face bears viscous layers or not
2851 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2855 if ( segmentIntersected )
2858 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2859 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2860 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2861 << ", intersection with face ("
2862 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2863 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2864 << ") distance = " << distance - segLen<< endl;
2870 return segmentIntersected;
2873 //================================================================================
2875 * \brief Returns size and direction of the last segment
2877 //================================================================================
2879 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2881 // find two non-coincident positions
2882 gp_XYZ orig = _pos.back();
2884 int iPrev = _pos.size() - 2;
2885 while ( iPrev >= 0 )
2887 dir = orig - _pos[iPrev];
2888 if ( dir.SquareModulus() > 1e-100 )
2898 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2899 segDir.SetDirection( _normal );
2904 gp_Pnt pPrev = _pos[ iPrev ];
2905 if ( !_sWOL.IsNull() )
2907 TopLoc_Location loc;
2908 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2911 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2912 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2916 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2917 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2919 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2921 segDir.SetLocation( pPrev );
2922 segDir.SetDirection( dir );
2923 segLen = dir.Modulus();
2929 //================================================================================
2931 * \brief Test intersection of the last segment with a given triangle
2932 * using Moller-Trumbore algorithm
2933 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2935 //================================================================================
2937 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2938 const SMDS_MeshNode* n0,
2939 const SMDS_MeshNode* n1,
2940 const SMDS_MeshNode* n2,
2942 const double& EPSILON) const
2944 //const double EPSILON = 1e-6;
2946 gp_XYZ orig = lastSegment.Location().XYZ();
2947 gp_XYZ dir = lastSegment.Direction().XYZ();
2949 SMESH_TNodeXYZ vert0( n0 );
2950 SMESH_TNodeXYZ vert1( n1 );
2951 SMESH_TNodeXYZ vert2( n2 );
2953 /* calculate distance from vert0 to ray origin */
2954 gp_XYZ tvec = orig - vert0;
2956 if ( tvec * dir > EPSILON )
2957 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2960 gp_XYZ edge1 = vert1 - vert0;
2961 gp_XYZ edge2 = vert2 - vert0;
2963 /* begin calculating determinant - also used to calculate U parameter */
2964 gp_XYZ pvec = dir ^ edge2;
2966 /* if determinant is near zero, ray lies in plane of triangle */
2967 double det = edge1 * pvec;
2969 if (det > -EPSILON && det < EPSILON)
2971 double inv_det = 1.0 / det;
2973 /* calculate U parameter and test bounds */
2974 double u = ( tvec * pvec ) * inv_det;
2975 if (u < 0.0 || u > 1.0)
2978 /* prepare to test V parameter */
2979 gp_XYZ qvec = tvec ^ edge1;
2981 /* calculate V parameter and test bounds */
2982 double v = (dir * qvec) * inv_det;
2983 if ( v < 0.0 || u + v > 1.0 )
2986 /* calculate t, ray intersects triangle */
2987 t = (edge2 * qvec) * inv_det;
2989 // if (det < EPSILON)
2992 // /* calculate distance from vert0 to ray origin */
2993 // gp_XYZ tvec = orig - vert0;
2995 // /* calculate U parameter and test bounds */
2996 // double u = tvec * pvec;
2997 // if (u < 0.0 || u > det)
3000 // /* prepare to test V parameter */
3001 // gp_XYZ qvec = tvec ^ edge1;
3003 // /* calculate V parameter and test bounds */
3004 // double v = dir * qvec;
3005 // if (v < 0.0 || u + v > det)
3008 // /* calculate t, scale parameters, ray intersects triangle */
3009 // double t = edge2 * qvec;
3010 // double inv_det = 1.0 / det;
3018 //================================================================================
3020 * \brief Perform smooth of _LayerEdge's based on EDGE's
3021 * \retval bool - true if node has been moved
3023 //================================================================================
3025 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3026 const TopoDS_Face& F,
3027 SMESH_MesherHelper& helper)
3029 ASSERT( IsOnEdge() );
3031 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3032 SMESH_TNodeXYZ oldPos( tgtNode );
3033 double dist01, distNewOld;
3035 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3036 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3037 dist01 = p0.Distance( _2neibors->_nodes[1] );
3039 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3040 double lenDelta = 0;
3043 lenDelta = _curvature->lenDelta( _len );
3044 newPos.ChangeCoord() += _normal * lenDelta;
3047 distNewOld = newPos.Distance( oldPos );
3051 if ( _2neibors->_plnNorm )
3053 // put newPos on the plane defined by source node and _plnNorm
3054 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3055 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3056 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3058 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3059 _pos.back() = newPos.XYZ();
3063 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3064 gp_XY uv( Precision::Infinite(), 0 );
3065 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3066 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3068 newPos = surface->Value( uv.X(), uv.Y() );
3069 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3072 if ( _curvature && lenDelta < 0 )
3074 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3075 _len -= prevPos.Distance( oldPos );
3076 _len += prevPos.Distance( newPos );
3078 bool moved = distNewOld > dist01/50;
3080 dumpMove( tgtNode ); // debug
3085 //================================================================================
3087 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3088 * \retval bool - true if _tgtNode has been moved
3090 //================================================================================
3092 bool _LayerEdge::Smooth(int& badNb)
3094 if ( _simplices.size() < 2 )
3095 return false; // _LayerEdge inflated along EDGE or FACE
3097 // compute new position for the last _pos
3098 gp_XYZ newPos (0,0,0);
3099 for ( unsigned i = 0; i < _simplices.size(); ++i )
3100 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3101 newPos /= _simplices.size();
3104 newPos += _normal * _curvature->lenDelta( _len );
3106 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3107 // if ( _cosin < -0.1)
3109 // // Avoid decreasing length of edge on concave surface
3110 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3111 // gp_Vec newMove( prevPos, newPos );
3112 // newPos = _pos.back() + newMove.XYZ();
3114 // else if ( _cosin > 0.3 )
3116 // // Avoid increasing length of edge too much
3119 // count quality metrics (orientation) of tetras around _tgtNode
3121 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3122 for ( unsigned i = 0; i < _simplices.size(); ++i )
3123 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3126 for ( unsigned i = 0; i < _simplices.size(); ++i )
3127 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3129 if ( nbOkAfter < nbOkBefore )
3132 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3134 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3135 _len += prevPos.Distance(newPos);
3137 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3138 _pos.back() = newPos;
3140 badNb += _simplices.size() - nbOkAfter;
3147 //================================================================================
3149 * \brief Add a new segment to _LayerEdge during inflation
3151 //================================================================================
3153 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3155 if ( _len - len > -1e-6 )
3157 _pos.push_back( _pos.back() );
3161 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3162 SMESH_TNodeXYZ oldXYZ( n );
3163 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3164 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3166 _pos.push_back( nXYZ );
3168 if ( !_sWOL.IsNull() )
3171 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3173 double u = Precision::Infinite(); // to force projection w/o distance check
3174 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3175 _pos.back().SetCoord( u, 0, 0 );
3176 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3177 pos->SetUParameter( u );
3181 gp_XY uv( Precision::Infinite(), 0 );
3182 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3183 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3184 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3185 pos->SetUParameter( uv.X() );
3186 pos->SetVParameter( uv.Y() );
3188 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3190 dumpMove( n ); //debug
3193 //================================================================================
3195 * \brief Remove last inflation step
3197 //================================================================================
3199 void _LayerEdge::InvalidateStep( int curStep )
3201 if ( _pos.size() > curStep )
3203 _pos.resize( curStep );
3204 gp_Pnt nXYZ = _pos.back();
3205 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3206 if ( !_sWOL.IsNull() )
3208 TopLoc_Location loc;
3209 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3211 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3212 pos->SetUParameter( nXYZ.X() );
3214 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3215 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3219 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3220 pos->SetUParameter( nXYZ.X() );
3221 pos->SetVParameter( nXYZ.Y() );
3222 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3223 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3226 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3231 //================================================================================
3233 * \brief Create layers of prisms
3235 //================================================================================
3237 bool _ViscousBuilder::refine(_SolidData& data)
3239 SMESH_MesherHelper helper( *_mesh );
3240 helper.SetSubShape( data._solid );
3241 helper.SetElementsOnShape(false);
3243 Handle(Geom_Curve) curve;
3244 Handle(Geom_Surface) surface;
3245 TopoDS_Edge geomEdge;
3246 TopoDS_Face geomFace;
3247 TopLoc_Location loc;
3248 double f,l, u/*, distXYZ[4]*/;
3252 for ( unsigned i = 0; i < data._edges.size(); ++i )
3254 _LayerEdge& edge = *data._edges[i];
3256 // get accumulated length of segments
3257 vector< double > segLen( edge._pos.size() );
3259 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3260 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3262 // allocate memory for new nodes if it is not yet refined
3263 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3264 if ( edge._nodes.size() == 2 )
3266 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3268 edge._nodes.back() = tgtNode;
3270 if ( !edge._sWOL.IsNull() )
3272 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3273 // restore position of the last node
3277 geomEdge = TopoDS::Edge( edge._sWOL );
3278 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3279 // double u = helper.GetNodeU( tgtNode );
3280 // p = curve->Value( u );
3284 geomFace = TopoDS::Face( edge._sWOL );
3285 surface = BRep_Tool::Surface( geomFace, loc );
3286 // gp_XY uv = helper.GetNodeUV( tgtNode );
3287 // p = surface->Value( uv.X(), uv.Y() );
3289 // p.Transform( loc );
3290 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3292 // calculate height of the first layer
3294 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3295 const double f = data._hyp->GetStretchFactor();
3296 const int N = data._hyp->GetNumberLayers();
3297 const double fPowN = pow( f, N );
3298 if ( fPowN - 1 <= numeric_limits<double>::min() )
3301 h0 = T * ( f - 1 )/( fPowN - 1 );
3303 const double zeroLen = std::numeric_limits<double>::min();
3305 // create intermediate nodes
3306 double hSum = 0, hi = h0/f;
3308 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3310 // compute an intermediate position
3313 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3315 int iPrevSeg = iSeg-1;
3316 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3318 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3319 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3321 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3322 if ( !edge._sWOL.IsNull() )
3324 // compute XYZ by parameters <pos>
3328 pos = curve->Value( u ).Transformed(loc);
3332 uv.SetCoord( pos.X(), pos.Y() );
3333 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3336 // create or update the node
3339 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3340 if ( !edge._sWOL.IsNull() )
3343 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3345 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3349 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3354 if ( !edge._sWOL.IsNull() )
3356 // make average pos from new and current parameters
3359 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3360 pos = curve->Value( u ).Transformed(loc);
3364 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3365 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3368 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3373 // TODO: make quadratic prisms and polyhedrons(?)
3375 helper.SetElementsOnShape(true);
3377 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3378 for ( ; exp.More(); exp.Next() )
3380 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3382 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3383 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3384 vector< vector<const SMDS_MeshNode*>* > nnVec;
3385 while ( fIt->more() )
3387 const SMDS_MeshElement* face = fIt->next();
3388 int nbNodes = face->NbCornerNodes();
3389 nnVec.resize( nbNodes );
3390 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3391 for ( int iN = 0; iN < nbNodes; ++iN )
3393 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3394 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3397 int nbZ = nnVec[0]->size();
3401 for ( int iZ = 1; iZ < nbZ; ++iZ )
3402 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3403 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3406 for ( int iZ = 1; iZ < nbZ; ++iZ )
3407 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3408 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3409 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3410 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3413 return error("Not supported type of element", data._index);
3420 //================================================================================
3422 * \brief Shrink 2D mesh on faces to let space for inflated layers
3424 //================================================================================
3426 bool _ViscousBuilder::shrink()
3428 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3429 // inflated along FACE or EDGE)
3430 map< TGeomID, _SolidData* > f2sdMap;
3431 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3433 _SolidData& data = _sdVec[i];
3434 TopTools_MapOfShape FFMap;
3435 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3436 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3437 if ( s2s->second.ShapeType() == TopAbs_FACE )
3439 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3441 if ( FFMap.Add( (*s2s).second ))
3442 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3443 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3444 // by StdMeshers_QuadToTriaAdaptor
3445 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3447 SMESH_ProxyMesh::SubMesh* proxySub =
3448 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3449 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3450 while ( fIt->more() )
3451 proxySub->AddElement( fIt->next() );
3452 // as a result 3D algo will use elements from proxySub and not from smDS
3457 SMESH_MesherHelper helper( *_mesh );
3460 map< int, _Shrinker1D > e2shrMap;
3462 // loop on FACES to srink mesh on
3463 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3464 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3466 _SolidData& data = *f2sd->second;
3467 TNode2Edge& n2eMap = data._n2eMap;
3468 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3470 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3472 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3473 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3475 helper.SetSubShape(F);
3477 // ===========================
3478 // Prepare data for shrinking
3479 // ===========================
3481 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3482 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3483 vector < const SMDS_MeshNode* > smoothNodes;
3485 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3486 while ( nIt->more() )
3488 const SMDS_MeshNode* n = nIt->next();
3489 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3490 smoothNodes.push_back( n );
3493 // Find out face orientation
3495 const set<TGeomID> ignoreShapes;
3497 if ( !smoothNodes.empty() )
3499 vector<_Simplex> simplices;
3500 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3501 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3502 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3503 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3504 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3508 // Find _LayerEdge's inflated along F
3509 vector< _LayerEdge* > lEdges;
3511 SMESH_subMeshIteratorPtr subIt =
3512 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3513 while ( subIt->more() )
3515 SMESH_subMesh* sub = subIt->next();
3516 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3517 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3519 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3520 while ( nIt->more() )
3522 _LayerEdge* edge = n2eMap[ nIt->next() ];
3523 lEdges.push_back( edge );
3524 prepareEdgeToShrink( *edge, F, helper, smDS );
3529 // Replace source nodes by target nodes in mesh faces to shrink
3530 const SMDS_MeshNode* nodes[20];
3531 for ( unsigned i = 0; i < lEdges.size(); ++i )
3533 _LayerEdge& edge = *lEdges[i];
3534 const SMDS_MeshNode* srcNode = edge._nodes[0];
3535 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3536 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3537 while ( fIt->more() )
3539 const SMDS_MeshElement* f = fIt->next();
3540 if ( !smDS->Contains( f ))
3542 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3543 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3545 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3546 nodes[iN] = ( n == srcNode ? tgtNode : n );
3548 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3552 // find out if a FACE is concave
3553 const bool isConcaveFace = isConcave( F, helper );
3555 // Create _SmoothNode's on face F
3556 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3558 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3559 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3561 const SMDS_MeshNode* n = smoothNodes[i];
3562 nodesToSmooth[ i ]._node = n;
3563 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3564 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3565 // fix up incorrect uv of nodes on the FACE
3566 helper.GetNodeUV( F, n, 0, &isOkUV);
3571 //if ( nodesToSmooth.empty() ) continue;
3573 // Find EDGE's to shrink
3574 set< _Shrinker1D* > eShri1D;
3576 for ( unsigned i = 0; i < lEdges.size(); ++i )
3578 _LayerEdge* edge = lEdges[i];
3579 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3581 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3582 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3583 eShri1D.insert( & srinker );
3584 srinker.AddEdge( edge, helper );
3585 // restore params of nodes on EGDE if the EDGE has been already
3586 // srinked while srinking another FACE
3587 srinker.RestoreParams();
3592 // ==================
3593 // Perform shrinking
3594 // ==================
3596 bool shrinked = true;
3597 int badNb, shriStep=0, smooStep=0;
3600 // Move boundary nodes (actually just set new UV)
3601 // -----------------------------------------------
3602 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3604 for ( unsigned i = 0; i < lEdges.size(); ++i )
3606 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3610 // Move nodes on EDGE's
3611 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3612 for ( ; shr != eShri1D.end(); ++shr )
3613 (*shr)->Compute( /*set3D=*/false, helper );
3616 // -----------------
3617 int nbNoImpSteps = 0;
3620 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3622 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3624 int oldBadNb = badNb;
3627 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3629 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3630 /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
3632 if ( badNb < oldBadNb )
3640 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3642 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3643 // First, find out a needed quality of smoothing (high for quadrangles only)
3646 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3647 if ( hasTria != hasQuad )
3649 highQuality = hasQuad;
3653 set<int> nbNodesSet;
3654 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3655 while ( fIt->more() && nbNodesSet.size() < 2 )
3656 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3657 highQuality = ( *nbNodesSet.begin() == 4 );
3660 if ( !highQuality && isConcaveFace )
3661 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3662 for ( int st = highQuality ? 10 : 3; st; --st )
3664 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3665 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3666 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3667 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3670 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3671 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3673 } // loop on FACES to srink mesh on
3676 // Replace source nodes by target nodes in shrinked mesh edges
3678 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3679 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3680 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3685 //================================================================================
3687 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3689 //================================================================================
3691 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3692 const TopoDS_Face& F,
3693 SMESH_MesherHelper& helper,
3694 const SMESHDS_SubMesh* faceSubMesh)
3696 const SMDS_MeshNode* srcNode = edge._nodes[0];
3697 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3701 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3703 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3704 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3705 gp_Vec2d uvDir( srcUV, tgtUV );
3706 double uvLen = uvDir.Magnitude();
3708 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3710 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3711 vector<const SMDS_MeshElement*> faces;
3712 multimap< double, const SMDS_MeshNode* > proj2node;
3713 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3714 while ( fIt->more() )
3716 const SMDS_MeshElement* f = fIt->next();
3717 if ( faceSubMesh->Contains( f ))
3718 faces.push_back( f );
3720 for ( unsigned i = 0; i < faces.size(); ++i )
3722 const int nbNodes = faces[i]->NbCornerNodes();
3723 for ( int j = 0; j < nbNodes; ++j )
3725 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3726 if ( n == srcNode ) continue;
3727 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3728 ( faces.size() > 1 || nbNodes > 3 ))
3730 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3731 gp_Vec2d uvDirN( srcUV, uv );
3732 double proj = uvDirN * uvDir;
3733 proj2node.insert( make_pair( proj, n ));
3737 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3738 const double minProj = p2n->first;
3739 const double projThreshold = 1.1 * uvLen;
3740 if ( minProj > projThreshold )
3742 // tgtNode is located so that it does not make faces with wrong orientation
3745 edge._pos.resize(1);
3746 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3748 // store most risky nodes in _simplices
3749 p2nEnd = proj2node.lower_bound( projThreshold );
3750 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3751 edge._simplices.resize( nbSimpl );
3752 for ( int i = 0; i < nbSimpl; ++i )
3754 edge._simplices[i]._nPrev = p2n->second;
3755 if ( ++p2n != p2nEnd )
3756 edge._simplices[i]._nNext = p2n->second;
3758 // set UV of source node to target node
3759 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3760 pos->SetUParameter( srcUV.X() );
3761 pos->SetVParameter( srcUV.Y() );
3763 else // _sWOL is TopAbs_EDGE
3765 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3766 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3767 if ( !edgeSM || edgeSM->NbElements() == 0 )
3768 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3770 const SMDS_MeshNode* n2 = 0;
3771 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3772 while ( eIt->more() && !n2 )
3774 const SMDS_MeshElement* e = eIt->next();
3775 if ( !edgeSM->Contains(e)) continue;
3776 n2 = e->GetNode( 0 );
3777 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3780 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3782 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3783 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3784 double u2 = helper.GetNodeU( E, n2, srcNode );
3786 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3788 // tgtNode is located so that it does not make faces with wrong orientation
3791 edge._pos.resize(1);
3792 edge._pos[0].SetCoord( U_TGT, uTgt );
3793 edge._pos[0].SetCoord( U_SRC, uSrc );
3794 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3796 edge._simplices.resize( 1 );
3797 edge._simplices[0]._nPrev = n2;
3799 // set UV of source node to target node
3800 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3801 pos->SetUParameter( uSrc );
3805 //================================================================================
3807 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3809 //================================================================================
3811 // Compute UV to follow during shrinking
3813 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3814 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3816 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3817 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3818 // gp_Vec2d uvDir( srcUV, tgtUV );
3819 // double uvLen = uvDir.Magnitude();
3822 // // Select shrinking step such that not to make faces with wrong orientation.
3823 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3824 // const double minStepSize = uvLen / 20;
3825 // double stepSize = uvLen;
3826 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3827 // while ( fIt->more() )
3829 // const SMDS_MeshElement* f = fIt->next();
3830 // if ( !faceSubMesh->Contains( f )) continue;
3831 // const int nbNodes = f->NbCornerNodes();
3832 // for ( int i = 0; i < nbNodes; ++i )
3834 // const SMDS_MeshNode* n = f->GetNode(i);
3835 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3837 // gp_XY uv = helper.GetNodeUV( F, n );
3838 // gp_Vec2d uvDirN( srcUV, uv );
3839 // double proj = uvDirN * uvDir;
3840 // if ( proj < stepSize && proj > minStepSize )
3846 // const int nbSteps = ceil( uvLen / stepSize );
3847 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3848 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3849 // edge._pos.resize( nbSteps );
3850 // edge._pos[0] = tgtUV0;
3851 // for ( int i = 1; i < nbSteps; ++i )
3853 // double r = i / double( nbSteps );
3854 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3859 //================================================================================
3861 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3863 //================================================================================
3865 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3867 SMESH::Controls::AspectRatio qualifier;
3868 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3869 const double maxAspectRatio = 4.;
3871 // find bad triangles
3873 vector< const SMDS_MeshElement* > badTrias;
3874 vector< double > badAspects;
3875 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3876 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3877 while ( fIt->more() )
3879 const SMDS_MeshElement * f = fIt->next();
3880 if ( f->NbCornerNodes() != 3 ) continue;
3881 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3882 double aspect = qualifier.GetValue( points );
3883 if ( aspect > maxAspectRatio )
3885 badTrias.push_back( f );
3886 badAspects.push_back( aspect );
3889 if ( badTrias.empty() )
3892 // find couples of faces to swap diagonal
3894 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3895 vector< T2Trias > triaCouples;
3897 TIDSortedElemSet involvedFaces, emptySet;
3898 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3901 double aspRatio [3];
3904 involvedFaces.insert( badTrias[iTia] );
3905 for ( int iP = 0; iP < 3; ++iP )
3906 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3908 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3909 int bestCouple = -1;
3910 for ( int iSide = 0; iSide < 3; ++iSide )
3912 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3913 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3914 trias [iSide].first = badTrias[iTia];
3915 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3917 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3920 // aspect ratio of an adjacent tria
3921 for ( int iP = 0; iP < 3; ++iP )
3922 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3923 double aspectInit = qualifier.GetValue( points2 );
3925 // arrange nodes as after diag-swaping
3926 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3927 i3 = helper.WrapIndex( i1-1, 3 );
3929 i3 = helper.WrapIndex( i1+1, 3 );
3931 points1( 1+ iSide ) = points2( 1+ i3 );
3932 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3934 // aspect ratio after diag-swaping
3935 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3936 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3939 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3943 if ( bestCouple >= 0 )
3945 triaCouples.push_back( trias[bestCouple] );
3946 involvedFaces.insert ( trias[bestCouple].second );
3950 involvedFaces.erase( badTrias[iTia] );
3953 if ( triaCouples.empty() )
3958 SMESH_MeshEditor editor( helper.GetMesh() );
3959 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3960 for ( size_t i = 0; i < triaCouples.size(); ++i )
3962 dumpChangeNodes( triaCouples[i].first );
3963 dumpChangeNodes( triaCouples[i].second );
3964 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
3968 // just for debug dump resulting triangles
3969 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
3970 for ( size_t i = 0; i < triaCouples.size(); ++i )
3972 dumpChangeNodes( triaCouples[i].first );
3973 dumpChangeNodes( triaCouples[i].second );
3977 //================================================================================
3979 * \brief Move target node to it's final position on the FACE during shrinking
3981 //================================================================================
3983 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3984 const TopoDS_Face& F,
3985 SMESH_MesherHelper& helper )
3988 return false; // already at the target position
3990 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3992 if ( _sWOL.ShapeType() == TopAbs_FACE )
3994 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
3995 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3996 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
3997 const double uvLen = tgtUV.Distance( curUV );
3999 // Select shrinking step such that not to make faces with wrong orientation.
4000 const double kSafe = 0.8;
4001 const double minStepSize = uvLen / 10;
4002 double stepSize = uvLen;
4003 for ( unsigned i = 0; i < _simplices.size(); ++i )
4005 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4006 for ( int j = 0; j < 2; ++j )
4007 if ( const SMDS_MeshNode* n = nn[j] )
4009 gp_XY uv = helper.GetNodeUV( F, n );
4010 gp_Vec2d uvDirN( curUV, uv );
4011 double proj = uvDirN * uvDir * kSafe;
4012 if ( proj < stepSize && proj > minStepSize )
4018 if ( stepSize == uvLen )
4025 newUV = curUV + uvDir.XY() * stepSize;
4028 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4029 pos->SetUParameter( newUV.X() );
4030 pos->SetVParameter( newUV.Y() );
4033 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4034 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4035 dumpMove( tgtNode );
4038 else // _sWOL is TopAbs_EDGE
4040 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4041 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4043 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4044 const double uSrc = _pos[0].Coord( U_SRC );
4045 const double lenTgt = _pos[0].Coord( LEN_TGT );
4047 double newU = _pos[0].Coord( U_TGT );
4048 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4054 newU = 0.1 * uSrc + 0.9 * u2;
4056 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4057 pos->SetUParameter( newU );
4059 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4060 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4061 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4062 dumpMove( tgtNode );
4068 //================================================================================
4070 * \brief Perform smooth on the FACE
4071 * \retval bool - true if the node has been moved
4073 //================================================================================
4075 bool _SmoothNode::Smooth(int& badNb,
4076 Handle(Geom_Surface)& surface,
4077 SMESH_MesherHelper& helper,
4078 const double refSign,
4082 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4084 // get uv of surrounding nodes
4085 vector<gp_XY> uv( _simplices.size() );
4086 for ( size_t i = 0; i < _simplices.size(); ++i )
4087 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4089 // compute new UV for the node
4091 if ( isCentroidal && _simplices.size() > 3 )
4093 // average centers of diagonals wieghted with their reciprocal lengths
4094 if ( _simplices.size() == 4 )
4096 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4097 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4098 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4102 double sumWeight = 0;
4103 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4104 for ( int i = 0; i < nb; ++i )
4107 int iTo = i + _simplices.size() - 1;
4108 for ( int j = iFrom; j < iTo; ++j )
4110 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4111 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4113 newPos += w * ( uv[i]+uv[i2] );
4116 newPos /= 2 * sumWeight;
4122 isCentroidal = false;
4123 for ( size_t i = 0; i < _simplices.size(); ++i )
4125 newPos /= _simplices.size();
4128 // count quality metrics (orientation) of triangles around the node
4130 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4131 for ( unsigned i = 0; i < _simplices.size(); ++i )
4132 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4135 for ( unsigned i = 0; i < _simplices.size(); ++i )
4136 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4138 if ( nbOkAfter < nbOkBefore )
4140 // if ( isCentroidal )
4141 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4142 badNb += _simplices.size() - nbOkBefore;
4146 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4147 pos->SetUParameter( newPos.X() );
4148 pos->SetVParameter( newPos.Y() );
4155 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4156 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4160 badNb += _simplices.size() - nbOkAfter;
4161 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4164 //================================================================================
4166 * \brief Delete _SolidData
4168 //================================================================================
4170 _SolidData::~_SolidData()
4172 for ( unsigned i = 0; i < _edges.size(); ++i )
4174 if ( _edges[i] && _edges[i]->_2neibors )
4175 delete _edges[i]->_2neibors;
4180 //================================================================================
4182 * \brief Add a _LayerEdge inflated along the EDGE
4184 //================================================================================
4186 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4189 if ( _nodes.empty() )
4191 _edges[0] = _edges[1] = 0;
4195 if ( e == _edges[0] || e == _edges[1] )
4197 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4198 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4199 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4200 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4203 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4205 BRep_Tool::Range( E, f,l );
4206 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4207 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4211 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4212 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4214 if ( _nodes.empty() )
4216 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4217 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4219 TopLoc_Location loc;
4220 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4221 GeomAdaptor_Curve aCurve(C, f,l);
4222 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4224 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
4225 _initU .reserve( nbExpectNodes );
4226 _normPar.reserve( nbExpectNodes );
4227 _nodes .reserve( nbExpectNodes );
4228 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4229 while ( nIt->more() )
4231 const SMDS_MeshNode* node = nIt->next();
4232 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4233 node == tgtNode0 || node == tgtNode1 )
4234 continue; // refinement nodes
4235 _nodes.push_back( node );
4236 _initU.push_back( helper.GetNodeU( E, node ));
4237 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4238 _normPar.push_back( len / totLen );
4243 // remove target node of the _LayerEdge from _nodes
4245 for ( unsigned i = 0; i < _nodes.size(); ++i )
4246 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4247 _nodes[i] = 0, nbFound++;
4248 if ( nbFound == _nodes.size() )
4253 //================================================================================
4255 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4257 //================================================================================
4259 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4261 if ( _done || _nodes.empty())
4263 const _LayerEdge* e = _edges[0];
4264 if ( !e ) e = _edges[1];
4267 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4268 ( !_edges[1] || _edges[1]->_pos.empty() ));
4270 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4272 if ( set3D || _done )
4274 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4275 GeomAdaptor_Curve aCurve(C, f,l);
4278 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4280 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4281 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4283 for ( unsigned i = 0; i < _nodes.size(); ++i )
4285 if ( !_nodes[i] ) continue;
4286 double len = totLen * _normPar[i];
4287 GCPnts_AbscissaPoint discret( aCurve, len, f );
4288 if ( !discret.IsDone() )
4289 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4290 double u = discret.Parameter();
4291 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4292 pos->SetUParameter( u );
4293 gp_Pnt p = C->Value( u );
4294 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4299 BRep_Tool::Range( E, f,l );
4301 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4303 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4305 for ( unsigned i = 0; i < _nodes.size(); ++i )
4307 if ( !_nodes[i] ) continue;
4308 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4309 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4310 pos->SetUParameter( u );
4315 //================================================================================
4317 * \brief Restore initial parameters of nodes on EDGE
4319 //================================================================================
4321 void _Shrinker1D::RestoreParams()
4324 for ( unsigned i = 0; i < _nodes.size(); ++i )
4326 if ( !_nodes[i] ) continue;
4327 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4328 pos->SetUParameter( _initU[i] );
4333 //================================================================================
4335 * \brief Replace source nodes by target nodes in shrinked mesh edges
4337 //================================================================================
4339 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4341 const SMDS_MeshNode* nodes[3];
4342 for ( int i = 0; i < 2; ++i )
4344 if ( !_edges[i] ) continue;
4346 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4347 if ( !eSubMesh ) return;
4348 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4349 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4350 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4351 while ( eIt->more() )
4353 const SMDS_MeshElement* e = eIt->next();
4354 if ( !eSubMesh->Contains( e ))
4356 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4357 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4359 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4360 nodes[iN] = ( n == srcNode ? tgtNode : n );
4362 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4367 //================================================================================
4369 * \brief Creates 2D and 1D elements on boundaries of new prisms
4371 //================================================================================
4373 bool _ViscousBuilder::addBoundaryElements()
4375 SMESH_MesherHelper helper( *_mesh );
4377 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4379 _SolidData& data = _sdVec[i];
4380 TopTools_IndexedMapOfShape geomEdges;
4381 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4382 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4384 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4386 // Get _LayerEdge's based on E
4388 map< double, const SMDS_MeshNode* > u2nodes;
4389 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4392 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4393 TNode2Edge & n2eMap = data._n2eMap;
4394 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4396 //check if 2D elements are needed on E
4397 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4398 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4399 ledges.push_back( n2e->second );
4401 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4402 continue; // no layers on E
4403 ledges.push_back( n2eMap[ u2n->second ]);
4405 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4406 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4407 int nbSharedPyram = 0;
4408 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4409 while ( vIt->more() )
4411 const SMDS_MeshElement* v = vIt->next();
4412 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4414 if ( nbSharedPyram > 1 )
4415 continue; // not free border of the pyramid
4417 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4418 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4419 continue; // faces already created
4421 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4422 ledges.push_back( n2eMap[ u2n->second ]);
4424 // Find out orientation and type of face to create
4426 bool reverse = false, isOnFace;
4428 map< TGeomID, TopoDS_Shape >::iterator e2f =
4429 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4431 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4433 F = e2f->second.Oriented( TopAbs_FORWARD );
4434 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4435 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4440 // find FACE with layers sharing E
4441 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4442 while ( fIt->more() && F.IsNull() )
4444 const TopoDS_Shape* pF = fIt->next();
4445 if ( helper.IsSubShape( *pF, data._solid) &&
4446 !_ignoreShapeIds.count( e2f->first ))
4450 // Find the sub-mesh to add new faces
4451 SMESHDS_SubMesh* sm = 0;
4453 sm = getMeshDS()->MeshElements( F );
4455 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4457 return error("error in addBoundaryElements()", data._index);
4460 const int dj1 = reverse ? 0 : 1;
4461 const int dj2 = reverse ? 1 : 0;
4462 for ( unsigned j = 1; j < ledges.size(); ++j )
4464 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4465 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4467 for ( unsigned z = 1; z < nn1.size(); ++z )
4468 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4470 for ( unsigned z = 1; z < nn1.size(); ++z )
4471 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));