1 // Copyright (C) 2007-2013 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_ViscousLayers2D.cxx
21 // Created : 23 Jul 2012
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers2D.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42 #include "SMESH_Quadtree.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include "utilities.h"
49 #include <BRepAdaptor_Curve.hxx>
50 #include <BRepAdaptor_Curve2d.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <Bnd_B3d.hxx>
55 #include <GCPnts_AbscissaPoint.hxx>
56 #include <Geom2dAdaptor_Curve.hxx>
57 #include <Geom2dInt_GInter.hxx>
58 #include <Geom2d_Circle.hxx>
59 #include <Geom2d_Line.hxx>
60 #include <Geom2d_TrimmedCurve.hxx>
61 #include <GeomAdaptor_Curve.hxx>
62 #include <Geom_Circle.hxx>
63 #include <Geom_Curve.hxx>
64 #include <Geom_Line.hxx>
65 #include <Geom_TrimmedCurve.hxx>
66 #include <IntRes2d_IntersectionPoint.hxx>
67 #include <Precision.hxx>
68 #include <Standard_ErrorHandler.hxx>
69 #include <TColStd_Array1OfReal.hxx>
71 #include <TopExp_Explorer.hxx>
72 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
73 #include <TopTools_IndexedMapOfShape.hxx>
74 #include <TopTools_ListIteratorOfListOfShape.hxx>
75 #include <TopTools_ListOfShape.hxx>
76 #include <TopTools_MapOfShape.hxx>
78 #include <TopoDS_Edge.hxx>
79 #include <TopoDS_Face.hxx>
80 #include <TopoDS_Vertex.hxx>
96 //================================================================================
101 //--------------------------------------------------------------------------------
103 * \brief Proxy Mesh of FACE with viscous layers. It's needed only to
104 * redefine newSubmesh().
106 struct _ProxyMeshOfFace : public SMESH_ProxyMesh
108 //---------------------------------------------------
109 // Proxy sub-mesh of an EDGE. It contains nodes in _uvPtStructVec.
110 struct _EdgeSubMesh : public SMESH_ProxyMesh::SubMesh
112 _EdgeSubMesh(int index=0): SubMesh(index) {}
113 //virtual int NbElements() const { return _elements.size()+1; }
114 virtual int NbNodes() const { return Max( 0, _uvPtStructVec.size()-2 ); }
115 void SetUVPtStructVec(UVPtStructVec& vec) { _uvPtStructVec.swap( vec ); }
117 _ProxyMeshOfFace(const SMESH_Mesh& mesh): SMESH_ProxyMesh(mesh) {}
118 _EdgeSubMesh* GetEdgeSubMesh(int ID) { return (_EdgeSubMesh*) getProxySubMesh(ID); }
119 virtual SubMesh* newSubmesh(int index=0) const { return new _EdgeSubMesh(index); }
121 //--------------------------------------------------------------------------------
123 * \brief SMESH_subMeshEventListener used to store _ProxyMeshOfFace, computed
124 * by _ViscousBuilder2D, in a SMESH_subMesh of the FACE.
125 * This is to delete _ProxyMeshOfFace when StdMeshers_ViscousLayers2D
126 * hypothesis is modified
128 struct _ProxyMeshHolder : public SMESH_subMeshEventListener
130 _ProxyMeshHolder( const TopoDS_Face& face,
131 SMESH_ProxyMesh::Ptr& mesh)
132 : SMESH_subMeshEventListener( /*deletable=*/true, Name() )
134 SMESH_subMesh* faceSM = mesh->GetMesh()->GetSubMesh( face );
135 faceSM->SetEventListener( this, new _Data( mesh ), faceSM );
137 // Finds a proxy mesh of face
138 static SMESH_ProxyMesh::Ptr FindProxyMeshOfFace( const TopoDS_Shape& face,
141 SMESH_ProxyMesh::Ptr proxy;
142 SMESH_subMesh* faceSM = mesh.GetSubMesh( face );
143 if ( EventListenerData* ld = faceSM->GetEventListenerData( Name() ))
144 proxy = static_cast< _Data* >( ld )->_mesh;
148 void ProcessEvent(const int event,
150 SMESH_subMesh* subMesh,
151 EventListenerData* data,
152 const SMESH_Hypothesis* /*hyp*/)
154 if ( event == SMESH_subMesh::CLEAN && eventType == SMESH_subMesh::COMPUTE_EVENT)
155 ((_Data*) data)->_mesh.reset();
158 // holder of a proxy mesh
159 struct _Data : public SMESH_subMeshEventListenerData
161 SMESH_ProxyMesh::Ptr _mesh;
162 _Data( SMESH_ProxyMesh::Ptr& mesh )
163 :SMESH_subMeshEventListenerData( /*isDeletable=*/true), _mesh( mesh )
166 // Returns identifier string
167 static const char* Name() { return "VISCOUS_2D::_ProxyMeshHolder"; }
171 //--------------------------------------------------------------------------------
173 * \brief Segment connecting inner ends of two _LayerEdge's.
177 const gp_XY* _uv[2]; // poiter to _LayerEdge::_uvIn
178 int _indexInLine; // position in _PolyLine
181 _Segment(const gp_XY& p1, const gp_XY& p2):_indexInLine(-1) { _uv[0] = &p1; _uv[1] = &p2; }
182 const gp_XY& p1() const { return *_uv[0]; }
183 const gp_XY& p2() const { return *_uv[1]; }
185 //--------------------------------------------------------------------------------
187 * \brief Tree of _Segment's used for a faster search of _Segment's.
189 struct _SegmentTree : public SMESH_Quadtree
191 typedef boost::shared_ptr< _SegmentTree > Ptr;
193 _SegmentTree( const vector< _Segment >& segments );
194 void GetSegmentsNear( const _Segment& seg, vector< const _Segment* >& found );
195 void GetSegmentsNear( const gp_Ax2d& ray, vector< const _Segment* >& found );
198 _SegmentTree* newChild() const { return new _SegmentTree; }
199 void buildChildrenData();
200 Bnd_B2d* buildRootBox();
202 static int maxNbSegInLeaf() { return 5; }
205 const _Segment* _seg;
207 void Set( const _Segment& seg )
210 _iMin[0] = ( seg._uv[1]->X() < seg._uv[0]->X() );
211 _iMin[1] = ( seg._uv[1]->Y() < seg._uv[0]->Y() );
213 bool IsOut( const _Segment& seg ) const;
214 bool IsOut( const gp_Ax2d& ray ) const;
216 vector< _SegBox > _segments;
218 //--------------------------------------------------------------------------------
220 * \brief Edge normal to FACE boundary, connecting a point on EDGE (_uvOut)
221 * and a point of a layer internal boundary (_uvIn)
225 gp_XY _uvOut; // UV on the FACE boundary
226 gp_XY _uvIn; // UV inside the FACE
227 double _length2D; // distance between _uvOut and _uvIn
229 bool _isBlocked;// is more inflation possible or not
231 gp_XY _normal2D; // to curve
232 double _len2dTo3dRatio; // to pass 2D <--> 3D
233 gp_Ax2d _ray; // a ray starting at _uvOut
235 vector<gp_XY> _uvRefined; // divisions by layers
237 bool SetNewLength( const double length );
243 //--------------------------------------------------------------------------------
245 * \brief Poly line composed of _Segment's of one EDGE.
246 * It's used to detect intersection of inflated layers by intersecting
251 StdMeshers_FaceSide* _wire;
252 int _edgeInd; // index of my EDGE in _wire
253 bool _advancable; // true if there is a viscous layer on my EDGE
254 bool _isStraight2D;// pcurve type
255 _PolyLine* _leftLine; // lines of neighbour EDGE's
256 _PolyLine* _rightLine;
257 int _firstPntInd; // index in vector<UVPtStruct> of _wire
260 vector< _LayerEdge > _lEdges; /* _lEdges[0] is usually is not treated
261 as it is equal to the last one of the _leftLine */
262 vector< _Segment > _segments; // segments connecting _uvIn's of _lEdges
263 _SegmentTree::Ptr _segTree;
265 vector< _PolyLine* > _reachableLines; // lines able to interfere with my layer
267 vector< const SMDS_MeshNode* > _leftNodes; // nodes built from a left VERTEX
268 vector< const SMDS_MeshNode* > _rightNodes; // nodes built from a right VERTEX
270 typedef vector< _Segment >::iterator TSegIterator;
271 typedef vector< _LayerEdge >::iterator TEdgeIterator;
273 TIDSortedElemSet _newFaces; // faces generated from this line
275 bool IsCommonEdgeShared( const _PolyLine& other );
276 size_t FirstLEdge() const
278 return ( _leftLine->_advancable && _lEdges.size() > 2 ) ? 1 : 0;
280 bool IsAdjacent( const _Segment& seg, const _LayerEdge* LE=0 ) const
282 if ( LE /*&& seg._indexInLine < _lEdges.size()*/ )
283 return ( seg._uv[0] == & LE->_uvIn ||
284 seg._uv[1] == & LE->_uvIn );
285 return ( & seg == &_leftLine->_segments.back() ||
286 & seg == &_rightLine->_segments[0] );
288 bool IsConcave() const;
290 //--------------------------------------------------------------------------------
292 * \brief Intersector of _Segment's
294 struct _SegmentIntersection
296 gp_XY _vec1, _vec2; // Vec( _seg.p1(), _seg.p2() )
297 gp_XY _vec21; // Vec( _seg2.p1(), _seg1.p1() )
298 double _D; // _vec1.Crossed( _vec2 )
299 double _param1, _param2; // intersection param on _seg1 and _seg2
301 bool Compute(const _Segment& seg1, const _Segment& seg2, bool seg2IsRay = false )
303 // !!! If seg2IsRay, returns true at any _param2 !!!
304 const double eps = 1e-10;
305 _vec1 = seg1.p2() - seg1.p1();
306 _vec2 = seg2.p2() - seg2.p1();
307 _vec21 = seg1.p1() - seg2.p1();
308 _D = _vec1.Crossed(_vec2);
309 if ( fabs(_D) < std::numeric_limits<double>::min())
311 _param1 = _vec2.Crossed(_vec21) / _D;
312 if (_param1 < -eps || _param1 > 1 + eps )
314 _param2 = _vec1.Crossed(_vec21) / _D;
315 return seg2IsRay || ( _param2 > -eps && _param2 < 1 + eps );
317 bool Compute( const _Segment& seg1, const gp_Ax2d& ray )
319 gp_XY segEnd = ray.Location().XY() + ray.Direction().XY();
320 _Segment seg2( ray.Location().XY(), segEnd );
321 return Compute( seg1, seg2, true );
323 //gp_XY GetPoint() { return _seg1.p1() + _param1 * _vec1; }
325 //--------------------------------------------------------------------------------
327 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
329 //--------------------------------------------------------------------------------
331 * \brief Builder of viscous layers
333 class _ViscousBuilder2D
336 _ViscousBuilder2D(SMESH_Mesh& theMesh,
337 const TopoDS_Face& theFace,
338 const StdMeshers_ViscousLayers2D* theHyp);
339 SMESH_ComputeErrorPtr GetError() const { return _error; }
341 SMESH_ProxyMesh::Ptr Compute(const TopoDS_Shape& theShapeHypAssignedTo);
345 bool findEdgesWithLayers(const TopoDS_Shape& theShapeHypAssignedTo);
346 bool makePolyLines();
348 bool fixCollisions();
352 bool toShrinkForAdjacent( const TopoDS_Face& adjFace,
353 const TopoDS_Edge& E,
354 const TopoDS_Vertex& V);
355 void setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut );
356 void setLayerEdgeData( _LayerEdge& lEdge,
358 Handle(Geom2d_Curve)& pcurve,
359 Handle(Geom_Curve)& curve,
362 GeomAPI_ProjectPointOnSurf* faceProj);
363 void adjustCommonEdge( _PolyLine& LL, _PolyLine& LR );
364 void calcLayersHeight(const double totalThick,
365 vector<double>& heights);
366 bool removeMeshFaces(const TopoDS_Shape& face);
368 bool error( const string& text );
369 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
370 _ProxyMeshOfFace* getProxyMesh();
373 //void makeGroupOfLE();
380 const StdMeshers_ViscousLayers2D* _hyp;
383 SMESH_ProxyMesh::Ptr _proxyMesh;
384 SMESH_ComputeErrorPtr _error;
387 Handle(Geom_Surface) _surface;
388 SMESH_MesherHelper _helper;
389 TSideVector _faceSideVec; // wires (StdMeshers_FaceSide) of _face
390 vector<_PolyLine> _polyLineVec; // fronts to advance
391 bool _is2DIsotropic; // is same U and V resoulution of _face
393 double _fPowN; // to compute thickness of layers
394 double _thickness; // required or possible layers thickness
396 // sub-shapes of _face
397 set<TGeomID> _ignoreShapeIds; // ids of EDGEs w/o layers
398 set<TGeomID> _noShrinkVert; // ids of VERTEXes that are extremities
399 // of EDGEs along which _LayerEdge can't be inflated because no viscous layers
400 // defined on neighbour FACEs sharing an EDGE. Nonetheless _LayerEdge's
401 // are inflated along such EDGEs but then such _LayerEdge's are turned into
402 // a node on VERTEX, i.e. all nodes on a _LayerEdge are melded into one node.
404 int _nbLE; // for DEBUG
407 //================================================================================
409 * \brief Returns StdMeshers_ViscousLayers2D for the FACE
411 const StdMeshers_ViscousLayers2D* findHyp(SMESH_Mesh& theMesh,
412 const TopoDS_Face& theFace,
413 TopoDS_Shape* assignedTo=0)
415 SMESH_HypoFilter hypFilter
416 ( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers2D::GetHypType() ));
417 const SMESH_Hypothesis * hyp =
418 theMesh.GetHypothesis( theFace, hypFilter, /*ancestors=*/true, assignedTo );
419 return dynamic_cast< const StdMeshers_ViscousLayers2D* > ( hyp );
422 //================================================================================
424 * \brief Returns ids of EDGEs not to create Viscous Layers on
425 * \param [in] theHyp - the hypothesis, holding edges either to ignore or not to.
426 * \param [in] theFace - the FACE whose EDGEs are checked.
427 * \param [in] theMesh - the mesh.
428 * \param [in,out] theEdgeIds - container returning EDGEs to ignore.
429 * \return int - number of found EDGEs of the FACE.
431 //================================================================================
433 int getEdgesToIgnore( const StdMeshers_ViscousLayers2D* theHyp,
434 const TopoDS_Shape& theFace,
435 const SMESHDS_Mesh* theMesh,
436 set< int > & theEdgeIds)
438 int nbToEdgesIgnore = 0;
439 vector<TGeomID> ids = theHyp->GetBndShapes();
440 if ( theHyp->IsToIgnoreShapes() ) // EDGEs to ignore are given
442 for ( size_t i = 0; i < ids.size(); ++i )
444 const TopoDS_Shape& E = theMesh->IndexToShape( ids[i] );
446 E.ShapeType() == TopAbs_EDGE &&
447 SMESH_MesherHelper::IsSubShape( E, theFace ))
449 theEdgeIds.insert( ids[i] );
454 else // EDGEs to make the Viscous Layers on are given
456 TopExp_Explorer E( theFace, TopAbs_EDGE );
457 for ( ; E.More(); E.Next(), ++nbToEdgesIgnore )
458 theEdgeIds.insert( theMesh->ShapeToIndex( E.Current() ));
460 for ( size_t i = 0; i < ids.size(); ++i )
461 nbToEdgesIgnore -= theEdgeIds.erase( ids[i] );
463 return nbToEdgesIgnore;
466 } // namespace VISCOUS_2D
468 //================================================================================
469 // StdMeshers_ViscousLayers hypothesis
471 StdMeshers_ViscousLayers2D::StdMeshers_ViscousLayers2D(int hypId, int studyId, SMESH_Gen* gen)
472 :StdMeshers_ViscousLayers(hypId, studyId, gen)
474 _name = StdMeshers_ViscousLayers2D::GetHypType();
475 _param_algo_dim = -2; // auxiliary hyp used by 2D algos
477 // --------------------------------------------------------------------------------
478 bool StdMeshers_ViscousLayers2D::SetParametersByMesh(const SMESH_Mesh* theMesh,
479 const TopoDS_Shape& theShape)
484 // --------------------------------------------------------------------------------
486 StdMeshers_ViscousLayers2D::Compute(SMESH_Mesh& theMesh,
487 const TopoDS_Face& theFace)
489 SMESH_ProxyMesh::Ptr pm;
491 TopoDS_Shape hypAssignedTo;
492 const StdMeshers_ViscousLayers2D* vlHyp = VISCOUS_2D::findHyp( theMesh, theFace, &hypAssignedTo );
495 VISCOUS_2D::_ViscousBuilder2D builder( theMesh, theFace, vlHyp );
496 pm = builder.Compute( hypAssignedTo );
497 SMESH_ComputeErrorPtr error = builder.GetError();
498 if ( error && !error->IsOK() )
499 theMesh.GetSubMesh( theFace )->GetComputeError() = error;
501 pm.reset( new SMESH_ProxyMesh( theMesh ));
502 if ( getenv("__ONLY__VL2D__"))
507 pm.reset( new SMESH_ProxyMesh( theMesh ));
511 // --------------------------------------------------------------------------------
512 void StdMeshers_ViscousLayers2D::RestoreListeners() const
514 StudyContextStruct* sc = _gen->GetStudyContext( _studyId );
515 std::map < int, SMESH_Mesh * >::iterator i_smesh = sc->mapMesh.begin();
516 for ( ; i_smesh != sc->mapMesh.end(); ++i_smesh )
518 SMESH_Mesh* smesh = i_smesh->second;
520 !smesh->HasShapeToMesh() ||
521 !smesh->GetMeshDS() ||
522 !smesh->GetMeshDS()->IsUsedHypothesis( this ))
525 // set event listeners to EDGE's of FACE where this hyp is used
526 TopoDS_Shape shape = i_smesh->second->GetShapeToMesh();
527 for ( TopExp_Explorer face( shape, TopAbs_FACE); face.More(); face.Next() )
528 if ( SMESH_Algo* algo = _gen->GetAlgo( *smesh, face.Current() ))
530 const std::list <const SMESHDS_Hypothesis *> & usedHyps =
531 algo->GetUsedHypothesis( *smesh, face.Current(), /*ignoreAuxiliary=*/false );
532 if ( std::find( usedHyps.begin(), usedHyps.end(), this ) != usedHyps.end() )
533 for ( TopExp_Explorer edge( face.Current(), TopAbs_EDGE); edge.More(); edge.Next() )
534 VISCOUS_3D::ToClearSubWithMain( smesh->GetSubMesh( edge.Current() ), face.Current() );
538 // END StdMeshers_ViscousLayers2D hypothesis
539 //================================================================================
541 using namespace VISCOUS_2D;
543 //================================================================================
545 * \brief Constructor of _ViscousBuilder2D
547 //================================================================================
549 _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh& theMesh,
550 const TopoDS_Face& theFace,
551 const StdMeshers_ViscousLayers2D* theHyp):
552 _mesh( &theMesh ), _face( theFace ), _hyp( theHyp ), _helper( theMesh )
554 _helper.SetSubShape( _face );
555 _helper.SetElementsOnShape( true );
557 _face.Orientation( TopAbs_FORWARD ); // 2D logic works only in this case
558 _surface = BRep_Tool::Surface( _face );
561 _fPowN = pow( _hyp->GetStretchFactor(), _hyp->GetNumberLayers() );
566 //================================================================================
568 * \brief Stores error description and returns false
570 //================================================================================
572 bool _ViscousBuilder2D::error(const string& text )
574 _error->myName = COMPERR_ALGO_FAILED;
575 _error->myComment = string("Viscous layers builder 2D: ") + text;
576 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( _face ) )
578 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
579 if ( smError && smError->myAlgo )
580 _error->myAlgo = smError->myAlgo;
584 cout << "_ViscousBuilder2D::error " << text << endl;
589 //================================================================================
591 * \brief Does its job
593 //================================================================================
595 SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute(const TopoDS_Shape& theShapeHypAssignedTo)
597 _error = SMESH_ComputeError::New(COMPERR_OK);
598 _faceSideVec = StdMeshers_FaceSide::GetFaceWires( _face, *_mesh, true, _error );
599 if ( !_error->IsOK() )
602 if ( !findEdgesWithLayers(theShapeHypAssignedTo) ) // analysis of a shape
605 if ( ! makePolyLines() ) // creation of fronts
608 if ( ! inflate() ) // advance fronts
611 // remove elements and nodes from _face
612 removeMeshFaces( _face );
614 if ( !shrink() ) // shrink segments on edges w/o layers
617 if ( ! refine() ) // make faces
625 //================================================================================
627 * \brief Finds EDGE's to make viscous layers on.
629 //================================================================================
631 bool _ViscousBuilder2D::findEdgesWithLayers(const TopoDS_Shape& theShapeHypAssignedTo)
633 // collect all EDGEs to ignore defined by hyp
634 int nbMyEdgesIgnored = getEdgesToIgnore( _hyp, _face, getMeshDS(), _ignoreShapeIds );
636 // check all EDGEs of the _face
637 int totalNbEdges = 0;
638 TopTools_IndexedDataMapOfShapeListOfShape facesOfEdgeMap;
639 TopExp::MapShapesAndAncestors( theShapeHypAssignedTo,
640 TopAbs_EDGE, TopAbs_FACE, facesOfEdgeMap);
641 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
643 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
644 totalNbEdges += wire->NbEdges();
645 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
647 const TopTools_ListOfShape& faceList = facesOfEdgeMap.FindFromKey( wire->Edge( iE ));
648 if ( faceList.Extent() > 1 )
650 // ignore internal EDGEs (shared by several FACEs)
651 const TGeomID edgeID = wire->EdgeID( iE );
652 _ignoreShapeIds.insert( edgeID );
654 // check if ends of an EDGE are to be added to _noShrinkVert
655 TopTools_ListIteratorOfListOfShape faceIt( faceList );
656 for ( ; faceIt.More(); faceIt.Next() )
658 const TopoDS_Shape& neighbourFace = faceIt.Value();
659 if ( neighbourFace.IsSame( _face )) continue;
660 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, neighbourFace );
661 if ( !algo ) continue;
663 const StdMeshers_ViscousLayers2D* viscHyp = 0;
664 const list <const SMESHDS_Hypothesis *> & allHyps =
665 algo->GetUsedHypothesis(*_mesh, neighbourFace, /*noAuxiliary=*/false);
666 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
667 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
668 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers2D*>( *hyp );
670 set<TGeomID> neighbourIgnoreEdges;
672 getEdgesToIgnore( viscHyp, neighbourFace, getMeshDS(), neighbourIgnoreEdges );
674 for ( int iV = 0; iV < 2; ++iV )
676 TopoDS_Vertex vertex = iV ? wire->LastVertex(iE) : wire->FirstVertex(iE);
678 _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
681 PShapeIteratorPtr edgeIt = _helper.GetAncestors( vertex, *_mesh, TopAbs_EDGE );
682 while ( const TopoDS_Shape* edge = edgeIt->next() )
683 if ( !edge->IsSame( wire->Edge( iE )) &&
684 _helper.IsSubShape( *edge, neighbourFace ) &&
685 neighbourIgnoreEdges.count( getMeshDS()->ShapeToIndex( *edge )))
687 _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
697 // add VERTEXes w/o layers to _ignoreShapeIds (this is used by toShrinkForAdjacent())
698 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
700 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
701 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
703 TGeomID edge1 = wire->EdgeID( iE );
704 TGeomID edge2 = wire->EdgeID( iE+1 );
705 if ( _ignoreShapeIds.count( edge1 ) && _ignoreShapeIds.count( edge2 ))
706 _ignoreShapeIds.insert( getMeshDS()->ShapeToIndex( wire->LastVertex( iE )));
710 return ( nbMyEdgesIgnored < totalNbEdges );
713 //================================================================================
715 * \brief Create the inner front of the viscous layers and prepare data for inflation
717 //================================================================================
719 bool _ViscousBuilder2D::makePolyLines()
721 // Create _PolyLines and _LayerEdge's
723 // count total nb of EDGEs to allocate _polyLineVec
725 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
727 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
728 nbEdges += wire->NbEdges();
729 if ( wire->GetUVPtStruct().empty() && wire->NbPoints() > 0 )
730 return error("Invalid node parameters on some EDGE");
732 _polyLineVec.resize( nbEdges );
734 // check if 2D normal should be computed by 3D one by means of projection
735 GeomAPI_ProjectPointOnSurf* faceProj = 0;
739 const UVPtStruct& uv = _faceSideVec[0]->GetUVPtStruct()[0];
740 gp_Pnt p = SMESH_TNodeXYZ( uv.node );
741 tmpLE._uvOut.SetCoord( uv.u, uv.v );
742 tmpLE._normal2D.SetCoord( 1., 0. );
743 setLenRatio( tmpLE, p );
744 const double r1 = tmpLE._len2dTo3dRatio;
745 tmpLE._normal2D.SetCoord( 0., 1. );
746 setLenRatio( tmpLE, p );
747 const double r2 = tmpLE._len2dTo3dRatio;
748 // projection is needed if two _len2dTo3dRatio's differ too much
749 const double maxR = Max( r2, r1 );
750 if ( Abs( r2-r1 )/maxR > 0.2*maxR )
751 faceProj = & _helper.GetProjector( _face, loc );
753 _is2DIsotropic = !faceProj;
755 // Assign data to _PolyLine's
756 // ---------------------------
759 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
761 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
762 const vector<UVPtStruct>& points = wire->GetUVPtStruct();
764 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
766 _PolyLine& L = _polyLineVec[ iPoLine++ ];
767 L._wire = wire.get();
769 L._advancable = !_ignoreShapeIds.count( wire->EdgeID( iE ));
771 int iRight = iPoLine - (( iE+1 < wire->NbEdges() ) ? 0 : wire->NbEdges() );
772 L._rightLine = &_polyLineVec[ iRight ];
773 _polyLineVec[ iRight ]._leftLine = &L;
775 L._firstPntInd = iPnt;
776 double lastNormPar = wire->LastParameter( iE ) - 1e-10;
777 while ( points[ iPnt ].normParam < lastNormPar )
779 L._lastPntInd = iPnt;
780 L._lEdges.resize( Max( 3, L._lastPntInd - L._firstPntInd + 1 )); // 3 edges minimum
782 // TODO: add more _LayerEdge's to strongly curved EDGEs
783 // in order not to miss collisions
786 Handle(Geom_Curve) curve = BRep_Tool::Curve( L._wire->Edge( iE ), loc, u, u );
787 Handle(Geom2d_Curve) pcurve = L._wire->Curve2d( L._edgeInd );
788 const bool reverse = (( L._wire->Edge( iE ).Orientation() == TopAbs_REVERSED ) ^
789 (_face.Orientation() == TopAbs_REVERSED ));
790 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
792 _LayerEdge& lEdge = L._lEdges[ i - L._firstPntInd ];
793 u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
794 p = SMESH_TNodeXYZ( points[ i ].node );
795 setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, faceProj );
796 setLenRatio( lEdge, p );
798 if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3-d _LayerEdge in the middle
800 L._lEdges[2] = L._lEdges[1];
801 u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
802 if ( !curve.IsNull() )
803 p = curve->Value( u );
805 p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
806 SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
807 setLayerEdgeData( L._lEdges[1], u, pcurve, curve, p, reverse, faceProj );
808 setLenRatio( L._lEdges[1], p );
813 // Fill _PolyLine's with _segments
814 // --------------------------------
816 double maxLen2dTo3dRatio = 0;
817 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
819 _PolyLine& L = _polyLineVec[ iPoLine ];
820 L._segments.resize( L._lEdges.size() - 1 );
821 for ( size_t i = 1; i < L._lEdges.size(); ++i )
823 _Segment & S = L._segments[i-1];
824 S._uv[0] = & L._lEdges[i-1]._uvIn;
825 S._uv[1] = & L._lEdges[i ]._uvIn;
826 S._indexInLine = i-1;
827 if ( maxLen2dTo3dRatio < L._lEdges[i]._len2dTo3dRatio )
828 maxLen2dTo3dRatio = L._lEdges[i]._len2dTo3dRatio;
830 // // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
831 // // becomes not connected to any segment
832 // if ( L._leftLine->_advancable )
833 // L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
835 L._segTree.reset( new _SegmentTree( L._segments ));
838 // Evaluate max possible _thickness if required layers thickness seems too high
839 // ----------------------------------------------------------------------------
841 _thickness = _hyp->GetTotalThickness();
842 _SegmentTree::box_type faceBndBox2D;
843 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
844 faceBndBox2D.Add( *_polyLineVec[ iPoLine]._segTree->getBox() );
845 double boxTol = 1e-3 * sqrt( faceBndBox2D.SquareExtent() );
847 if ( _thickness * maxLen2dTo3dRatio > sqrt( faceBndBox2D.SquareExtent() ) / 10 )
849 vector< const _Segment* > foundSegs;
850 double maxPossibleThick = 0;
851 _SegmentIntersection intersection;
852 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
854 _PolyLine& L1 = _polyLineVec[ iL1 ];
855 _SegmentTree::box_type boxL1 = * L1._segTree->getBox();
856 boxL1.Enlarge( boxTol );
857 // consider case of a circle as well!
858 for ( size_t iL2 = iL1; iL2 < _polyLineVec.size(); ++iL2 )
860 _PolyLine& L2 = _polyLineVec[ iL2 ];
861 _SegmentTree::box_type boxL2 = * L2._segTree->getBox();
862 boxL2.Enlarge( boxTol );
863 if ( boxL1.IsOut( boxL2 ))
865 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
868 L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
869 for ( size_t i = 0; i < foundSegs.size(); ++i )
870 if ( intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
872 double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
873 double psblThick = distToL2 / ( 1 + L1._advancable + L2._advancable );
874 maxPossibleThick = Max( psblThick, maxPossibleThick );
879 if ( maxPossibleThick > 0. )
880 _thickness = Min( _hyp->GetTotalThickness(), maxPossibleThick );
883 // Adjust _LayerEdge's at _PolyLine's extremities
884 // -----------------------------------------------
886 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
888 _PolyLine& LL = _polyLineVec[ iPoLine ];
889 _PolyLine& LR = *LL._rightLine;
890 adjustCommonEdge( LL, LR );
892 // recreate _segments if some _LayerEdge's have been removed by adjustCommonEdge()
893 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
895 _PolyLine& L = _polyLineVec[ iPoLine ];
896 // if ( L._segments.size() == L._lEdges.size() - 1 )
898 L._segments.resize( L._lEdges.size() - 1 );
899 for ( size_t i = 1; i < L._lEdges.size(); ++i )
901 _Segment & S = L._segments[i-1];
902 S._uv[0] = & L._lEdges[i-1]._uvIn;
903 S._uv[1] = & L._lEdges[i ]._uvIn;
904 S._indexInLine = i-1;
906 L._segTree.reset( new _SegmentTree( L._segments ));
908 // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
909 // becomes not connected to any segment
910 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
912 _PolyLine& L = _polyLineVec[ iPoLine ];
913 if ( L._leftLine->_advancable )
914 L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
917 // Fill _reachableLines.
918 // ----------------------
920 // compute bnd boxes taking into account the layers total thickness
921 vector< _SegmentTree::box_type > lineBoxes( _polyLineVec.size() );
922 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
924 lineBoxes[ iPoLine ] = *_polyLineVec[ iPoLine ]._segTree->getBox();
925 lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * _thickness *
926 ( _polyLineVec[ iPoLine ]._advancable ? 2. : 1.2 ));
929 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
931 _PolyLine& L1 = _polyLineVec[ iPoLine ];
932 for ( size_t iL2 = 0; iL2 < _polyLineVec.size(); ++iL2 )
934 _PolyLine& L2 = _polyLineVec[ iL2 ];
935 if ( iPoLine == iL2 || lineBoxes[ iPoLine ].IsOut( lineBoxes[ iL2 ]))
937 if ( !L1._advancable && ( L1._leftLine == &L2 || L1._rightLine == &L2 ))
939 // check reachability by _LayerEdge's
940 int iDelta = 1; //Max( 1, L1._lEdges.size() / 100 );
941 for ( size_t iLE = 1; iLE < L1._lEdges.size(); iLE += iDelta )
943 _LayerEdge& LE = L1._lEdges[iLE];
944 if ( !lineBoxes[ iL2 ].IsOut ( LE._uvOut,
945 LE._uvOut + LE._normal2D *_thickness * LE._len2dTo3dRatio ))
947 L1._reachableLines.push_back( & L2 );
952 // add self to _reachableLines
953 Geom2dAdaptor_Curve pcurve( L1._wire->Curve2d( L1._edgeInd ));
954 L1._isStraight2D = ( pcurve.GetType() == GeomAbs_Line );
955 if ( !L1._isStraight2D )
957 // TODO: check carefully
958 L1._reachableLines.push_back( & L1 );
965 //================================================================================
967 * \brief adjust common _LayerEdge of two adjacent _PolyLine's
968 * \param LL - left _PolyLine
969 * \param LR - right _PolyLine
971 //================================================================================
973 void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
975 int nbAdvancableL = LL._advancable + LR._advancable;
976 if ( nbAdvancableL == 0 )
979 _LayerEdge& EL = LL._lEdges.back();
980 _LayerEdge& ER = LR._lEdges.front();
981 gp_XY normL = EL._normal2D;
982 gp_XY normR = ER._normal2D;
983 gp_XY tangL ( normL.Y(), -normL.X() );
985 // set common direction to a VERTEX _LayerEdge shared by two _PolyLine's
986 gp_XY normCommon = ( normL * int( LL._advancable ) +
987 normR * int( LR._advancable )).Normalized();
988 EL._normal2D = normCommon;
989 EL._ray.SetLocation ( EL._uvOut );
990 EL._ray.SetDirection( EL._normal2D );
991 if ( nbAdvancableL == 1 ) { // _normal2D is true normal (not average)
992 EL._isBlocked = true; // prevent intersecting with _Segments of _advancable line
995 // update _LayerEdge::_len2dTo3dRatio according to a new direction
996 const vector<UVPtStruct>& points = LL._wire->GetUVPtStruct();
997 setLenRatio( EL, SMESH_TNodeXYZ( points[ LL._lastPntInd ].node ));
1001 const double dotNormTang = normR * tangL;
1002 const bool largeAngle = Abs( dotNormTang ) > 0.2;
1003 if ( largeAngle ) // not 180 degrees
1005 // recompute _len2dTo3dRatio to take into account angle between EDGEs
1006 gp_Vec2d oldNorm( LL._advancable ? normL : normR );
1007 double angleFactor = 1. / Max( 0.3, Cos( oldNorm.Angle( normCommon )));
1008 EL._len2dTo3dRatio *= angleFactor;
1009 ER._len2dTo3dRatio = EL._len2dTo3dRatio;
1011 gp_XY normAvg = ( normL + normR ).Normalized(); // average normal at VERTEX
1013 if ( dotNormTang < 0. ) // ---------------------------- CONVEX ANGLE
1015 // Remove _LayerEdge's intersecting the normAvg to avoid collisions
1016 // during inflate().
1018 // find max length of the VERTEX based _LayerEdge whose direction is normAvg
1019 double maxLen2D = _thickness * EL._len2dTo3dRatio;
1020 const gp_XY& pCommOut = ER._uvOut;
1021 gp_XY pCommIn = pCommOut + normAvg * maxLen2D;
1022 _Segment segCommon( pCommOut, pCommIn );
1023 _SegmentIntersection intersection;
1024 vector< const _Segment* > foundSegs;
1025 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1027 _PolyLine& L1 = _polyLineVec[ iL1 ];
1028 const _SegmentTree::box_type* boxL1 = L1._segTree->getBox();
1029 if ( boxL1->IsOut ( pCommOut, pCommIn ))
1031 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1034 L1._segTree->GetSegmentsNear( segCommon, foundSegs );
1035 for ( size_t i = 0; i < foundSegs.size(); ++i )
1036 if ( intersection.Compute( *foundSegs[i], segCommon ) &&
1037 intersection._param2 > 1e-10 )
1039 double len2D = intersection._param2 * maxLen2D / ( 2 + L1._advancable );
1040 if ( len2D < maxLen2D ) {
1042 pCommIn = pCommOut + normAvg * maxLen2D; // here length of segCommon changes
1048 // remove _LayerEdge's intersecting segCommon
1049 for ( int isR = 0; isR < 2; ++isR ) // loop on [ LL, LR ]
1051 _PolyLine& L = isR ? LR : LL;
1052 _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1053 int dIt = isR ? +1 : -1;
1054 if ( nbAdvancableL == 1 && L._advancable && normL * normR > -0.01 )
1055 continue; // obtuse internal angle
1056 // at least 3 _LayerEdge's should remain in a _PolyLine
1057 if ( L._lEdges.size() < 4 ) continue;
1059 _SegmentIntersection lastIntersection;
1060 for ( ; iLE < L._lEdges.size(); ++iLE, eIt += dIt )
1062 gp_XY uvIn = eIt->_uvOut + eIt->_normal2D * _thickness * eIt->_len2dTo3dRatio;
1063 _Segment segOfEdge( eIt->_uvOut, uvIn );
1064 if ( !intersection.Compute( segCommon, segOfEdge ))
1066 lastIntersection._param1 = intersection._param1;
1067 lastIntersection._param2 = intersection._param2;
1069 if ( iLE >= L._lEdges.size() - 1 )
1071 // all _LayerEdge's intersect the segCommon, limit inflation
1072 // of remaining 3 _LayerEdge's
1073 vector< _LayerEdge > newEdgeVec( Min( 3, L._lEdges.size() ));
1074 newEdgeVec.front() = L._lEdges.front();
1075 newEdgeVec.back() = L._lEdges.back();
1076 if ( newEdgeVec.size() == 3 )
1078 newEdgeVec[1] = L._lEdges[ isR ? (L._lEdges.size() - 2) : 1 ];
1079 newEdgeVec[1]._len2dTo3dRatio *= lastIntersection._param2;
1081 L._lEdges.swap( newEdgeVec );
1082 if ( !isR ) std::swap( lastIntersection._param1 , lastIntersection._param2 );
1083 L._lEdges.front()._len2dTo3dRatio *= lastIntersection._param1; // ??
1084 L._lEdges.back ()._len2dTo3dRatio *= lastIntersection._param2;
1086 else if ( iLE != 1 )
1088 // eIt points to the _LayerEdge not intersecting with segCommon
1090 LR._lEdges.erase( LR._lEdges.begin()+1, eIt );
1092 LL._lEdges.erase( eIt, --LL._lEdges.end() );
1093 // eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1094 // for ( size_t i = 1; i < iLE; ++i, eIt += dIt )
1095 // eIt->_isBlocked = true;
1099 else // ------------------------------------------ CONCAVE ANGLE
1101 if ( nbAdvancableL == 1 )
1103 // make that the _LayerEdge at VERTEX is not shared by LL and LR:
1104 // different normals is a sign that they are not shared
1105 _LayerEdge& notSharedEdge = LL._advancable ? LR._lEdges[0] : LL._lEdges.back();
1106 _LayerEdge& sharedEdge = LR._advancable ? LR._lEdges[0] : LL._lEdges.back();
1108 notSharedEdge._normal2D.SetCoord( 0.,0. );
1109 sharedEdge._normal2D = normAvg;
1110 sharedEdge._isBlocked = false;
1111 notSharedEdge._isBlocked = true;
1117 //================================================================================
1119 * \brief initialize data of a _LayerEdge
1121 //================================================================================
1123 void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge& lEdge,
1125 Handle(Geom2d_Curve)& pcurve,
1126 Handle(Geom_Curve)& curve,
1129 GeomAPI_ProjectPointOnSurf* faceProj)
1132 if ( faceProj && !curve.IsNull() )
1134 uv = pcurve->Value( u );
1135 gp_Vec tangent; gp_Pnt p; gp_Vec du, dv;
1136 curve->D1( u, p, tangent );
1139 _surface->D1( uv.X(), uv.Y(), p, du, dv );
1140 gp_Vec faceNorm = du ^ dv;
1141 gp_Vec normal = faceNorm ^ tangent;
1143 p = pOut.XYZ() + normal.XYZ() * /*1e-2 * */_hyp->GetTotalThickness() / _hyp->GetNumberLayers();
1144 faceProj->Perform( p );
1145 if ( !faceProj->IsDone() || faceProj->NbPoints() < 1 )
1146 return setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, NULL );
1147 Quantity_Parameter U,V;
1148 faceProj->LowerDistanceParameters(U,V);
1149 lEdge._normal2D.SetCoord( U - uv.X(), V - uv.Y() );
1150 lEdge._normal2D.Normalize();
1155 pcurve->D1( u, uv, tangent );
1156 tangent.Normalize();
1159 lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
1161 lEdge._uvOut = lEdge._uvIn = uv.XY();
1162 lEdge._ray.SetLocation ( lEdge._uvOut );
1163 lEdge._ray.SetDirection( lEdge._normal2D );
1164 lEdge._isBlocked = false;
1165 lEdge._length2D = 0;
1167 lEdge._ID = _nbLE++;
1171 //================================================================================
1173 * \brief Compute and set _LayerEdge::_len2dTo3dRatio
1175 //================================================================================
1177 void _ViscousBuilder2D::setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut )
1179 const double probeLen2d = 1e-3;
1181 gp_Pnt2d p2d = LE._uvOut + LE._normal2D * probeLen2d;
1182 gp_Pnt p3d = _surface->Value( p2d.X(), p2d.Y() );
1183 double len3d = p3d.Distance( pOut );
1184 if ( len3d < std::numeric_limits<double>::min() )
1185 LE._len2dTo3dRatio = std::numeric_limits<double>::min();
1187 LE._len2dTo3dRatio = probeLen2d / len3d;
1190 //================================================================================
1192 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1194 //================================================================================
1196 bool _ViscousBuilder2D::inflate()
1198 // Limit size of inflation step by geometry size found by
1199 // itersecting _LayerEdge's with _Segment's
1200 double minSize = _thickness, maxSize = 0;
1201 vector< const _Segment* > foundSegs;
1202 _SegmentIntersection intersection;
1203 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1205 _PolyLine& L1 = _polyLineVec[ iL1 ];
1206 for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1208 _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1209 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1212 L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1213 for ( size_t i = 0; i < foundSegs.size(); ++i )
1214 if ( ! L1.IsAdjacent( *foundSegs[i], & L1._lEdges[iLE] ) &&
1215 intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1217 double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1218 double size = distToL2 / ( 1 + L1._advancable + L2._advancable );
1219 if ( 1e-10 < size && size < minSize )
1221 if ( size > maxSize )
1227 if ( minSize > maxSize ) // no collisions possible
1228 maxSize = _thickness;
1230 cout << "-- minSize = " << minSize << ", maxSize = " << maxSize << endl;
1233 double curThick = 0, stepSize = minSize;
1235 if ( maxSize > _thickness )
1236 maxSize = _thickness;
1237 while ( curThick < maxSize )
1239 curThick += stepSize * 1.25;
1240 if ( curThick > _thickness )
1241 curThick = _thickness;
1243 // Elongate _LayerEdge's
1244 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1246 _PolyLine& L = _polyLineVec[ iL ];
1247 if ( !L._advancable ) continue;
1248 bool lenChange = false;
1249 for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1250 lenChange |= L._lEdges[iLE].SetNewLength( curThick );
1251 // for ( int k=0; k<L._segments.size(); ++k)
1252 // cout << "( " << L._segments[k].p1().X() << ", " <<L._segments[k].p1().Y() << " ) "
1253 // << "( " << L._segments[k].p2().X() << ", " <<L._segments[k].p2().Y() << " ) "
1256 L._segTree.reset( new _SegmentTree( L._segments ));
1259 // Avoid intersection of _Segment's
1260 bool allBlocked = fixCollisions();
1263 break; // no more inflating possible
1265 stepSize = Max( stepSize , _thickness / 10. );
1269 // if (nbSteps == 0 )
1270 // return error("failed at the very first inflation step");
1273 // remove _LayerEdge's of one line intersecting with each other
1274 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1276 _PolyLine& L = _polyLineVec[ iL ];
1277 if ( !L._advancable ) continue;
1279 // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
1280 if ( /*!L._leftLine->_advancable &&*/ L.IsCommonEdgeShared( *L._leftLine ) ) {
1281 L._lEdges[0] = L._leftLine->_lEdges.back();
1283 if ( !L._rightLine->_advancable && L.IsCommonEdgeShared( *L._rightLine ) ) {
1284 L._lEdges.back() = L._rightLine->_lEdges[0];
1287 _SegmentIntersection intersection;
1288 for ( int isR = 0; ( isR < 2 && L._lEdges.size() > 2 ); ++isR )
1290 int nbRemove = 0, deltaIt = isR ? -1 : +1;
1291 _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.end()-1 : L._lEdges.begin();
1292 if ( eIt->_length2D == 0 ) continue;
1293 _Segment seg1( eIt->_uvOut, eIt->_uvIn );
1294 for ( eIt += deltaIt; nbRemove < L._lEdges.size()-1; eIt += deltaIt )
1296 _Segment seg2( eIt->_uvOut, eIt->_uvIn );
1297 if ( !intersection.Compute( seg1, seg2 ))
1301 if ( nbRemove > 0 ) {
1302 if ( nbRemove == L._lEdges.size()-1 ) // 1st and last _LayerEdge's intersect
1305 _LayerEdge& L0 = L._lEdges.front();
1306 _LayerEdge& L1 = L._lEdges.back();
1307 L0._length2D *= intersection._param1 * 0.5;
1308 L1._length2D *= intersection._param2 * 0.5;
1309 L0._uvIn = L0._uvOut + L0._normal2D * L0._length2D;
1310 L1._uvIn = L1._uvOut + L1._normal2D * L1._length2D;
1311 if ( L.IsCommonEdgeShared( *L._leftLine ))
1312 L._leftLine->_lEdges.back() = L0;
1315 L._lEdges.erase( L._lEdges.end()-nbRemove-1,
1316 L._lEdges.end()-nbRemove );
1318 L._lEdges.erase( L._lEdges.begin()+1,
1319 L._lEdges.begin()+1+nbRemove );
1326 //================================================================================
1328 * \brief Remove intersection of _PolyLine's
1330 //================================================================================
1332 bool _ViscousBuilder2D::fixCollisions()
1334 // look for intersections of _Segment's by intersecting _LayerEdge's with
1336 vector< const _Segment* > foundSegs;
1337 _SegmentIntersection intersection;
1339 list< pair< _LayerEdge*, double > > edgeLenLimitList;
1340 list< _LayerEdge* > blockedEdgesList;
1342 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1344 _PolyLine& L1 = _polyLineVec[ iL1 ];
1345 //if ( !L1._advancable ) continue;
1346 for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1348 _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1349 for ( size_t iLE = L1.FirstLEdge(); iLE < L1._lEdges.size(); ++iLE )
1351 _LayerEdge& LE1 = L1._lEdges[iLE];
1352 if ( LE1._isBlocked ) continue;
1354 L2._segTree->GetSegmentsNear( LE1._ray, foundSegs );
1355 for ( size_t i = 0; i < foundSegs.size(); ++i )
1357 if ( ! L1.IsAdjacent( *foundSegs[i], &LE1 ) &&
1358 intersection.Compute( *foundSegs[i], LE1._ray ))
1360 const double dist2DToL2 = intersection._param2;
1361 double newLen2D = dist2DToL2 / 2;
1362 if ( newLen2D < 1.1 * LE1._length2D ) // collision!
1364 if ( newLen2D > 0 || !L1._advancable )
1366 blockedEdgesList.push_back( &LE1 );
1367 if ( L1._advancable && newLen2D > 0 )
1369 edgeLenLimitList.push_back( make_pair( &LE1, newLen2D ));
1370 blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine ]);
1371 blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine + 1 ]);
1373 else // here dist2DToL2 < 0 and LE1._length2D == 0
1375 _LayerEdge* LE2[2] = { & L2._lEdges[ foundSegs[i]->_indexInLine ],
1376 & L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
1377 _Segment outSeg2( LE2[0]->_uvOut, LE2[1]->_uvOut );
1378 intersection.Compute( outSeg2, LE1._ray );
1379 newLen2D = intersection._param2 / 2;
1382 edgeLenLimitList.push_back( make_pair( LE2[0], newLen2D ));
1383 edgeLenLimitList.push_back( make_pair( LE2[1], newLen2D ));
1394 // limit length of _LayerEdge's that are extrema of _PolyLine's
1395 // to avoid intersection of these _LayerEdge's
1396 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1398 _PolyLine& L = _polyLineVec[ iL1 ];
1399 if ( L._lEdges.size() < 4 ) // all intermediate _LayerEdge's intersect with extremum ones
1401 _LayerEdge& LEL = L._leftLine->_lEdges.back();
1402 _LayerEdge& LER = L._lEdges.back();
1403 _Segment segL( LEL._uvOut, LEL._uvIn );
1404 _Segment segR( LER._uvOut, LER._uvIn );
1405 double newLen2DL, newLen2DR;
1406 if ( intersection.Compute( segL, LER._ray ))
1408 newLen2DR = intersection._param2 / 2;
1409 newLen2DL = LEL._length2D * intersection._param1 / 2;
1411 else if ( intersection.Compute( segR, LEL._ray ))
1413 newLen2DL = intersection._param2 / 2;
1414 newLen2DR = LER._length2D * intersection._param1 / 2;
1420 if ( newLen2DL > 0 && newLen2DR > 0 )
1422 if ( newLen2DL < 1.1 * LEL._length2D )
1423 edgeLenLimitList.push_back( make_pair( &LEL, newLen2DL ));
1424 if ( newLen2DR < 1.1 * LER._length2D )
1425 edgeLenLimitList.push_back( make_pair( &LER, newLen2DR ));
1430 // set limited length to _LayerEdge's
1431 list< pair< _LayerEdge*, double > >::iterator edge2Len = edgeLenLimitList.begin();
1432 for ( ; edge2Len != edgeLenLimitList.end(); ++edge2Len )
1434 _LayerEdge* LE = edge2Len->first;
1435 if ( LE->_length2D > edge2Len->second )
1437 LE->_isBlocked = false;
1438 LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
1440 LE->_isBlocked = true;
1443 // block inflation of _LayerEdge's
1444 list< _LayerEdge* >::iterator edge = blockedEdgesList.begin();
1445 for ( ; edge != blockedEdgesList.end(); ++edge )
1446 (*edge)->_isBlocked = true;
1448 // find a not blocked _LayerEdge
1449 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1451 _PolyLine& L = _polyLineVec[ iL ];
1452 if ( !L._advancable ) continue;
1453 for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1454 if ( !L._lEdges[ iLE ]._isBlocked )
1461 //================================================================================
1463 * \brief Create new edges and shrink edges existing on a non-advancable _PolyLine
1464 * adjacent to an advancable one.
1466 //================================================================================
1468 bool _ViscousBuilder2D::shrink()
1470 gp_Pnt2d uv; //gp_Vec2d tangent;
1471 _SegmentIntersection intersection;
1474 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1476 _PolyLine& L = _polyLineVec[ iL1 ]; // line with no layers
1477 if ( L._advancable )
1479 const int nbAdvancable = ( L._rightLine->_advancable + L._leftLine->_advancable );
1480 if ( nbAdvancable == 0 )
1483 const TopoDS_Edge& E = L._wire->Edge ( L._edgeInd );
1484 const int edgeID = L._wire->EdgeID ( L._edgeInd );
1485 const double edgeLen = L._wire->EdgeLength( L._edgeInd );
1486 Handle(Geom2d_Curve) pcurve = L._wire->Curve2d ( L._edgeInd );
1487 const bool edgeReversed = ( E.Orientation() == TopAbs_REVERSED );
1489 SMESH_MesherHelper helper( *_mesh ); // to create nodes and edges on E
1490 helper.SetSubShape( E );
1491 helper.SetElementsOnShape( true );
1493 // Check a FACE adjacent to _face by E
1494 bool existingNodesFound = false;
1495 TopoDS_Face adjFace;
1496 PShapeIteratorPtr faceIt = _helper.GetAncestors( E, *_mesh, TopAbs_FACE );
1497 while ( const TopoDS_Shape* f = faceIt->next() )
1498 if ( !_face.IsSame( *f ))
1500 adjFace = TopoDS::Face( *f );
1501 SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( adjFace, *_mesh );
1502 if ( !pm || pm->NbProxySubMeshes() == 0 )
1504 // There are no viscous layers on an adjacent FACE, clear it's 2D mesh
1505 removeMeshFaces( adjFace );
1509 // There are viscous layers on the adjacent FACE; shrink must be already done;
1513 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1514 int iPFrom = L._firstPntInd, iPTo = L._lastPntInd;
1515 if ( L._leftLine->_advancable )
1517 vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1518 for ( int i = 0; i < _hyp->GetNumberLayers(); ++i ) {
1519 const UVPtStruct& uvPt = points[ iPFrom + i + 1 ];
1520 L._leftNodes.push_back( uvPt.node );
1521 uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1524 if ( L._rightLine->_advancable )
1526 vector<gp_XY>& uvVec = L._lEdges.back()._uvRefined;
1527 for ( int i = 0; i < _hyp->GetNumberLayers(); ++i ) {
1528 const UVPtStruct& uvPt = points[ iPTo - i - 1 ];
1529 L._rightNodes.push_back( uvPt.node );
1530 uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1533 // make proxy sub-mesh data of present nodes
1535 if ( L._leftLine->_advancable ) iPFrom += _hyp->GetNumberLayers();
1536 if ( L._rightLine->_advancable ) iPTo -= _hyp->GetNumberLayers();
1537 UVPtStructVec nodeDataVec( & points[ iPFrom ], & points[ iPTo + 1 ]);
1539 double normSize = nodeDataVec.back().normParam - nodeDataVec.front().normParam;
1540 for ( int iP = nodeDataVec.size()-1; iP >= 0 ; --iP )
1541 nodeDataVec[iP].normParam =
1542 ( nodeDataVec[iP].normParam - nodeDataVec[0].normParam ) / normSize;
1544 const SMDS_MeshNode* n = nodeDataVec.front().node;
1545 if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1546 nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
1547 n = nodeDataVec.back().node;
1548 if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1549 nodeDataVec.back().param = L._wire->LastU( L._edgeInd );
1551 _ProxyMeshOfFace::_EdgeSubMesh* myEdgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
1552 myEdgeSM->SetUVPtStructVec( nodeDataVec );
1554 existingNodesFound = true;
1556 } // loop on FACEs sharing E
1558 if ( existingNodesFound )
1559 continue; // nothing more to do in this case
1561 double u1 = L._wire->FirstU( L._edgeInd ), uf = u1;
1562 double u2 = L._wire->LastU ( L._edgeInd ), ul = u2;
1564 // a ratio to pass 2D <--> 1D
1565 const double len1D = 1e-3;
1566 const double len2D = pcurve->Value(uf).Distance( pcurve->Value(uf+len1D));
1567 double len1dTo2dRatio = len1D / len2D;
1569 // create a vector of proxy nodes
1570 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1571 UVPtStructVec nodeDataVec( & points[ L._firstPntInd ],
1572 & points[ L._lastPntInd + 1 ]);
1573 nodeDataVec.front().param = u1; // U on vertex is correct on only one of shared edges
1574 nodeDataVec.back ().param = u2;
1575 nodeDataVec.front().normParam = 0;
1576 nodeDataVec.back ().normParam = 1;
1578 // Get length of existing segments (from an edge start to a node) and their nodes
1579 vector< double > segLengths( nodeDataVec.size() - 1 );
1580 BRepAdaptor_Curve curve( E );
1581 for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
1583 const double len = GCPnts_AbscissaPoint::Length( curve, uf, nodeDataVec[iP].param );
1584 segLengths[ iP-1 ] = len;
1587 // Move first and last parameters on EDGE (U of n1) according to layers' thickness
1588 // and create nodes of layers on EDGE ( -x-x-x )
1592 // x-----x-----x-----x-----
1597 // x-x-x-x-----x-----x----
1600 int isRShrinkedForAdjacent;
1601 UVPtStructVec nodeDataForAdjacent;
1602 for ( int isR = 0; isR < 2; ++isR )
1604 _PolyLine* L2 = isR ? L._rightLine : L._leftLine; // line with layers
1605 if ( !L2->_advancable &&
1606 !toShrinkForAdjacent( adjFace, E, L._wire->FirstVertex( L._edgeInd + isR )))
1609 double & u = isR ? u2 : u1; // param to move
1610 double u0 = isR ? ul : uf; // init value of the param to move
1611 int iPEnd = isR ? nodeDataVec.size() - 1 : 0;
1613 _LayerEdge& nearLE = isR ? L._lEdges.back() : L._lEdges.front();
1614 _LayerEdge& farLE = isR ? L._lEdges.front() : L._lEdges.back();
1616 // try to find length of advancement along L by intersecting L with
1617 // an adjacent _Segment of L2
1619 double& length2D = nearLE._length2D;
1620 double length1D = 0;
1621 sign = ( isR ^ edgeReversed ) ? -1. : 1.;
1623 bool isConvex = false;
1624 if ( L2->_advancable )
1626 const uvPtStruct& tang2P1 = points[ isR ? L2->_firstPntInd : L2->_lastPntInd ];
1627 const uvPtStruct& tang2P2 = points[ isR ? L2->_firstPntInd+1 : L2->_lastPntInd-1 ];
1628 gp_XY seg2Dir( tang2P2.u - tang2P1.u,
1629 tang2P2.v - tang2P1.v );
1630 int iFSeg2 = isR ? 0 : L2->_segments.size() - 1;
1631 int iLSeg2 = isR ? 1 : L2->_segments.size() - 2;
1632 gp_XY uvLSeg2In = L2->_lEdges[ iLSeg2 ]._uvIn;
1633 Handle(Geom2d_Line) seg2Line = new Geom2d_Line( uvLSeg2In, seg2Dir );
1635 Geom2dAdaptor_Curve edgeCurve( pcurve, Min( uf, ul ), Max( uf, ul ));
1636 Geom2dAdaptor_Curve seg2Curve( seg2Line );
1637 Geom2dInt_GInter curveInt( edgeCurve, seg2Curve, 1e-7, 1e-7 );
1638 isConvex = ( curveInt.IsDone() && !curveInt.IsEmpty() );
1641 length1D = Abs( u - curveInt.Point( 1 ).ParamOnFirst() );
1642 double maxDist2d = 2 * L2->_lEdges[ iLSeg2 ]._length2D;
1643 isConvex = ( length1D < maxDist2d * len1dTo2dRatio );
1650 if ( !isConvex ) { /* concave VERTEX */ /* o-----o---
1656 length2D = L2->_lEdges[ iFSeg2 ]._length2D;
1657 //if ( L2->_advancable ) continue;
1660 else // L2 is advancable but in the face adjacent by L
1662 length2D = farLE._length2D;
1663 if ( length2D == 0 ) {
1664 _LayerEdge& neighborLE =
1665 ( isR ? L._leftLine->_lEdges.back() : L._rightLine->_lEdges.front() );
1666 length2D = neighborLE._length2D;
1667 if ( length2D == 0 )
1668 length2D = _thickness * nearLE._len2dTo3dRatio;
1672 // move u to the internal boundary of layers
1674 // x-x-x-x-----x-----x----
1675 double maxLen3D = Min( _thickness, edgeLen / ( 1 + nbAdvancable ));
1676 double maxLen2D = maxLen3D * nearLE._len2dTo3dRatio;
1677 if ( !length2D ) length2D = length1D / len1dTo2dRatio;
1678 if ( Abs( length2D ) > maxLen2D )
1679 length2D = maxLen2D;
1680 nearLE._uvIn = nearLE._uvOut + nearLE._normal2D * length2D;
1682 u += length2D * len1dTo2dRatio * sign;
1683 nodeDataVec[ iPEnd ].param = u;
1685 gp_Pnt2d newUV = pcurve->Value( u );
1686 nodeDataVec[ iPEnd ].u = newUV.X();
1687 nodeDataVec[ iPEnd ].v = newUV.Y();
1689 // compute params of layers on L
1690 vector<double> heights;
1691 calcLayersHeight( u - u0, heights );
1693 vector< double > params( heights.size() );
1694 for ( size_t i = 0; i < params.size(); ++i )
1695 params[ i ] = u0 + heights[ i ];
1697 // create nodes of layers and edges between them
1699 vector< const SMDS_MeshNode* >& layersNode = isR ? L._rightNodes : L._leftNodes;
1700 vector<gp_XY>& nodeUV = ( isR ? L._lEdges.back() : L._lEdges[0] )._uvRefined;
1701 nodeUV.resize ( _hyp->GetNumberLayers() );
1702 layersNode.resize( _hyp->GetNumberLayers() );
1703 const SMDS_MeshNode* vertexNode = nodeDataVec[ iPEnd ].node;
1704 const SMDS_MeshNode * prevNode = vertexNode;
1705 for ( size_t i = 0; i < params.size(); ++i )
1707 gp_Pnt p = curve.Value( params[i] );
1708 layersNode[ i ] = helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, params[i] );
1709 nodeUV [ i ] = pcurve->Value( params[i] ).XY();
1710 helper.AddEdge( prevNode, layersNode[ i ] );
1711 prevNode = layersNode[ i ];
1714 // store data of layer nodes made for adjacent FACE
1715 if ( !L2->_advancable )
1717 isRShrinkedForAdjacent = isR;
1718 nodeDataForAdjacent.resize( _hyp->GetNumberLayers() );
1720 size_t iFrw = 0, iRev = nodeDataForAdjacent.size()-1, *i = isR ? &iRev : &iFrw;
1721 nodeDataForAdjacent[ *i ] = points[ isR ? L._lastPntInd : L._firstPntInd ];
1722 nodeDataForAdjacent[ *i ].param = u0;
1723 nodeDataForAdjacent[ *i ].normParam = isR;
1724 for ( ++iFrw, --iRev; iFrw < layersNode.size(); ++iFrw, --iRev )
1726 nodeDataForAdjacent[ *i ].node = layersNode[ iFrw - 1 ];
1727 nodeDataForAdjacent[ *i ].u = nodeUV [ iFrw - 1 ].X();
1728 nodeDataForAdjacent[ *i ].v = nodeUV [ iFrw - 1 ].Y();
1729 nodeDataForAdjacent[ *i ].param = params [ iFrw - 1 ];
1732 // replace a node on vertex by a node of last (most internal) layer
1733 // in a segment on E
1734 SMDS_ElemIteratorPtr segIt = vertexNode->GetInverseElementIterator( SMDSAbs_Edge );
1735 const SMDS_MeshNode* segNodes[3];
1736 while ( segIt->more() )
1738 const SMDS_MeshElement* segment = segIt->next();
1739 if ( segment->getshapeId() != edgeID ) continue;
1741 const int nbNodes = segment->NbNodes();
1742 for ( int i = 0; i < nbNodes; ++i )
1744 const SMDS_MeshNode* n = segment->GetNode( i );
1745 segNodes[ i ] = ( n == vertexNode ? layersNode.back() : n );
1747 getMeshDS()->ChangeElementNodes( segment, segNodes, nbNodes );
1750 nodeDataVec[ iPEnd ].node = layersNode.back();
1752 } // loop on the extremities of L
1754 // Shrink edges to fit in between the layers at EDGE ends
1756 double newLength = GCPnts_AbscissaPoint::Length( curve, u1, u2 );
1757 double lenRatio = newLength / edgeLen * ( edgeReversed ? -1. : 1. );
1758 for ( size_t iP = 1; iP < nodeDataVec.size()-1; ++iP )
1760 const SMDS_MeshNode* oldNode = nodeDataVec[iP].node;
1762 GCPnts_AbscissaPoint discret( curve, segLengths[iP-1] * lenRatio, u1 );
1763 if ( !discret.IsDone() )
1764 throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
1766 nodeDataVec[iP].param = discret.Parameter();
1767 if ( oldNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1768 throw SALOME_Exception(SMESH_Comment("ViscousBuilder2D: not SMDS_TOP_EDGE node position: ")
1769 << oldNode->GetPosition()->GetTypeOfPosition()
1770 << " of node " << oldNode->GetID());
1771 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( oldNode->GetPosition() );
1772 pos->SetUParameter( nodeDataVec[iP].param );
1774 gp_Pnt newP = curve.Value( nodeDataVec[iP].param );
1775 getMeshDS()->MoveNode( oldNode, newP.X(), newP.Y(), newP.Z() );
1777 gp_Pnt2d newUV = pcurve->Value( nodeDataVec[iP].param ).XY();
1778 nodeDataVec[iP].u = newUV.X();
1779 nodeDataVec[iP].v = newUV.Y();
1780 nodeDataVec[iP].normParam = segLengths[iP-1] / edgeLen;
1781 // nodeDataVec[iP].x = segLengths[iP-1] / edgeLen;
1782 // nodeDataVec[iP].y = segLengths[iP-1] / edgeLen;
1785 // Add nodeDataForAdjacent to nodeDataVec
1787 if ( !nodeDataForAdjacent.empty() )
1789 const double par1 = isRShrinkedForAdjacent ? u2 : uf;
1790 const double par2 = isRShrinkedForAdjacent ? ul : u1;
1791 const double shrinkLen = GCPnts_AbscissaPoint::Length( curve, par1, par2 );
1793 // compute new normParam for nodeDataVec
1794 for ( size_t iP = 0; iP < nodeDataVec.size()-1; ++iP )
1795 nodeDataVec[iP+1].normParam = segLengths[iP] / ( edgeLen + shrinkLen );
1796 double normDelta = 1 - nodeDataVec.back().normParam;
1797 if ( !isRShrinkedForAdjacent )
1798 for ( size_t iP = 0; iP < nodeDataVec.size(); ++iP )
1799 nodeDataVec[iP].normParam += normDelta;
1801 // compute new normParam for nodeDataForAdjacent
1802 const double deltaR = isRShrinkedForAdjacent ? nodeDataVec.back().normParam : 0;
1803 for ( size_t iP = !isRShrinkedForAdjacent; iP < nodeDataForAdjacent.size(); ++iP )
1805 double lenFromPar1 =
1806 GCPnts_AbscissaPoint::Length( curve, par1, nodeDataForAdjacent[iP].param );
1807 nodeDataForAdjacent[iP].normParam = deltaR + normDelta * lenFromPar1 / shrinkLen;
1809 // concatenate nodeDataVec and nodeDataForAdjacent
1810 nodeDataVec.insert(( isRShrinkedForAdjacent ? nodeDataVec.end() : nodeDataVec.begin() ),
1811 nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
1814 // Extend nodeDataVec by a node located at the end of not shared _LayerEdge
1815 /* n - to add to nodeDataVec
1824 for ( int isR = 0; isR < 2; ++isR )
1826 _PolyLine& L2 = *( isR ? L._rightLine : L._leftLine ); // line with layers
1827 if ( ! L2._advancable || L.IsCommonEdgeShared( L2 ) )
1829 vector< const SMDS_MeshNode* >& layerNodes2 = isR ? L2._leftNodes : L2._rightNodes;
1830 _LayerEdge& LE2 = isR ? L2._lEdges.front() : L2._lEdges.back();
1831 if ( layerNodes2.empty() )
1833 // refine the not shared _LayerEdge
1834 vector<double> layersHeight;
1835 calcLayersHeight( LE2._length2D, layersHeight );
1837 vector<gp_XY>& nodeUV2 = LE2._uvRefined;
1838 nodeUV2.resize ( _hyp->GetNumberLayers() );
1839 layerNodes2.resize( _hyp->GetNumberLayers() );
1840 for ( size_t i = 0; i < layersHeight.size(); ++i )
1842 gp_XY uv = LE2._uvOut + LE2._normal2D * layersHeight[i];
1843 gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
1845 layerNodes2[ i ] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
1848 UVPtStruct ptOfNode;
1849 ptOfNode.u = LE2._uvRefined.back().X();
1850 ptOfNode.v = LE2._uvRefined.back().Y();
1851 ptOfNode.node = layerNodes2.back();
1852 ptOfNode.param = isR ? ul : uf;
1853 ptOfNode.normParam = isR ? 1 : 0;
1855 nodeDataVec.insert(( isR ? nodeDataVec.end() : nodeDataVec.begin() ), ptOfNode );
1857 // recompute normParam of nodes in nodeDataVec
1858 newLength = GCPnts_AbscissaPoint::Length( curve,
1859 nodeDataVec.front().param,
1860 nodeDataVec.back().param);
1861 for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
1863 const double len = GCPnts_AbscissaPoint::Length( curve,
1864 nodeDataVec.front().param,
1865 nodeDataVec[iP].param );
1866 nodeDataVec[iP].normParam = len / newLength;
1870 // create a proxy sub-mesh containing the moved nodes
1871 _ProxyMeshOfFace::_EdgeSubMesh* edgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
1872 edgeSM->SetUVPtStructVec( nodeDataVec );
1874 // set a sub-mesh event listener to remove just created edges when
1875 // "ViscousLayers2D" hypothesis is modified
1876 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( E ), _face );
1878 } // loop on _polyLineVec
1883 //================================================================================
1885 * \brief Returns true if there will be a shrinked mesh on EDGE E of FACE adjFace
1888 //================================================================================
1890 bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face& adjFace,
1891 const TopoDS_Edge& E,
1892 const TopoDS_Vertex& V)
1894 TopoDS_Shape hypAssignedTo;
1895 if ( const StdMeshers_ViscousLayers2D* vlHyp = findHyp( *_mesh, adjFace, &hypAssignedTo ))
1897 VISCOUS_2D::_ViscousBuilder2D builder( *_mesh, adjFace, vlHyp );
1898 builder._faceSideVec = StdMeshers_FaceSide::GetFaceWires( adjFace, *_mesh, true, _error );
1899 builder.findEdgesWithLayers( hypAssignedTo );
1901 PShapeIteratorPtr edgeIt = _helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
1902 while ( const TopoDS_Shape* edgeAtV = edgeIt->next() )
1904 if ( !edgeAtV->IsSame( E ) &&
1905 _helper.IsSubShape( *edgeAtV, adjFace ) &&
1906 !builder._ignoreShapeIds.count( getMeshDS()->ShapeToIndex( *edgeAtV )))
1915 //================================================================================
1919 //================================================================================
1921 bool _ViscousBuilder2D::refine()
1923 // find out orientation of faces to create
1925 ( _helper.GetSubShapeOri( _mesh->GetShapeToMesh(), _face ) == TopAbs_REVERSED );
1927 // store a proxyMesh in a sub-mesh
1928 // make faces on each _PolyLine
1929 vector< double > layersHeight;
1930 double prevLen2D = -1;
1931 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1933 _PolyLine& L = _polyLineVec[ iL ];
1934 if ( !L._advancable ) continue;
1936 // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
1937 size_t iLE = 0, nbLE = L._lEdges.size();
1938 const bool leftEdgeShared = L.IsCommonEdgeShared( *L._leftLine );
1939 const bool rightEdgeShared = L.IsCommonEdgeShared( *L._rightLine );
1940 if ( /*!L._leftLine->_advancable &&*/ leftEdgeShared )
1942 L._lEdges[0] = L._leftLine->_lEdges.back();
1943 iLE += int( !L._leftLine->_advancable );
1945 if ( !L._rightLine->_advancable && rightEdgeShared )
1947 L._lEdges.back() = L._rightLine->_lEdges[0];
1951 // limit length of neighbour _LayerEdge's to avoid sharp change of layers thickness
1952 vector< double > segLen( L._lEdges.size() );
1954 for ( size_t i = 1; i < segLen.size(); ++i )
1956 // accumulate length of segments
1957 double sLen = (L._lEdges[i-1]._uvOut - L._lEdges[i]._uvOut ).Modulus();
1958 segLen[i] = segLen[i-1] + sLen;
1960 for ( int isR = 0; isR < 2; ++isR )
1962 size_t iF = 0, iL = L._lEdges.size()-1;
1963 size_t *i = isR ? &iL : &iF;
1964 _LayerEdge* prevLE = & L._lEdges[ *i ];
1966 for ( ++iF, --iL; iF < L._lEdges.size()-1; ++iF, --iL )
1968 _LayerEdge& LE = L._lEdges[*i];
1969 if ( prevLE->_length2D > 0 )
1971 gp_XY tangent ( LE._normal2D.Y(), -LE._normal2D.X() );
1972 weight += Abs( tangent * ( prevLE->_uvIn - LE._uvIn )) / segLen.back();
1973 // gp_XY prevTang( LE._uvOut - prevLE->_uvOut );
1974 // gp_XY prevNorm( -prevTang.Y(), prevTang.X() );
1975 gp_XY prevNorm = LE._normal2D;
1976 double prevProj = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
1977 if ( prevProj > 0 ) {
1978 prevProj /= prevNorm.Modulus();
1979 if ( LE._length2D < prevProj )
1980 weight += 0.75 * ( 1 - weight ); // length decrease is more preferable
1981 LE._length2D = weight * LE._length2D + ( 1 - weight ) * prevProj;
1982 LE._uvIn = LE._uvOut + LE._normal2D * LE._length2D;
1988 // DEBUG: to see _uvRefined. cout can be redirected to hide NETGEN output
1989 // cerr << "import smesh" << endl << "mesh = smesh.Mesh()"<< endl;
1991 // calculate intermediate UV on _LayerEdge's ( _LayerEdge::_uvRefined )
1992 for ( ; iLE < nbLE; ++iLE )
1994 _LayerEdge& LE = L._lEdges[iLE];
1995 if ( fabs( LE._length2D - prevLen2D ) > LE._length2D / 100. )
1997 calcLayersHeight( LE._length2D, layersHeight );
1998 prevLen2D = LE._length2D;
2000 for ( size_t i = 0; i < layersHeight.size(); ++i )
2001 LE._uvRefined.push_back( LE._uvOut + LE._normal2D * layersHeight[i] );
2003 // DEBUG: to see _uvRefined
2004 // for ( size_t i = 0; i < LE._uvRefined.size(); ++i )
2006 // gp_XY uv = LE._uvRefined[i];
2007 // gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2008 // cerr << "mesh.AddNode( " << p.X() << ", " << p.Y() << ", " << p.Z() << " )" << endl;
2012 // nodes to create 1 layer of faces
2013 vector< const SMDS_MeshNode* > outerNodes( L._lastPntInd - L._firstPntInd + 1 );
2014 vector< const SMDS_MeshNode* > innerNodes( L._lastPntInd - L._firstPntInd + 1 );
2016 // initialize outerNodes by nodes of the L._wire
2017 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
2018 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2019 outerNodes[ i-L._firstPntInd ] = points[i].node;
2021 // compute normalized [0;1] node parameters of outerNodes
2022 vector< double > normPar( L._lastPntInd - L._firstPntInd + 1 );
2024 normF = L._wire->FirstParameter( L._edgeInd ),
2025 normL = L._wire->LastParameter ( L._edgeInd ),
2026 normDist = normL - normF;
2027 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2028 normPar[ i - L._firstPntInd ] = ( points[i].normParam - normF ) / normDist;
2030 // Create layers of faces
2032 bool hasLeftNode = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared );
2033 bool hasRightNode = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
2034 bool hasOwnLeftNode = ( !L._leftNodes.empty() );
2035 bool hasOwnRightNode = ( !L._rightNodes.empty() );
2036 bool isClosedEdge = ( outerNodes.front() == outerNodes.back() );
2038 iN0 = ( hasLeftNode || hasOwnLeftNode || isClosedEdge ),
2039 nbN = innerNodes.size() - ( hasRightNode || hasOwnRightNode );
2040 L._leftNodes .reserve( _hyp->GetNumberLayers() );
2041 L._rightNodes.reserve( _hyp->GetNumberLayers() );
2042 int cur = 0, prev = -1; // to take into account orientation of _face
2043 if ( isReverse ) std::swap( cur, prev );
2044 for ( int iF = 0; iF < _hyp->GetNumberLayers(); ++iF ) // loop on layers of faces
2046 // get accumulated length of intermediate segments
2047 if ( _is2DIsotropic )
2048 for ( iS = 1; iS < segLen.size(); ++iS )
2050 double sLen = (L._lEdges[iS-1]._uvRefined[iF] - L._lEdges[iS]._uvRefined[iF] ).Modulus();
2051 segLen[iS] = segLen[iS-1] + sLen;
2054 for ( iS = 1; iS < segLen.size(); ++iS )
2056 const gp_XY& uv1 = L._lEdges[iS-1]._uvRefined[iF];
2057 const gp_XY& uv2 = L._lEdges[iS ]._uvRefined[iF];
2058 gp_Pnt p1 = _surface->Value( uv1.X(), uv1.Y() );
2059 gp_Pnt p2 = _surface->Value( uv2.X(), uv2.Y() );
2060 double sLen = p1.Distance( p2 );
2061 segLen[iS] = segLen[iS-1] + sLen;
2063 // normalize the accumulated length
2064 for ( iS = 1; iS < segLen.size(); ++iS )
2065 segLen[iS] /= segLen.back();
2067 // create innerNodes of a current layer
2069 for ( size_t i = iN0; i < nbN; ++i )
2071 while ( normPar[i] > segLen[iS+1] )
2073 double r = ( normPar[i] - segLen[iS] ) / ( segLen[iS+1] - segLen[iS] );
2074 gp_XY uv = r * L._lEdges[iS+1]._uvRefined[iF] + (1-r) * L._lEdges[iS]._uvRefined[iF];
2075 gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2076 innerNodes[i] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2078 // use nodes created for adjacent _PolyLine's
2079 if ( hasOwnLeftNode ) innerNodes.front() = L._leftNodes [ iF ];
2080 else if ( hasLeftNode ) innerNodes.front() = L._leftLine->_rightNodes[ iF ];
2081 if ( hasOwnRightNode ) innerNodes.back() = L._rightNodes[ iF ];
2082 else if ( hasRightNode ) innerNodes.back() = L._rightLine->_leftNodes[ iF ];
2083 if ( isClosedEdge ) innerNodes.front() = innerNodes.back(); // circle
2084 if ( !hasOwnLeftNode ) L._leftNodes.push_back( innerNodes.front() );
2085 if ( !hasOwnRightNode ) L._rightNodes.push_back( innerNodes.back() );
2088 for ( size_t i = 1; i < innerNodes.size(); ++i )
2089 if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i+prev ], outerNodes[ i+cur ],
2090 innerNodes[ i+cur ], innerNodes[ i+prev ]))
2091 L._newFaces.insert( L._newFaces.end(), f );
2093 outerNodes.swap( innerNodes );
2095 // faces between not shared _LayerEdge's (at concave VERTEX)
2096 for ( int isR = 0; isR < 2; ++isR )
2098 if ( isR ? rightEdgeShared : leftEdgeShared )
2100 vector< const SMDS_MeshNode* > &
2101 lNodes = (isR ? L._rightNodes : L._leftLine->_rightNodes ),
2102 rNodes = (isR ? L._rightLine->_leftNodes : L._leftNodes );
2103 if ( lNodes.empty() || rNodes.empty() || lNodes.size() != rNodes.size() )
2106 for ( size_t i = 1; i < lNodes.size(); ++i )
2107 _helper.AddFace( lNodes[ i+prev ], rNodes[ i+prev ],
2108 rNodes[ i+cur ], lNodes[ i+cur ]);
2110 const UVPtStruct& ptOnVertex = points[ isR ? L._lastPntInd : L._firstPntInd ];
2112 _helper.AddFace( ptOnVertex.node, lNodes[ 0 ], rNodes[ 0 ]);
2114 _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
2117 // Fill the _ProxyMeshOfFace
2119 UVPtStructVec nodeDataVec( outerNodes.size() ); // outerNodes swapped with innerNodes
2120 for ( size_t i = 0; i < outerNodes.size(); ++i )
2122 gp_XY uv = _helper.GetNodeUV( _face, outerNodes[i] );
2123 nodeDataVec[i].u = uv.X();
2124 nodeDataVec[i].v = uv.Y();
2125 nodeDataVec[i].node = outerNodes[i];
2126 nodeDataVec[i].param = points [i + L._firstPntInd].param;
2127 nodeDataVec[i].normParam = normPar[i];
2128 nodeDataVec[i].x = normPar[i];
2129 nodeDataVec[i].y = normPar[i];
2131 nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
2132 nodeDataVec.back() .param = L._wire->LastU ( L._edgeInd );
2134 _ProxyMeshOfFace::_EdgeSubMesh* edgeSM
2135 = getProxyMesh()->GetEdgeSubMesh( L._wire->EdgeID( L._edgeInd ));
2136 edgeSM->SetUVPtStructVec( nodeDataVec );
2138 } // loop on _PolyLine's
2143 //================================================================================
2145 * \brief Improve quality of the created mesh elements
2147 //================================================================================
2149 bool _ViscousBuilder2D::improve()
2154 // fixed nodes on EDGE's
2155 std::set<const SMDS_MeshNode*> fixedNodes;
2156 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
2158 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
2159 const vector<UVPtStruct>& points = wire->GetUVPtStruct();
2160 for ( size_t i = 0; i < points.size(); ++i )
2161 fixedNodes.insert( fixedNodes.end(), points[i].node );
2163 // fixed proxy nodes
2164 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2166 _PolyLine& L = _polyLineVec[ iL ];
2167 const TopoDS_Edge& E = L._wire->Edge( L._edgeInd );
2168 if ( const SMESH_ProxyMesh::SubMesh* sm = _proxyMesh->GetProxySubMesh( E ))
2170 const UVPtStructVec& points = sm->GetUVPtStructVec();
2171 for ( size_t i = 0; i < points.size(); ++i )
2172 fixedNodes.insert( fixedNodes.end(), points[i].node );
2174 for ( size_t i = 0; i < L._rightNodes.size(); ++i )
2175 fixedNodes.insert( fixedNodes.end(), L._rightNodes[i] );
2179 SMESH_MeshEditor editor( _mesh );
2180 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2182 _PolyLine& L = _polyLineVec[ iL ];
2183 if ( L._isStraight2D ) continue;
2184 // SMESH_MeshEditor::SmoothMethod how =
2185 // L._isStraight2D ? SMESH_MeshEditor::LAPLACIAN : SMESH_MeshEditor::CENTROIDAL;
2186 //editor.Smooth( L._newFaces, fixedNodes, how, /*nbIt = */3 );
2187 //editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::LAPLACIAN, /*nbIt = */1 );
2188 editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::CENTROIDAL, /*nbIt = */3 );
2193 //================================================================================
2195 * \brief Remove elements and nodes from a face
2197 //================================================================================
2199 bool _ViscousBuilder2D::removeMeshFaces(const TopoDS_Shape& face)
2201 // we don't use SMESH_subMesh::ComputeStateEngine() because of a listener
2202 // which clears EDGEs together with _face.
2203 bool thereWereElems = false;
2204 SMESH_subMesh* sm = _mesh->GetSubMesh( face );
2205 if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2207 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2208 thereWereElems = eIt->more();
2209 while ( eIt->more() ) getMeshDS()->RemoveFreeElement( eIt->next(), smDS );
2210 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2211 while ( nIt->more() ) getMeshDS()->RemoveFreeNode( nIt->next(), smDS );
2213 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2215 return thereWereElems;
2218 //================================================================================
2220 * \brief Creates a _ProxyMeshOfFace and store it in a sub-mesh of FACE
2222 //================================================================================
2224 _ProxyMeshOfFace* _ViscousBuilder2D::getProxyMesh()
2226 if ( _proxyMesh.get() )
2227 return (_ProxyMeshOfFace*) _proxyMesh.get();
2229 _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *_mesh );
2230 _proxyMesh.reset( proxyMeshOfFace );
2231 new _ProxyMeshHolder( _face, _proxyMesh );
2233 return proxyMeshOfFace;
2236 //================================================================================
2238 * \brief Calculate height of layers for the given thickness. Height is measured
2239 * from the outer boundary
2241 //================================================================================
2243 void _ViscousBuilder2D::calcLayersHeight(const double totalThick,
2244 vector<double>& heights)
2246 heights.resize( _hyp->GetNumberLayers() );
2248 if ( _fPowN - 1 <= numeric_limits<double>::min() )
2249 h0 = totalThick / _hyp->GetNumberLayers();
2251 h0 = totalThick * ( _hyp->GetStretchFactor() - 1 )/( _fPowN - 1 );
2253 double hSum = 0, hi = h0;
2254 for ( int i = 0; i < _hyp->GetNumberLayers(); ++i )
2257 heights[ i ] = hSum;
2258 hi *= _hyp->GetStretchFactor();
2262 //================================================================================
2264 * \brief Elongate this _LayerEdge
2266 //================================================================================
2268 bool _LayerEdge::SetNewLength( const double length3D )
2270 if ( _isBlocked ) return false;
2272 //_uvInPrev = _uvIn;
2273 _length2D = length3D * _len2dTo3dRatio;
2274 _uvIn = _uvOut + _normal2D * _length2D;
2278 //================================================================================
2280 * \brief Return true if _LayerEdge at a common VERTEX between EDGEs with
2281 * and w/o layer is common to the both _PolyLine's. If this is true, nodes
2282 * of this _LayerEdge are inflated along a _PolyLine w/o layer, else the nodes
2283 * are inflated along _normal2D of _LayerEdge of EDGE with layer
2285 //================================================================================
2287 bool _PolyLine::IsCommonEdgeShared( const _PolyLine& other )
2289 const double tol = 1e-30;
2291 if ( & other == _leftLine )
2292 return _lEdges[0]._normal2D.IsEqual( _leftLine->_lEdges.back()._normal2D, tol );
2294 if ( & other == _rightLine )
2295 return _lEdges.back()._normal2D.IsEqual( _rightLine->_lEdges[0]._normal2D, tol );
2300 //================================================================================
2302 * \brief Return \c true if the EDGE of this _PolyLine is concave
2304 //================================================================================
2306 bool _PolyLine::IsConcave() const
2308 if ( _lEdges.size() < 2 )
2311 gp_Vec2d v1( _lEdges[0]._uvOut, _lEdges[1]._uvOut );
2312 gp_Vec2d v2( _lEdges[0]._uvOut, _lEdges[2]._uvOut );
2313 const double size2 = v2.Magnitude();
2315 return ( v1 ^ v2 ) / size2 < -1e-3 * size2;
2318 //================================================================================
2320 * \brief Constructor of SegmentTree
2322 //================================================================================
2324 _SegmentTree::_SegmentTree( const vector< _Segment >& segments ):
2327 _segments.resize( segments.size() );
2328 for ( size_t i = 0; i < segments.size(); ++i )
2329 _segments[i].Set( segments[i] );
2334 //================================================================================
2336 * \brief Return the maximal bnd box
2338 //================================================================================
2340 _SegmentTree::box_type* _SegmentTree::buildRootBox()
2342 _SegmentTree::box_type* box = new _SegmentTree::box_type;
2343 for ( size_t i = 0; i < _segments.size(); ++i )
2345 box->Add( *_segments[i]._seg->_uv[0] );
2346 box->Add( *_segments[i]._seg->_uv[1] );
2351 //================================================================================
2353 * \brief Redistrubute _segments among children
2355 //================================================================================
2357 void _SegmentTree::buildChildrenData()
2359 for ( int i = 0; i < _segments.size(); ++i )
2360 for (int j = 0; j < nbChildren(); j++)
2361 if ( !myChildren[j]->getBox()->IsOut( *_segments[i]._seg->_uv[0],
2362 *_segments[i]._seg->_uv[1] ))
2363 ((_SegmentTree*)myChildren[j])->_segments.push_back( _segments[i]);
2365 SMESHUtils::FreeVector( _segments ); // = _elements.clear() + free memory
2367 for (int j = 0; j < nbChildren(); j++)
2369 _SegmentTree* child = static_cast<_SegmentTree*>( myChildren[j]);
2370 child->myIsLeaf = ( child->_segments.size() <= maxNbSegInLeaf() );
2374 //================================================================================
2376 * \brief Return elements which can include the point
2378 //================================================================================
2380 void _SegmentTree::GetSegmentsNear( const _Segment& seg,
2381 vector< const _Segment* >& found )
2383 if ( getBox()->IsOut( *seg._uv[0], *seg._uv[1] ))
2388 for ( int i = 0; i < _segments.size(); ++i )
2389 if ( !_segments[i].IsOut( seg ))
2390 found.push_back( _segments[i]._seg );
2394 for (int i = 0; i < nbChildren(); i++)
2395 ((_SegmentTree*) myChildren[i])->GetSegmentsNear( seg, found );
2400 //================================================================================
2402 * \brief Return segments intersecting a ray
2404 //================================================================================
2406 void _SegmentTree::GetSegmentsNear( const gp_Ax2d& ray,
2407 vector< const _Segment* >& found )
2409 if ( getBox()->IsOut( ray ))
2414 for ( int i = 0; i < _segments.size(); ++i )
2415 if ( !_segments[i].IsOut( ray ))
2416 found.push_back( _segments[i]._seg );
2420 for (int i = 0; i < nbChildren(); i++)
2421 ((_SegmentTree*) myChildren[i])->GetSegmentsNear( ray, found );
2425 //================================================================================
2427 * \brief Classify a _Segment
2429 //================================================================================
2431 bool _SegmentTree::_SegBox::IsOut( const _Segment& seg ) const
2433 const double eps = std::numeric_limits<double>::min();
2434 for ( int iC = 0; iC < 2; ++iC )
2436 if ( seg._uv[0]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps &&
2437 seg._uv[1]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps )
2439 if ( seg._uv[0]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps &&
2440 seg._uv[1]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps )
2446 //================================================================================
2448 * \brief Classify a ray
2450 //================================================================================
2452 bool _SegmentTree::_SegBox::IsOut( const gp_Ax2d& ray ) const
2454 double distBoxCenter2Ray =
2455 ray.Direction().XY() ^ ( ray.Location().XY() - 0.5 * (*_seg->_uv[0] + *_seg->_uv[1]));
2457 double boxSectionDiam =
2458 Abs( ray.Direction().X() ) * ( _seg->_uv[1-_iMin[1]]->Y() - _seg->_uv[_iMin[1]]->Y() ) +
2459 Abs( ray.Direction().Y() ) * ( _seg->_uv[1-_iMin[0]]->X() - _seg->_uv[_iMin[0]]->X() );
2461 return Abs( distBoxCenter2Ray ) > 0.5 * boxSectionDiam;