1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : StdMeshers_Cartesian_3D.cxx
25 #include "StdMeshers_Cartesian_3D.hxx"
27 #include "SMDS_MeshNode.hxx"
28 #include "SMESH_Block.hxx"
29 #include "SMESH_Comment.hxx"
30 #include "SMESH_Mesh.hxx"
31 #include "SMESH_MesherHelper.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_subMeshEventListener.hxx"
34 #include "StdMeshers_CartesianParameters3D.hxx"
36 #include <utilities.h>
37 #include <Utils_ExceptHandlers.hxx>
38 #include <Basics_OCCTVersion.hxx>
40 #include <GEOMUtils.hxx>
42 #include <BRepAdaptor_Curve.hxx>
43 #include <BRepAdaptor_Surface.hxx>
44 #include <BRepBndLib.hxx>
45 #include <BRepBuilderAPI_Copy.hxx>
46 #include <BRepBuilderAPI_MakeFace.hxx>
47 #include <BRepTools.hxx>
48 #include <BRepTopAdaptor_FClass2d.hxx>
49 #include <BRep_Builder.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B3d.hxx>
52 #include <Bnd_Box.hxx>
54 #include <GCPnts_UniformDeflection.hxx>
55 #include <Geom2d_BSplineCurve.hxx>
56 #include <Geom2d_BezierCurve.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAPI_ProjectPointOnSurf.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_BSplineCurve.hxx>
61 #include <Geom_BSplineSurface.hxx>
62 #include <Geom_BezierCurve.hxx>
63 #include <Geom_BezierSurface.hxx>
64 #include <Geom_RectangularTrimmedSurface.hxx>
65 #include <Geom_TrimmedCurve.hxx>
66 #include <IntAna_IntConicQuad.hxx>
67 #include <IntAna_IntLinTorus.hxx>
68 #include <IntAna_Quadric.hxx>
69 #include <IntCurveSurface_TransitionOnCurve.hxx>
70 #include <IntCurvesFace_Intersector.hxx>
71 #include <Poly_Triangulation.hxx>
72 #include <Precision.hxx>
74 #include <TopExp_Explorer.hxx>
75 #include <TopLoc_Location.hxx>
76 #include <TopTools_MapOfShape.hxx>
78 #include <TopoDS_Compound.hxx>
79 #include <TopoDS_Face.hxx>
80 #include <TopoDS_TShape.hxx>
81 #include <gp_Cone.hxx>
82 #include <gp_Cylinder.hxx>
85 #include <gp_Pnt2d.hxx>
86 #include <gp_Sphere.hxx>
87 #include <gp_Torus.hxx>
93 #include <tbb/parallel_for.h>
94 //#include <tbb/enumerable_thread_specific.h>
103 #if OCC_VERSION_LARGE <= 0x06050300
104 // workaround is required only for OCCT6.5.3 and older (see OCC22809)
105 #define ELLIPSOLID_WORKAROUND
108 #ifdef ELLIPSOLID_WORKAROUND
109 #include <BRepIntCurveSurface_Inter.hxx>
110 #include <BRepTopAdaptor_TopolTool.hxx>
111 #include <BRepAdaptor_HSurface.hxx>
114 //=============================================================================
118 //=============================================================================
120 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, int studyId, SMESH_Gen * gen)
121 :SMESH_3D_Algo(hypId, studyId, gen)
123 _name = "Cartesian_3D";
124 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
125 _compatibleHypothesis.push_back("CartesianParameters3D");
127 _onlyUnaryInput = false; // to mesh all SOLIDs at once
128 _requireDiscreteBoundary = false; // 2D mesh not needed
129 _supportSubmeshes = false; // do not use any existing mesh
132 //=============================================================================
134 * Check presence of a hypothesis
136 //=============================================================================
138 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
139 const TopoDS_Shape& aShape,
140 Hypothesis_Status& aStatus)
142 aStatus = SMESH_Hypothesis::HYP_MISSING;
144 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
145 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
146 if ( h == hyps.end())
151 for ( ; h != hyps.end(); ++h )
153 if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
155 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
160 return aStatus == HYP_OK;
167 //=============================================================================
168 // Definitions of internal utils
169 // --------------------------------------------------------------------------
171 Trans_TANGENT = IntCurveSurface_Tangent,
172 Trans_IN = IntCurveSurface_In,
173 Trans_OUT = IntCurveSurface_Out,
176 // --------------------------------------------------------------------------
178 * \brief Common data of any intersection between a Grid and a shape
180 struct B_IntersectPoint
182 mutable const SMDS_MeshNode* _node;
183 mutable vector< TGeomID > _faceIDs;
185 B_IntersectPoint(): _node(NULL) {}
186 void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
187 int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
188 bool IsOnFace( int faceID ) const;
189 virtual ~B_IntersectPoint() {}
191 // --------------------------------------------------------------------------
193 * \brief Data of intersection between a GridLine and a TopoDS_Face
195 struct F_IntersectPoint : public B_IntersectPoint
198 mutable Transition _transition;
199 mutable size_t _indexOnLine;
201 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
203 // --------------------------------------------------------------------------
205 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
207 struct E_IntersectPoint : public B_IntersectPoint
213 // --------------------------------------------------------------------------
215 * \brief A line of the grid and its intersections with 2D geometry
220 double _length; // line length
221 multiset< F_IntersectPoint > _intPoints;
223 void RemoveExcessIntPoints( const double tol );
224 bool GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut );
226 // --------------------------------------------------------------------------
228 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
233 vector< gp_XYZ > _origins; // origin points of all planes in one direction
234 vector< double > _zProjs; // projections of origins to _zNorm
236 // --------------------------------------------------------------------------
238 * \brief Iterator on the parallel grid lines of one direction
244 size_t _iVar1, _iVar2, _iConst;
245 string _name1, _name2, _nameConst;
247 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
248 size_t iv1, size_t iv2, size_t iConst,
249 const string& nv1, const string& nv2, const string& nConst )
251 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
252 _curInd[0] = _curInd[1] = _curInd[2] = 0;
253 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
254 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
257 size_t I() const { return _curInd[0]; }
258 size_t J() const { return _curInd[1]; }
259 size_t K() const { return _curInd[2]; }
260 void SetIJK( size_t i, size_t j, size_t k )
262 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
266 if ( ++_curInd[_iVar1] == _size[_iVar1] )
267 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
269 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
270 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
271 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
272 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
273 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
274 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
275 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
277 // --------------------------------------------------------------------------
279 * \brief Container of GridLine's
283 vector< double > _coords[3]; // coordinates of grid nodes
284 gp_XYZ _axes [3]; // axis directions
285 vector< GridLine > _lines [3]; // in 3 directions
286 double _tol, _minCellSize;
288 gp_Mat _invB; // inverted basis of _axes
290 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
291 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
293 list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
294 TopTools_IndexedMapOfShape _shapes;
296 SMESH_MesherHelper* _helper;
298 size_t CellIndex( size_t i, size_t j, size_t k ) const
300 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
302 size_t NodeIndex( size_t i, size_t j, size_t k ) const
304 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
306 size_t NodeIndexDX() const { return 1; }
307 size_t NodeIndexDY() const { return _coords[0].size(); }
308 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
310 LineIndexer GetLineIndexer(size_t iDir) const;
312 void SetCoordinates(const vector<double>& xCoords,
313 const vector<double>& yCoords,
314 const vector<double>& zCoords,
315 const double* axesDirs,
316 const Bnd_Box& bndBox );
317 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
318 void ComputeNodes(SMESH_MesherHelper& helper);
320 #ifdef ELLIPSOLID_WORKAROUND
321 // --------------------------------------------------------------------------
323 * \brief struct temporary replacing IntCurvesFace_Intersector until
324 * OCCT bug 0022809 is fixed
325 * http://tracker.dev.opencascade.org/view.php?id=22809
327 struct TMP_IntCurvesFace_Intersector
329 BRepAdaptor_Surface _surf;
331 BRepIntCurveSurface_Inter _intcs;
332 vector<IntCurveSurface_IntersectionPoint> _points;
333 BRepTopAdaptor_TopolTool _clsf;
335 TMP_IntCurvesFace_Intersector(const TopoDS_Face& face, const double tol)
336 :_surf( face ), _tol( tol ), _clsf( new BRepAdaptor_HSurface(_surf) ) {}
337 Bnd_Box Bounding() const { Bnd_Box b; BRepBndLib::Add (_surf.Face(), b); return b; }
338 void Perform( const gp_Lin& line, const double w0, const double w1 )
341 for ( _intcs.Init( _surf.Face(), line, _tol ); _intcs.More(); _intcs.Next() )
342 if ( w0 <= _intcs.W() && _intcs.W() <= w1 )
343 _points.push_back( _intcs.Point() );
345 bool IsDone() const { return true; }
346 int NbPnt() const { return _points.size(); }
347 IntCurveSurface_TransitionOnCurve Transition( const int i ) const { return _points[ i-1 ].Transition(); }
348 double WParameter( const int i ) const { return _points[ i-1 ].W(); }
349 TopAbs_State ClassifyUVPoint(const gp_Pnt2d& p) { return _clsf.Classify( p, _tol ); }
351 #define __IntCurvesFace_Intersector TMP_IntCurvesFace_Intersector
353 #define __IntCurvesFace_Intersector IntCurvesFace_Intersector
355 // --------------------------------------------------------------------------
357 * \brief Intersector of TopoDS_Face with all GridLine's
359 struct FaceGridIntersector
365 __IntCurvesFace_Intersector* _surfaceInt;
366 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
368 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
371 void StoreIntersections()
373 for ( size_t i = 0; i < _intersections.size(); ++i )
375 multiset< F_IntersectPoint >::iterator ip =
376 _intersections[i].first->_intPoints.insert( _intersections[i].second );
377 ip->_faceIDs.reserve( 1 );
378 ip->_faceIDs.push_back( _faceID );
381 const Bnd_Box& GetFaceBndBox()
383 GetCurveFaceIntersector();
386 __IntCurvesFace_Intersector* GetCurveFaceIntersector()
390 _surfaceInt = new __IntCurvesFace_Intersector( _face, Precision::PConfusion() );
391 _bndBox = _surfaceInt->Bounding();
392 if ( _bndBox.IsVoid() )
393 BRepBndLib::Add (_face, _bndBox);
397 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
399 // --------------------------------------------------------------------------
401 * \brief Intersector of a surface with a GridLine
403 struct FaceLineIntersector
406 double _u, _v, _w; // params on the face and the line
407 Transition _transition; // transition of at intersection (see IntCurveSurface.cdl)
408 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
411 gp_Cylinder _cylinder;
415 __IntCurvesFace_Intersector* _surfaceInt;
417 vector< F_IntersectPoint > _intPoints;
419 void IntersectWithPlane (const GridLine& gridLine);
420 void IntersectWithCylinder(const GridLine& gridLine);
421 void IntersectWithCone (const GridLine& gridLine);
422 void IntersectWithSphere (const GridLine& gridLine);
423 void IntersectWithTorus (const GridLine& gridLine);
424 void IntersectWithSurface (const GridLine& gridLine);
426 bool UVIsOnFace() const;
427 void addIntPoint(const bool toClassify=true);
428 bool isParamOnLineOK( const double linLength )
430 return -_tol < _w && _w < linLength + _tol;
432 FaceLineIntersector():_surfaceInt(0) {}
433 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
435 // --------------------------------------------------------------------------
437 * \brief Class representing topology of the hexahedron and creating a mesh
438 * volume basing on analysis of hexahedron intersection with geometry
442 // --------------------------------------------------------------------------------
445 // --------------------------------------------------------------------------------
446 struct _Node //!< node either at a hexahedron corner or at intersection
448 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
449 const B_IntersectPoint* _intPoint;
450 const _Face* _usedInFace;
452 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
453 :_node(n), _intPoint(ip), _usedInFace(0) {}
454 const SMDS_MeshNode* Node() const
455 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
456 const E_IntersectPoint* EdgeIntPnt() const
457 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
458 bool IsUsedInFace( const _Face* polygon = 0 )
460 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
462 void Add( const E_IntersectPoint* ip )
467 else if ( !_intPoint->_node ) {
468 ip->Add( _intPoint->_faceIDs );
472 _intPoint->Add( ip->_faceIDs );
475 TGeomID IsLinked( const B_IntersectPoint* other,
476 TGeomID avoidFace=-1 ) const // returns id of a common face
478 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
480 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
482 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
486 if ( const SMDS_MeshNode* n = Node() )
487 return SMESH_TNodeXYZ( n );
488 if ( const E_IntersectPoint* eip =
489 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
491 return gp_Pnt( 1e100, 0, 0 );
493 TGeomID ShapeID() const
495 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
496 return eip->_shapeID;
500 // --------------------------------------------------------------------------------
501 struct _Link // link connecting two _Node's
504 _Face* _faces[2]; // polygons sharing a link
505 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
506 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
507 vector< _Link > _splits;
508 _Link() { _faces[0] = 0; }
510 // --------------------------------------------------------------------------------
515 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
516 void Reverse() { _reverse = !_reverse; }
517 int NbResultLinks() const { return _link->_splits.size(); }
518 _OrientedLink ResultLink(int i) const
520 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
522 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
523 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
524 operator bool() const { return _link; }
525 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
527 vector< TGeomID > faces;
528 const B_IntersectPoint *ip0, *ip1;
529 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
530 ( ip1 = _link->_nodes[1]->_intPoint ))
532 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
533 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
534 !usedIDs.count( ip0->_faceIDs[i] ) )
535 faces.push_back( ip0->_faceIDs[i] );
539 bool HasEdgeNodes() const
541 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
542 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
546 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
548 void AddFace( _Face* f )
550 if ( _link->_faces[0] )
552 _link->_faces[1] = f;
556 _link->_faces[0] = f;
557 _link->_faces[1] = 0;
560 void RemoveFace( _Face* f )
562 if ( !_link->_faces[0] ) return;
564 if ( _link->_faces[1] == f )
566 _link->_faces[1] = 0;
568 else if ( _link->_faces[0] == f )
570 _link->_faces[0] = 0;
571 if ( _link->_faces[1] )
573 _link->_faces[0] = _link->_faces[1];
574 _link->_faces[1] = 0;
579 // --------------------------------------------------------------------------------
582 vector< _OrientedLink > _links; // links on GridLine's
583 vector< _Link > _polyLinks; // links added to close a polygonal face
584 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
585 bool IsPolyLink( const _OrientedLink& ol )
587 return _polyLinks.empty() ? false :
588 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
590 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
592 if ( faceToFindEqual && faceToFindEqual != this ) {
593 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
594 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
595 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
598 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
605 _polyLinks.push_back( l );
606 _links.push_back( _OrientedLink( &_polyLinks.back() ));
609 // --------------------------------------------------------------------------------
610 struct _volumeDef // holder of nodes of a volume mesh element
612 vector< _Node* > _nodes;
613 vector< int > _quantities;
614 typedef boost::shared_ptr<_volumeDef> Ptr;
615 void set( const vector< _Node* >& nodes,
616 const vector< int >& quant = vector< int >() )
617 { _nodes = nodes; _quantities = quant; }
618 void set( _Node** nodes, int nb )
619 { _nodes.assign( nodes, nodes + nb ); }
622 // topology of a hexahedron
625 _Link _hexLinks [12];
628 // faces resulted from hexahedron intersection
629 vector< _Face > _polygons;
631 // intresections with EDGEs
632 vector< const E_IntersectPoint* > _eIntPoints;
634 // additional nodes created at intersection points
635 vector< _Node > _intNodes;
637 // nodes inside the hexahedron (at VERTEXes)
638 vector< _Node* > _vIntNodes;
640 // computed volume elements
641 //vector< _volumeDef::Ptr > _volumeDefs;
642 _volumeDef _volumeDefs;
645 double _sizeThreshold, _sideLength[3];
646 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
647 int _origNodeInd; // index of _hexNodes[0] node within the _grid
651 Hexahedron(const double sizeThreshold, Grid* grid);
652 int MakeElements(SMESH_MesherHelper& helper,
653 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
654 void ComputeElements();
655 void Init() { init( _i, _j, _k ); }
658 Hexahedron(const Hexahedron& other );
659 void init( size_t i, size_t j, size_t k );
660 void init( size_t i );
661 void addEdges(SMESH_MesherHelper& helper,
662 vector< Hexahedron* >& intersectedHex,
663 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
664 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
665 double proj, BRepAdaptor_Curve& curve,
666 const gp_XYZ& axis, const gp_XYZ& origin );
667 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
668 bool addIntersection( const E_IntersectPoint& ip,
669 vector< Hexahedron* >& hexes,
670 int ijk[], int dIJK[] );
671 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
672 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
673 bool findChainOnEdge( const vector< _OrientedLink >& splits,
674 const _OrientedLink& prevSplit,
675 const _OrientedLink& avoidSplit,
678 vector<_Node*>& chn);
679 int addElements(SMESH_MesherHelper& helper);
680 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const;
681 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
682 bool isInHole() const;
683 bool checkPolyhedronSize() const;
688 bool debugDumpLink( _Link* link );
689 _Node* findEqualNode( vector< _Node* >& nodes,
690 const E_IntersectPoint* ip,
693 for ( size_t i = 0; i < nodes.size(); ++i )
694 if ( nodes[i]->EdgeIntPnt() == ip ||
695 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
699 bool isImplementEdges() const { return !_grid->_edgeIntP.empty(); }
700 bool isOutParam(const double uvw[3]) const;
704 // --------------------------------------------------------------------------
706 * \brief Hexahedron computing volumes in one thread
708 struct ParallelHexahedron
710 vector< Hexahedron* >& _hexVec;
711 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
712 void operator() ( const tbb::blocked_range<size_t>& r ) const
714 for ( size_t i = r.begin(); i != r.end(); ++i )
715 if ( Hexahedron* hex = _hexVec[ i ] )
716 hex->ComputeElements();
719 // --------------------------------------------------------------------------
721 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
723 struct ParallelIntersector
725 vector< FaceGridIntersector >& _faceVec;
726 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
727 void operator() ( const tbb::blocked_range<size_t>& r ) const
729 for ( size_t i = r.begin(); i != r.end(); ++i )
730 _faceVec[i].Intersect();
735 //=============================================================================
736 // Implementation of internal utils
737 //=============================================================================
739 * \brief adjust \a i to have \a val between values[i] and values[i+1]
741 inline void locateValue( int & i, double val, const vector<double>& values,
742 int& di, double tol )
744 //val += values[0]; // input \a val is measured from 0.
745 if ( i > values.size()-2 )
748 while ( i+2 < values.size() && val > values[ i+1 ])
750 while ( i > 0 && val < values[ i ])
753 if ( i > 0 && val - values[ i ] < tol )
755 else if ( i+2 < values.size() && values[ i+1 ] - val < tol )
760 //=============================================================================
762 * Remove coincident intersection points
764 void GridLine::RemoveExcessIntPoints( const double tol )
766 if ( _intPoints.size() < 2 ) return;
768 set< Transition > tranSet;
769 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
770 while ( ip2 != _intPoints.end() )
774 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
776 tranSet.insert( ip1->_transition );
777 tranSet.insert( ip2->_transition );
778 ip2->Add( ip1->_faceIDs );
779 _intPoints.erase( ip1 );
782 if ( tranSet.size() > 1 ) // points with different transition coincide
784 bool isIN = tranSet.count( Trans_IN );
785 bool isOUT = tranSet.count( Trans_OUT );
787 (*ip1)._transition = Trans_TANGENT;
789 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
793 //================================================================================
795 * Return "is OUT" state for nodes before the given intersection point
797 bool GridLine::GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut )
799 if ( ip->_transition == Trans_IN )
801 if ( ip->_transition == Trans_OUT )
803 if ( ip->_transition == Trans_APEX )
805 // singularity point (apex of a cone)
806 if ( _intPoints.size() == 1 || ip == _intPoints.begin() )
808 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
809 if ( ipAft == _intPoints.end() )
812 if ( ipBef->_transition != ipAft->_transition )
813 return ( ipBef->_transition == Trans_OUT );
814 return ( ipBef->_transition != Trans_OUT );
816 // _transition == Trans_TANGENT
819 //================================================================================
823 void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
824 const SMDS_MeshNode* n) const
826 if ( _faceIDs.empty() )
829 for ( size_t i = 0; i < fIDs.size(); ++i )
831 vector< TGeomID >::iterator it =
832 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
833 if ( it == _faceIDs.end() )
834 _faceIDs.push_back( fIDs[i] );
839 //================================================================================
841 * Returns index of a common face if any, else zero
843 int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
846 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
847 if ( avoidFace != other->_faceIDs[i] &&
848 IsOnFace ( other->_faceIDs[i] ))
849 return other->_faceIDs[i];
852 //================================================================================
854 * Returns \c true if \a faceID in in this->_faceIDs
856 bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
858 vector< TGeomID >::const_iterator it =
859 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
860 return ( it != _faceIDs.end() );
862 //================================================================================
864 * Return an iterator on GridLine's in a given direction
866 LineIndexer Grid::GetLineIndexer(size_t iDir) const
868 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
869 const string s [] = { "X", "Y", "Z" };
870 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
871 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
872 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
875 //=============================================================================
877 * Creates GridLine's of the grid
879 void Grid::SetCoordinates(const vector<double>& xCoords,
880 const vector<double>& yCoords,
881 const vector<double>& zCoords,
882 const double* axesDirs,
883 const Bnd_Box& shapeBox)
885 _coords[0] = xCoords;
886 _coords[1] = yCoords;
887 _coords[2] = zCoords;
889 _axes[0].SetCoord( axesDirs[0],
892 _axes[1].SetCoord( axesDirs[3],
895 _axes[2].SetCoord( axesDirs[6],
898 _axes[0].Normalize();
899 _axes[1].Normalize();
900 _axes[2].Normalize();
902 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
906 _minCellSize = Precision::Infinite();
907 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
909 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
911 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
912 if ( cellLen < _minCellSize )
913 _minCellSize = cellLen;
916 if ( _minCellSize < Precision::Confusion() )
917 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
918 SMESH_Comment("Too small cell size: ") << _minCellSize );
919 _tol = _minCellSize / 1000.;
921 // attune grid extremities to shape bounding box
923 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
924 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
925 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
926 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
927 for ( int i = 0; i < 6; ++i )
928 if ( fabs( sP[i] - *cP[i] ) < _tol )
929 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
931 for ( int iDir = 0; iDir < 3; ++iDir )
933 if ( _coords[iDir][0] - sP[iDir] > _tol )
935 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
936 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
938 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
940 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
941 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
944 _tol = _minCellSize / 1000.;
946 _origin = ( _coords[0][0] * _axes[0] +
947 _coords[1][0] * _axes[1] +
948 _coords[2][0] * _axes[2] );
951 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
953 LineIndexer li = GetLineIndexer( iDir );
954 _lines[iDir].resize( li.NbLines() );
955 double len = _coords[ iDir ].back() - _coords[iDir].front();
956 for ( ; li.More(); ++li )
958 GridLine& gl = _lines[iDir][ li.LineIndex() ];
959 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
960 _coords[1][li.J()] * _axes[1] +
961 _coords[2][li.K()] * _axes[2] );
962 gl._line.SetDirection( _axes[ iDir ]);
967 //================================================================================
969 * Computes coordinates of a point in the grid CS
971 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
973 gp_XYZ p = P * _invB;
974 p.Coord( UVW[0], UVW[1], UVW[2] );
976 //================================================================================
980 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
982 // state of each node of the grid relative to the geometry
983 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
984 vector< bool > isNodeOut( nbGridNodes, false );
985 _nodes.resize( nbGridNodes, 0 );
986 _gridIntP.resize( nbGridNodes, NULL );
988 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
990 LineIndexer li = GetLineIndexer( iDir );
992 // find out a shift of node index while walking along a GridLine in this direction
993 li.SetIndexOnLine( 0 );
994 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
995 li.SetIndexOnLine( 1 );
996 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
998 const vector<double> & coords = _coords[ iDir ];
999 for ( ; li.More(); ++li ) // loop on lines in iDir
1001 li.SetIndexOnLine( 0 );
1002 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1004 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1005 const gp_XYZ lineLoc = line._line.Location().XYZ();
1006 const gp_XYZ lineDir = line._line.Direction().XYZ();
1007 line.RemoveExcessIntPoints( _tol );
1008 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1009 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1012 const double* nodeCoord = & coords[0];
1013 const double* coord0 = nodeCoord;
1014 const double* coordEnd = coord0 + coords.size();
1015 double nodeParam = 0;
1016 for ( ; ip != intPnts.end(); ++ip )
1018 // set OUT state or just skip IN nodes before ip
1019 if ( nodeParam < ip->_paramOnLine - _tol )
1021 isOut = line.GetIsOutBefore( ip, isOut );
1023 while ( nodeParam < ip->_paramOnLine - _tol )
1026 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = isOut;
1027 if ( ++nodeCoord < coordEnd )
1028 nodeParam = *nodeCoord - *coord0;
1032 if ( nodeCoord == coordEnd ) break;
1034 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1035 if ( nodeParam > ip->_paramOnLine + _tol )
1037 // li.SetIndexOnLine( 0 );
1038 // double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1039 // xyz[ li._iConst ] += ip->_paramOnLine;
1040 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1041 ip->_node = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1042 ip->_indexOnLine = nodeCoord-coord0-1;
1044 // create a mesh node at ip concident with a grid node
1047 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1048 if ( !_nodes[ nodeIndex ] )
1050 //li.SetIndexOnLine( nodeCoord-coord0 );
1051 //double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1052 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1053 _nodes [ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1054 _gridIntP[ nodeIndex ] = & * ip;
1056 if ( _gridIntP[ nodeIndex ] )
1057 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1059 _gridIntP[ nodeIndex ] = & * ip;
1060 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1061 ip->_indexOnLine = nodeCoord-coord0;
1062 if ( ++nodeCoord < coordEnd )
1063 nodeParam = *nodeCoord - *coord0;
1066 // set OUT state to nodes after the last ip
1067 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1068 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = true;
1072 // Create mesh nodes at !OUT nodes of the grid
1074 for ( size_t z = 0; z < _coords[2].size(); ++z )
1075 for ( size_t y = 0; y < _coords[1].size(); ++y )
1076 for ( size_t x = 0; x < _coords[0].size(); ++x )
1078 size_t nodeIndex = NodeIndex( x, y, z );
1079 if ( !isNodeOut[ nodeIndex ] && !_nodes[ nodeIndex] )
1081 //_nodes[ nodeIndex ] = helper.AddNode( _coords[0][x], _coords[1][y], _coords[2][z] );
1082 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1083 _coords[1][y] * _axes[1] +
1084 _coords[2][z] * _axes[2] );
1085 _nodes[ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1090 // check validity of transitions
1091 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1092 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1094 LineIndexer li = GetLineIndexer( iDir );
1095 for ( ; li.More(); ++li )
1097 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1098 if ( intPnts.empty() ) continue;
1099 if ( intPnts.size() == 1 )
1101 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1102 intPnts.begin()->_transition != Trans_APEX )
1103 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1104 SMESH_Comment("Wrong SOLE transition of GridLine (")
1105 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1106 << ") along " << li._nameConst
1107 << ": " << trName[ intPnts.begin()->_transition] );
1111 if ( intPnts.begin()->_transition == Trans_OUT )
1112 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1113 SMESH_Comment("Wrong START transition of GridLine (")
1114 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1115 << ") along " << li._nameConst
1116 << ": " << trName[ intPnts.begin()->_transition ]);
1117 if ( intPnts.rbegin()->_transition == Trans_IN )
1118 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1119 SMESH_Comment("Wrong END transition of GridLine (")
1120 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1121 << ") along " << li._nameConst
1122 << ": " << trName[ intPnts.rbegin()->_transition ]);
1129 //=============================================================================
1131 * Intersects TopoDS_Face with all GridLine's
1133 void FaceGridIntersector::Intersect()
1135 FaceLineIntersector intersector;
1136 intersector._surfaceInt = GetCurveFaceIntersector();
1137 intersector._tol = _grid->_tol;
1138 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1139 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1141 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1142 PIntFun interFunction;
1144 bool isDirect = true;
1145 BRepAdaptor_Surface surf( _face );
1146 switch ( surf.GetType() ) {
1148 intersector._plane = surf.Plane();
1149 interFunction = &FaceLineIntersector::IntersectWithPlane;
1150 isDirect = intersector._plane.Direct();
1152 case GeomAbs_Cylinder:
1153 intersector._cylinder = surf.Cylinder();
1154 interFunction = &FaceLineIntersector::IntersectWithCylinder;
1155 isDirect = intersector._cylinder.Direct();
1158 intersector._cone = surf.Cone();
1159 interFunction = &FaceLineIntersector::IntersectWithCone;
1160 //isDirect = intersector._cone.Direct();
1162 case GeomAbs_Sphere:
1163 intersector._sphere = surf.Sphere();
1164 interFunction = &FaceLineIntersector::IntersectWithSphere;
1165 isDirect = intersector._sphere.Direct();
1168 intersector._torus = surf.Torus();
1169 interFunction = &FaceLineIntersector::IntersectWithTorus;
1170 //isDirect = intersector._torus.Direct();
1173 interFunction = &FaceLineIntersector::IntersectWithSurface;
1176 std::swap( intersector._transOut, intersector._transIn );
1178 _intersections.clear();
1179 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1181 if ( surf.GetType() == GeomAbs_Plane )
1183 // check if all lines in this direction are parallel to a plane
1184 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1185 Precision::Angular()))
1187 // find out a transition, that is the same for all lines of a direction
1188 gp_Dir plnNorm = intersector._plane.Axis().Direction();
1189 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1190 intersector._transition =
1191 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1193 if ( surf.GetType() == GeomAbs_Cylinder )
1195 // check if all lines in this direction are parallel to a cylinder
1196 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1197 Precision::Angular()))
1201 // intersect the grid lines with the face
1202 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1204 GridLine& gridLine = _grid->_lines[iDir][iL];
1205 if ( _bndBox.IsOut( gridLine._line )) continue;
1207 intersector._intPoints.clear();
1208 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1209 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1210 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1214 //================================================================================
1216 * Return true if (_u,_v) is on the face
1218 bool FaceLineIntersector::UVIsOnFace() const
1220 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1221 return ( state == TopAbs_IN || state == TopAbs_ON );
1223 //================================================================================
1225 * Store an intersection if it is IN or ON the face
1227 void FaceLineIntersector::addIntPoint(const bool toClassify)
1229 if ( !toClassify || UVIsOnFace() )
1232 p._paramOnLine = _w;
1233 p._transition = _transition;
1234 _intPoints.push_back( p );
1237 //================================================================================
1239 * Intersect a line with a plane
1241 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
1243 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1244 _w = linPlane.ParamOnConic(1);
1245 if ( isParamOnLineOK( gridLine._length ))
1247 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1251 //================================================================================
1253 * Intersect a line with a cylinder
1255 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1257 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1258 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1260 _w = linCylinder.ParamOnConic(1);
1261 if ( linCylinder.NbPoints() == 1 )
1262 _transition = Trans_TANGENT;
1264 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1265 if ( isParamOnLineOK( gridLine._length ))
1267 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1270 if ( linCylinder.NbPoints() > 1 )
1272 _w = linCylinder.ParamOnConic(2);
1273 if ( isParamOnLineOK( gridLine._length ))
1275 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1276 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1282 //================================================================================
1284 * Intersect a line with a cone
1286 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1288 IntAna_IntConicQuad linCone(gridLine._line,_cone);
1289 if ( !linCone.IsDone() ) return;
1291 gp_Vec du, dv, norm;
1292 for ( int i = 1; i <= linCone.NbPoints(); ++i )
1294 _w = linCone.ParamOnConic( i );
1295 if ( !isParamOnLineOK( gridLine._length )) continue;
1296 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1299 ElSLib::D1( _u, _v, _cone, P, du, dv );
1301 double normSize2 = norm.SquareMagnitude();
1302 if ( normSize2 > Precision::Angular() * Precision::Angular() )
1304 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1305 cos /= sqrt( normSize2 );
1306 if ( cos < -Precision::Angular() )
1307 _transition = _transIn;
1308 else if ( cos > Precision::Angular() )
1309 _transition = _transOut;
1311 _transition = Trans_TANGENT;
1315 _transition = Trans_APEX;
1317 addIntPoint( /*toClassify=*/false);
1321 //================================================================================
1323 * Intersect a line with a sphere
1325 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
1327 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1328 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1330 _w = linSphere.ParamOnConic(1);
1331 if ( linSphere.NbPoints() == 1 )
1332 _transition = Trans_TANGENT;
1334 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1335 if ( isParamOnLineOK( gridLine._length ))
1337 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1340 if ( linSphere.NbPoints() > 1 )
1342 _w = linSphere.ParamOnConic(2);
1343 if ( isParamOnLineOK( gridLine._length ))
1345 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
1346 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1352 //================================================================================
1354 * Intersect a line with a torus
1356 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
1358 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
1359 if ( !linTorus.IsDone()) return;
1361 gp_Vec du, dv, norm;
1362 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
1364 _w = linTorus.ParamOnLine( i );
1365 if ( !isParamOnLineOK( gridLine._length )) continue;
1366 linTorus.ParamOnTorus( i, _u,_v );
1369 ElSLib::D1( _u, _v, _torus, P, du, dv );
1371 double normSize = norm.Magnitude();
1372 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1374 if ( cos < -Precision::Angular() )
1375 _transition = _transIn;
1376 else if ( cos > Precision::Angular() )
1377 _transition = _transOut;
1379 _transition = Trans_TANGENT;
1380 addIntPoint( /*toClassify=*/false);
1384 //================================================================================
1386 * Intersect a line with a non-analytical surface
1388 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
1390 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
1391 if ( !_surfaceInt->IsDone() ) return;
1392 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
1394 _transition = Transition( _surfaceInt->Transition( i ) );
1395 _w = _surfaceInt->WParameter( i );
1396 addIntPoint(/*toClassify=*/false);
1399 //================================================================================
1401 * check if its face can be safely intersected in a thread
1403 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
1408 TopLoc_Location loc;
1409 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
1410 Handle(Geom_RectangularTrimmedSurface) ts =
1411 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
1412 while( !ts.IsNull() ) {
1413 surf = ts->BasisSurface();
1414 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
1416 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
1417 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
1418 if ( !noSafeTShapes.insert((const Standard_Transient*) _face.TShape() ).second )
1422 TopExp_Explorer exp( _face, TopAbs_EDGE );
1423 for ( ; exp.More(); exp.Next() )
1425 bool edgeIsSafe = true;
1426 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1429 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
1432 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1433 while( !tc.IsNull() ) {
1434 c = tc->BasisCurve();
1435 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1437 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
1438 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
1445 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
1448 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1449 while( !tc.IsNull() ) {
1450 c2 = tc->BasisCurve();
1451 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1453 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
1454 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
1458 if ( !edgeIsSafe && !noSafeTShapes.insert((const Standard_Transient*) e.TShape() ).second )
1463 //================================================================================
1465 * \brief Creates topology of the hexahedron
1467 Hexahedron::Hexahedron(const double sizeThreshold, Grid* grid)
1468 : _grid( grid ), _sizeThreshold( sizeThreshold ), _nbFaceIntNodes(0)
1470 _polygons.reserve(100); // to avoid reallocation;
1472 //set nodes shift within grid->_nodes from the node 000
1473 size_t dx = _grid->NodeIndexDX();
1474 size_t dy = _grid->NodeIndexDY();
1475 size_t dz = _grid->NodeIndexDZ();
1477 size_t i100 = i000 + dx;
1478 size_t i010 = i000 + dy;
1479 size_t i110 = i010 + dx;
1480 size_t i001 = i000 + dz;
1481 size_t i101 = i100 + dz;
1482 size_t i011 = i010 + dz;
1483 size_t i111 = i110 + dz;
1484 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
1485 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
1486 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
1487 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
1488 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
1489 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
1490 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
1491 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
1493 vector< int > idVec;
1494 // set nodes to links
1495 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
1497 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
1498 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
1499 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
1500 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
1503 // set links to faces
1504 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
1505 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
1507 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
1508 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
1509 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
1510 faceID == SMESH_Block::ID_Fx1z ||
1511 faceID == SMESH_Block::ID_F0yz );
1512 quad._links.resize(4);
1513 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
1514 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
1515 for ( int i = 0; i < 4; ++i )
1517 bool revLink = revFace;
1518 if ( i > 1 ) // reverse links u1 and v0
1520 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
1521 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
1526 //================================================================================
1528 * \brief Copy constructor
1530 Hexahedron::Hexahedron( const Hexahedron& other )
1531 :_grid( other._grid ), _sizeThreshold( other._sizeThreshold ), _nbFaceIntNodes(0)
1533 _polygons.reserve(100); // to avoid reallocation;
1535 for ( int i = 0; i < 8; ++i )
1536 _nodeShift[i] = other._nodeShift[i];
1538 for ( int i = 0; i < 12; ++i )
1540 const _Link& srcLink = other._hexLinks[ i ];
1541 _Link& tgtLink = this->_hexLinks[ i ];
1542 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
1543 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
1546 for ( int i = 0; i < 6; ++i )
1548 const _Face& srcQuad = other._hexQuads[ i ];
1549 _Face& tgtQuad = this->_hexQuads[ i ];
1550 tgtQuad._links.resize(4);
1551 for ( int j = 0; j < 4; ++j )
1553 const _OrientedLink& srcLink = srcQuad._links[ j ];
1554 _OrientedLink& tgtLink = tgtQuad._links[ j ];
1555 tgtLink._reverse = srcLink._reverse;
1556 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
1561 //================================================================================
1563 * \brief Initializes its data by given grid cell
1565 void Hexahedron::init( size_t i, size_t j, size_t k )
1567 _i = i; _j = j; _k = k;
1568 // set nodes of grid to nodes of the hexahedron and
1569 // count nodes at hexahedron corners located IN and ON geometry
1570 _nbCornerNodes = _nbBndNodes = 0;
1571 _origNodeInd = _grid->NodeIndex( i,j,k );
1572 for ( int iN = 0; iN < 8; ++iN )
1574 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _nodeShift[iN] ];
1575 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _nodeShift[iN] ];
1576 _nbCornerNodes += bool( _hexNodes[iN]._node );
1577 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
1579 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
1580 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
1581 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
1586 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
1587 _nbFaceIntNodes + _nbCornerNodes + _eIntPoints.size() > 3)
1589 _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
1591 // this method can be called in parallel, so use own helper
1592 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
1594 // create sub-links (_splits) by splitting links with _fIntPoints
1596 for ( int iLink = 0; iLink < 12; ++iLink )
1598 _Link& link = _hexLinks[ iLink ];
1599 link._fIntNodes.resize( link._fIntPoints.size() );
1600 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
1602 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
1603 link._fIntNodes[ i ] = & _intNodes.back();
1606 link._splits.clear();
1607 split._nodes[ 0 ] = link._nodes[0];
1608 bool isOut = ( ! link._nodes[0]->Node() );
1609 bool checkTransition;
1610 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
1612 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
1613 if ( !isGridNode ) // intersection non-coincident with a grid node
1615 if ( split._nodes[ 0 ]->Node() && !isOut )
1617 split._nodes[ 1 ] = link._fIntNodes[i];
1618 link._splits.push_back( split );
1620 split._nodes[ 0 ] = link._fIntNodes[i];
1621 checkTransition = true;
1623 else // FACE intersection coincident with a grid node (at link ends)
1625 checkTransition = ( i == 0 && link._nodes[0]->Node() );
1627 if ( checkTransition )
1629 if ( link._fIntPoints[i]->_faceIDs.size() > 1 || _eIntPoints.size() > 0 )
1630 isOut = isOutPoint( link, i, helper );
1632 switch ( link._fIntPoints[i]->_transition ) {
1633 case Trans_OUT: isOut = true; break;
1634 case Trans_IN : isOut = false; break;
1636 isOut = isOutPoint( link, i, helper );
1640 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
1642 split._nodes[ 1 ] = link._nodes[1];
1643 link._splits.push_back( split );
1647 // Create _Node's at intersections with EDGEs.
1649 const double tol2 = _grid->_tol * _grid->_tol;
1650 int facets[3], nbFacets, subEntity;
1652 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
1654 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
1655 _Node* equalNode = 0;
1656 switch( nbFacets ) {
1657 case 1: // in a _Face
1659 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
1660 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1662 equalNode->Add( _eIntPoints[ iP ] );
1665 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1666 quad._eIntNodes.push_back( & _intNodes.back() );
1670 case 2: // on a _Link
1672 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
1673 if ( link._splits.size() > 0 )
1675 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
1677 equalNode->Add( _eIntPoints[ iP ] );
1681 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1682 for ( int iF = 0; iF < 2; ++iF )
1684 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1685 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1687 equalNode->Add( _eIntPoints[ iP ] );
1690 quad._eIntNodes.push_back( & _intNodes.back() );
1696 case 3: // at a corner
1698 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
1699 if ( node.Node() > 0 )
1701 if ( node._intPoint )
1702 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
1706 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1707 for ( int iF = 0; iF < 3; ++iF )
1709 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1710 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1712 equalNode->Add( _eIntPoints[ iP ] );
1715 quad._eIntNodes.push_back( & _intNodes.back() );
1721 } // switch( nbFacets )
1723 if ( nbFacets == 0 ||
1724 _grid->_shapes( _eIntPoints[ iP ]->_shapeID ).ShapeType() == TopAbs_VERTEX )
1726 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
1728 equalNode->Add( _eIntPoints[ iP ] );
1730 else if ( nbFacets == 0 ) {
1731 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
1732 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1733 _vIntNodes.push_back( & _intNodes.back() );
1736 } // loop on _eIntPoints
1738 else if ( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) // _nbFaceIntNodes == 0
1741 // create sub-links (_splits) of whole links
1742 for ( int iLink = 0; iLink < 12; ++iLink )
1744 _Link& link = _hexLinks[ iLink ];
1745 link._splits.clear();
1746 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
1748 split._nodes[ 0 ] = link._nodes[0];
1749 split._nodes[ 1 ] = link._nodes[1];
1750 link._splits.push_back( split );
1756 //================================================================================
1758 * \brief Initializes its data by given grid cell (countered from zero)
1760 void Hexahedron::init( size_t iCell )
1762 size_t iNbCell = _grid->_coords[0].size() - 1;
1763 size_t jNbCell = _grid->_coords[1].size() - 1;
1764 _i = iCell % iNbCell;
1765 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
1766 _k = iCell / iNbCell / jNbCell;
1770 //================================================================================
1772 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
1774 void Hexahedron::ComputeElements()
1778 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
1779 if ( _nbCornerNodes + nbIntersections < 4 )
1782 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
1786 _polygons.reserve( 20 );
1788 // Create polygons from quadrangles
1789 // --------------------------------
1791 vector< _OrientedLink > splits;
1792 vector<_Node*> chainNodes;
1793 _Face* coplanarPolyg;
1795 bool hasEdgeIntersections = !_eIntPoints.empty();
1797 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
1799 _Face& quad = _hexQuads[ iF ] ;
1801 _polygons.resize( _polygons.size() + 1 );
1802 _Face* polygon = &_polygons.back();
1803 polygon->_polyLinks.reserve( 20 );
1806 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
1807 for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
1808 splits.push_back( quad._links[ iE ].ResultLink( iS ));
1810 // add splits of links to a polygon and add _polyLinks to make
1811 // polygon's boundary closed
1813 int nbSplits = splits.size();
1814 if (( nbSplits == 1 ) &&
1815 ( quad._eIntNodes.empty() ||
1816 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
1817 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
1821 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
1822 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
1823 quad._eIntNodes[ iP ]->_usedInFace = 0;
1825 int nbUsedEdgeNodes = 0;
1826 _Face* prevPolyg = 0; // polygon previously created from this quad
1828 while ( nbSplits > 0 )
1831 while ( !splits[ iS ] )
1834 if ( !polygon->_links.empty() )
1836 _polygons.resize( _polygons.size() + 1 );
1837 polygon = &_polygons.back();
1838 polygon->_polyLinks.reserve( 20 );
1840 polygon->_links.push_back( splits[ iS ] );
1841 splits[ iS++ ]._link = 0;
1844 _Node* nFirst = polygon->_links.back().FirstNode();
1845 _Node *n1,*n2 = polygon->_links.back().LastNode();
1846 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
1848 _OrientedLink& split = splits[ iS ];
1849 if ( !split ) continue;
1851 n1 = split.FirstNode();
1854 n1->_intPoint->_faceIDs.size() > 1 )
1856 // n1 is at intersection with EDGE
1857 if ( findChainOnEdge( splits, polygon->_links.back(), split, iS, quad, chainNodes ))
1859 for ( size_t i = 1; i < chainNodes.size(); ++i )
1860 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1861 prevPolyg = polygon;
1862 n2 = chainNodes.back();
1866 else if ( n1 != n2 )
1868 // try to connect to intersections with EDGEs
1869 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
1870 findChain( n2, n1, quad, chainNodes ))
1872 for ( size_t i = 1; i < chainNodes.size(); ++i )
1874 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
1875 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
1877 if ( chainNodes.back() != n1 )
1879 n2 = chainNodes.back();
1884 // try to connect to a split ending on the same FACE
1887 _OrientedLink foundSplit;
1888 for ( int i = iS; i < splits.size() && !foundSplit; ++i )
1889 if (( foundSplit = splits[ i ]) &&
1890 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
1896 foundSplit._link = 0;
1900 if ( n2 != foundSplit.FirstNode() )
1902 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
1903 n2 = foundSplit.FirstNode();
1909 if ( n2->IsLinked( nFirst->_intPoint ))
1911 polygon->AddPolyLink( n2, n1, prevPolyg );
1914 } // if ( n1 != n2 )
1916 polygon->_links.push_back( split );
1919 n2 = polygon->_links.back().LastNode();
1923 if ( nFirst != n2 ) // close a polygon
1925 if ( !findChain( n2, nFirst, quad, chainNodes ))
1927 if ( !closePolygon( polygon, chainNodes ))
1928 if ( !isImplementEdges() )
1929 chainNodes.push_back( nFirst );
1931 for ( size_t i = 1; i < chainNodes.size(); ++i )
1933 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1934 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
1938 if ( polygon->_links.size() < 3 && nbSplits > 0 )
1940 polygon->_polyLinks.clear();
1941 polygon->_links.clear();
1943 } // while ( nbSplits > 0 )
1945 if ( polygon->_links.size() < 3 )
1947 _polygons.pop_back();
1949 } // loop on 6 hexahedron sides
1951 // Create polygons closing holes in a polyhedron
1952 // ----------------------------------------------
1954 // clear _usedInFace
1955 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
1956 _intNodes[ iN ]._usedInFace = 0;
1958 // add polygons to their links and mark used nodes
1959 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1961 _Face& polygon = _polygons[ iP ];
1962 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1964 polygon._links[ iL ].AddFace( &polygon );
1965 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
1969 vector< _OrientedLink* > freeLinks;
1970 freeLinks.reserve(20);
1971 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1973 _Face& polygon = _polygons[ iP ];
1974 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1975 if ( polygon._links[ iL ].NbFaces() < 2 )
1976 freeLinks.push_back( & polygon._links[ iL ]);
1978 int nbFreeLinks = freeLinks.size();
1979 if ( nbFreeLinks == 1 ) return;
1981 // put not used intersection nodes to _vIntNodes
1982 int nbVertexNodes = 0; // nb not used vertex nodes
1984 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
1985 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
1987 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
1988 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
1990 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
1991 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
1993 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
1996 _vIntNodes.push_back( &_intNodes[ iN ]);
2002 set<TGeomID> usedFaceIDs;
2003 vector< TGeomID > faces;
2004 TGeomID curFace = 0;
2005 const size_t nbQuadPolygons = _polygons.size();
2006 E_IntersectPoint ipTmp;
2008 // create polygons by making closed chains of free links
2009 size_t iPolygon = _polygons.size();
2010 while ( nbFreeLinks > 0 )
2012 if ( iPolygon == _polygons.size() )
2014 _polygons.resize( _polygons.size() + 1 );
2015 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
2016 _polygons[ iPolygon ]._links.reserve( 20 );
2018 _Face& polygon = _polygons[ iPolygon ];
2020 _OrientedLink* curLink = 0;
2022 if (( !hasEdgeIntersections ) ||
2023 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
2025 // get a remaining link to start from
2026 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2027 if (( curLink = freeLinks[ iL ] ))
2028 freeLinks[ iL ] = 0;
2029 polygon._links.push_back( *curLink );
2033 // find all links connected to curLink
2034 curNode = curLink->FirstNode();
2036 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2037 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2039 curLink = freeLinks[ iL ];
2040 freeLinks[ iL ] = 0;
2042 polygon._links.push_back( *curLink );
2044 } while ( curLink );
2046 else // there are intersections with EDGEs
2048 // get a remaining link to start from, one lying on minimal nb of FACEs
2050 typedef pair< TGeomID, int > TFaceOfLink;
2051 TFaceOfLink faceOfLink( -1, -1 );
2052 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
2053 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2054 if ( freeLinks[ iL ] )
2056 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2057 if ( faces.size() == 1 )
2059 faceOfLink = TFaceOfLink( faces[0], iL );
2060 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2062 facesOfLink[0] = faceOfLink;
2064 else if ( facesOfLink[0].first < 0 )
2066 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
2067 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
2070 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
2071 faceOfLink = facesOfLink[i];
2073 if ( faceOfLink.first < 0 ) // all faces used
2075 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
2076 if (( curLink = freeLinks[ iL ]))
2079 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2080 faceOfLink.second = iL;
2082 usedFaceIDs.clear();
2084 curFace = faceOfLink.first;
2085 curLink = freeLinks[ faceOfLink.second ];
2086 freeLinks[ faceOfLink.second ] = 0;
2088 usedFaceIDs.insert( curFace );
2089 polygon._links.push_back( *curLink );
2092 // find all links lying on a curFace
2095 // go forward from curLink
2096 curNode = curLink->LastNode();
2098 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2099 if ( freeLinks[ iL ] &&
2100 freeLinks[ iL ]->FirstNode() == curNode &&
2101 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
2103 curLink = freeLinks[ iL ];
2104 freeLinks[ iL ] = 0;
2105 polygon._links.push_back( *curLink );
2108 } while ( curLink );
2110 std::reverse( polygon._links.begin(), polygon._links.end() );
2112 curLink = & polygon._links.back();
2115 // go backward from curLink
2116 curNode = curLink->FirstNode();
2118 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2119 if ( freeLinks[ iL ] &&
2120 freeLinks[ iL ]->LastNode() == curNode &&
2121 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
2123 curLink = freeLinks[ iL ];
2124 freeLinks[ iL ] = 0;
2125 polygon._links.push_back( *curLink );
2128 } while ( curLink );
2130 curNode = polygon._links.back().FirstNode();
2132 if ( polygon._links[0].LastNode() != curNode )
2134 if ( nbVertexNodes > 0 )
2136 // add links with _vIntNodes if not already used
2138 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2139 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
2140 _vIntNodes[ iN ]->IsOnFace( curFace ))
2142 _vIntNodes[ iN ]->_usedInFace = &polygon;
2143 chainNodes.push_back( _vIntNodes[ iN ] );
2145 if ( chainNodes.size() > 1 )
2147 sortVertexNodes( chainNodes, curNode, curFace );
2149 for ( int i = 0; i < chainNodes.size(); ++i )
2151 polygon.AddPolyLink( chainNodes[ i ], curNode );
2152 curNode = chainNodes[ i ];
2153 freeLinks.push_back( &polygon._links.back() );
2156 nbVertexNodes -= chainNodes.size();
2158 // if ( polygon._links.size() > 1 )
2160 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
2161 freeLinks.push_back( &polygon._links.back() );
2165 } // if there are intersections with EDGEs
2167 if ( polygon._links.size() < 2 ||
2168 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
2169 return; // closed polygon not found -> invalid polyhedron
2171 if ( polygon._links.size() == 2 )
2173 if ( freeLinks.back() == &polygon._links.back() )
2175 freeLinks.pop_back();
2178 if ( polygon._links.front().NbFaces() > 0 )
2179 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
2180 if ( polygon._links.back().NbFaces() > 0 )
2181 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
2183 if ( iPolygon == _polygons.size()-1 )
2184 _polygons.pop_back();
2186 else // polygon._links.size() >= 2
2188 // add polygon to its links
2189 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2191 polygon._links[ iL ].AddFace( &polygon );
2192 polygon._links[ iL ].Reverse();
2194 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
2196 // check that a polygon does not lie on a hexa side
2198 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
2200 if ( polygon._links[ iL ].NbFaces() < 2 )
2201 continue; // it's a just added free link
2202 // look for a polygon made on a hexa side and sharing
2203 // two or more haxa links
2205 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
2206 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
2207 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
2208 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
2209 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
2210 coplanarPolyg < & _polygons[ nbQuadPolygons ])
2212 if ( iL2 == polygon._links.size() )
2215 if ( coplanarPolyg ) // coplanar polygon found
2217 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
2218 nbFreeLinks -= polygon._polyLinks.size();
2220 // an E_IntersectPoint used to mark nodes of coplanarPolyg
2221 // as lying on curFace while they are not at intersection with geometry
2222 ipTmp._faceIDs.resize(1);
2223 ipTmp._faceIDs[0] = curFace;
2225 // fill freeLinks with links not shared by coplanarPolyg and polygon
2226 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2227 if ( polygon._links[ iL ]._link->_faces[1] &&
2228 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
2230 _Face* p = polygon._links[ iL ]._link->_faces[0];
2231 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2232 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
2234 freeLinks.push_back( & p->_links[ iL2 ] );
2236 freeLinks.back()->RemoveFace( &polygon );
2240 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
2241 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
2242 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
2244 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
2245 if ( p == coplanarPolyg )
2246 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
2247 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2248 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
2250 // set links of coplanarPolyg in place of used freeLinks
2251 // to re-create coplanarPolyg next
2253 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
2254 if ( iL3 < freeLinks.size() )
2255 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
2257 freeLinks.push_back( & p->_links[ iL2 ] );
2259 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
2260 // mark nodes of coplanarPolyg as lying on curFace
2261 for ( int iN = 0; iN < 2; ++iN )
2263 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
2264 if ( n->_intPoint ) n->_intPoint->Add( ipTmp._faceIDs );
2265 else n->_intPoint = &ipTmp;
2270 // set coplanarPolyg to be re-created next
2271 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2272 if ( coplanarPolyg == & _polygons[ iP ] )
2275 _polygons[ iPolygon ]._links.clear();
2276 _polygons[ iPolygon ]._polyLinks.clear();
2279 _polygons.pop_back();
2280 usedFaceIDs.erase( curFace );
2282 } // if ( coplanarPolyg )
2283 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
2285 iPolygon = _polygons.size();
2287 } // end of case ( polygon._links.size() > 2 )
2288 } // while ( nbFreeLinks > 0 )
2290 if ( ! checkPolyhedronSize() )
2295 for ( size_t i = 0; i < 8; ++i )
2296 if ( _hexNodes[ i ]._intPoint == &ipTmp )
2297 _hexNodes[ i ]._intPoint = 0;
2299 // create a classic cell if possible
2302 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2303 nbPolygons += (_polygons[ iF ]._links.size() > 0 );
2305 //const int nbNodes = _nbCornerNodes + nbIntersections;
2307 for ( size_t i = 0; i < 8; ++i )
2308 nbNodes += _hexNodes[ i ].IsUsedInFace();
2309 for ( size_t i = 0; i < _intNodes.size(); ++i )
2310 nbNodes += _intNodes[ i ].IsUsedInFace();
2312 bool isClassicElem = false;
2313 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
2314 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
2315 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
2316 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
2317 if ( !isClassicElem )
2319 _volumeDefs._nodes.clear();
2320 _volumeDefs._quantities.clear();
2322 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2324 const size_t nbLinks = _polygons[ iF ]._links.size();
2325 if ( nbLinks == 0 ) continue;
2326 _volumeDefs._quantities.push_back( nbLinks );
2327 for ( size_t iL = 0; iL < nbLinks; ++iL )
2328 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
2332 //================================================================================
2334 * \brief Create elements in the mesh
2336 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
2337 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2339 SMESHDS_Mesh* mesh = helper.GetMeshDS();
2341 size_t nbCells[3] = { _grid->_coords[0].size() - 1,
2342 _grid->_coords[1].size() - 1,
2343 _grid->_coords[2].size() - 1 };
2344 const size_t nbGridCells = nbCells[0] * nbCells[1] * nbCells[2];
2345 vector< Hexahedron* > allHexa( nbGridCells, 0 );
2348 // set intersection nodes from GridLine's to links of allHexa
2349 int i,j,k, iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
2350 for ( int iDir = 0; iDir < 3; ++iDir )
2352 int dInd[4][3] = { {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
2353 dInd[1][ iDirOther[iDir][0] ] = -1;
2354 dInd[2][ iDirOther[iDir][1] ] = -1;
2355 dInd[3][ iDirOther[iDir][0] ] = -1; dInd[3][ iDirOther[iDir][1] ] = -1;
2356 // loop on GridLine's parallel to iDir
2357 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
2358 for ( ; lineInd.More(); ++lineInd )
2360 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
2361 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
2362 for ( ; ip != line._intPoints.end(); ++ip )
2364 // if ( !ip->_node ) continue; // intersection at a grid node
2365 lineInd.SetIndexOnLine( ip->_indexOnLine );
2366 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
2368 i = int(lineInd.I()) + dInd[iL][0];
2369 j = int(lineInd.J()) + dInd[iL][1];
2370 k = int(lineInd.K()) + dInd[iL][2];
2371 if ( i < 0 || i >= nbCells[0] ||
2372 j < 0 || j >= nbCells[1] ||
2373 k < 0 || k >= nbCells[2] ) continue;
2375 const size_t hexIndex = _grid->CellIndex( i,j,k );
2376 Hexahedron *& hex = allHexa[ hexIndex ];
2379 hex = new Hexahedron( *this );
2385 const int iLink = iL + iDir * 4;
2386 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
2387 hex->_nbFaceIntNodes += bool( ip->_node );
2393 // implement geom edges into the mesh
2394 addEdges( helper, allHexa, edge2faceIDsMap );
2396 // add not split hexadrons to the mesh
2398 vector< Hexahedron* > intHexa( nbIntHex, (Hexahedron*) NULL );
2399 for ( size_t i = 0; i < allHexa.size(); ++i )
2401 Hexahedron * & hex = allHexa[ i ];
2404 intHexa.push_back( hex );
2405 if ( hex->_nbFaceIntNodes > 0 || hex->_eIntPoints.size() > 0 )
2406 continue; // treat intersected hex later
2407 this->init( hex->_i, hex->_j, hex->_k );
2413 if (( _nbCornerNodes == 8 ) &&
2414 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
2416 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
2417 SMDS_MeshElement* el =
2418 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
2419 _hexNodes[3].Node(), _hexNodes[1].Node(),
2420 _hexNodes[4].Node(), _hexNodes[6].Node(),
2421 _hexNodes[7].Node(), _hexNodes[5].Node() );
2422 mesh->SetMeshElementOnShape( el, helper.GetSubShapeID() );
2427 else if ( _nbCornerNodes > 3 && !hex )
2429 // all intersection of hex with geometry are at grid nodes
2430 hex = new Hexahedron( *this );
2434 intHexa.push_back( hex );
2438 // add elements resulted from hexadron intersection
2440 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
2441 ParallelHexahedron( intHexa ),
2442 tbb::simple_partitioner()); // ComputeElements() is called here
2443 for ( size_t i = 0; i < intHexa.size(); ++i )
2444 if ( Hexahedron * hex = intHexa[ i ] )
2445 nbAdded += hex->addElements( helper );
2447 for ( size_t i = 0; i < intHexa.size(); ++i )
2448 if ( Hexahedron * hex = intHexa[ i ] )
2450 hex->ComputeElements();
2451 nbAdded += hex->addElements( helper );
2455 for ( size_t i = 0; i < allHexa.size(); ++i )
2457 delete allHexa[ i ];
2462 //================================================================================
2464 * \brief Implements geom edges into the mesh
2466 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
2467 vector< Hexahedron* >& hexes,
2468 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2470 if ( edge2faceIDsMap.empty() ) return;
2472 // Prepare planes for intersecting with EDGEs
2475 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
2477 GridPlanes& planes = pln[ iDirZ ];
2478 int iDirX = ( iDirZ + 1 ) % 3;
2479 int iDirY = ( iDirZ + 2 ) % 3;
2480 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
2481 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
2482 planes._zProjs [0] = 0;
2483 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
2484 const vector< double > & u = _grid->_coords[ iDirZ ];
2485 for ( int i = 1; i < planes._zProjs.size(); ++i )
2487 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
2491 const double deflection = _grid->_minCellSize / 20.;
2492 const double tol = _grid->_tol;
2493 E_IntersectPoint ip;
2495 // Intersect EDGEs with the planes
2496 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
2497 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
2499 const TGeomID edgeID = e2fIt->first;
2500 const TopoDS_Edge & E = TopoDS::Edge( _grid->_shapes( edgeID ));
2501 BRepAdaptor_Curve curve( E );
2502 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
2503 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
2505 ip._faceIDs = e2fIt->second;
2506 ip._shapeID = edgeID;
2508 // discretize the EGDE
2509 GCPnts_UniformDeflection discret( curve, deflection, true );
2510 if ( !discret.IsDone() || discret.NbPoints() < 2 )
2513 // perform intersection
2514 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
2516 GridPlanes& planes = pln[ iDirZ ];
2517 int iDirX = ( iDirZ + 1 ) % 3;
2518 int iDirY = ( iDirZ + 2 ) % 3;
2519 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
2520 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
2521 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
2522 int dIJK[3], d000[3] = { 0,0,0 };
2523 double o[3] = { _grid->_coords[0][0],
2524 _grid->_coords[1][0],
2525 _grid->_coords[2][0] };
2527 // locate the 1st point of a segment within the grid
2528 gp_XYZ p1 = discret.Value( 1 ).XYZ();
2529 double u1 = discret.Parameter( 1 );
2530 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
2532 _grid->ComputeUVW( p1, ip._uvw );
2533 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
2534 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
2535 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
2536 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
2537 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
2538 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
2540 int ijk[3]; // grid index where a segment intersect a plane
2545 // add the 1st vertex point to a hexahedron
2549 ip._shapeID = _grid->_shapes.Add( v1 );
2550 _grid->_edgeIntP.push_back( ip );
2551 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2552 _grid->_edgeIntP.pop_back();
2553 ip._shapeID = edgeID;
2555 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
2557 // locate the 2nd point of a segment within the grid
2558 gp_XYZ p2 = discret.Value( iP ).XYZ();
2559 double u2 = discret.Parameter( iP );
2560 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
2562 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
2564 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
2566 // treat intersections with planes between 2 end points of a segment
2567 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
2568 int iZ = iZ1 + ( iZ1 < iZ2 );
2569 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
2571 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
2572 planes._zProjs[ iZ ],
2573 curve, planes._zNorm, _grid->_origin );
2574 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
2575 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2576 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2579 // add ip to hex "above" the plane
2580 _grid->_edgeIntP.push_back( ip );
2582 bool added = addIntersection(_grid->_edgeIntP.back(), hexes, ijk, dIJK);
2584 // add ip to hex "below" the plane
2585 ijk[ iDirZ ] = iZ-1;
2586 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, dIJK ) &&
2588 _grid->_edgeIntP.pop_back();
2596 // add the 2nd vertex point to a hexahedron
2599 ip._shapeID = _grid->_shapes.Add( v2 );
2601 _grid->ComputeUVW( p1, ip._uvw );
2602 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2603 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2605 _grid->_edgeIntP.push_back( ip );
2606 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2607 _grid->_edgeIntP.pop_back();
2608 ip._shapeID = edgeID;
2610 } // loop on 3 grid directions
2615 //================================================================================
2617 * \brief Finds intersection of a curve with a plane
2618 * \param [in] u1 - parameter of one curve point
2619 * \param [in] proj1 - projection of the curve point to the plane normal
2620 * \param [in] u2 - parameter of another curve point
2621 * \param [in] proj2 - projection of the other curve point to the plane normal
2622 * \param [in] proj - projection of a point where the curve intersects the plane
2623 * \param [in] curve - the curve
2624 * \param [in] axis - the plane normal
2625 * \param [in] origin - the plane origin
2626 * \return gp_Pnt - the found intersection point
2628 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
2629 double u2, double proj2,
2631 BRepAdaptor_Curve& curve,
2633 const gp_XYZ& origin)
2635 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
2636 double u = u1 * ( 1 - r ) + u2 * r;
2637 gp_Pnt p = curve.Value( u );
2638 double newProj = axis * ( p.XYZ() - origin );
2639 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
2642 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
2644 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
2649 //================================================================================
2651 * \brief Returns indices of a hexahedron sub-entities holding a point
2652 * \param [in] ip - intersection point
2653 * \param [out] facets - 0-3 facets holding a point
2654 * \param [out] sub - index of a vertex or an edge holding a point
2655 * \return int - number of facets holding a point
2657 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
2659 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
2661 int vertex = 0, egdeMask = 0;
2663 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
2664 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
2667 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
2668 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
2672 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
2673 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
2676 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
2677 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
2681 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
2682 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
2685 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
2686 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
2693 case 0: sub = 0; break;
2694 case 1: sub = facets[0]; break;
2696 const int edge [3][8] = {
2697 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
2698 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
2699 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
2700 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
2701 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
2702 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
2704 switch ( egdeMask ) {
2705 case X | Y: sub = edge[ 0 ][ vertex ]; break;
2706 case X | Z: sub = edge[ 1 ][ vertex ]; break;
2707 default: sub = edge[ 2 ][ vertex ];
2713 sub = vertex + SMESH_Block::ID_FirstV;
2718 //================================================================================
2720 * \brief Adds intersection with an EDGE
2722 bool Hexahedron::addIntersection( const E_IntersectPoint& ip,
2723 vector< Hexahedron* >& hexes,
2724 int ijk[], int dIJK[] )
2728 size_t hexIndex[4] = {
2729 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
2730 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
2731 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
2732 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
2734 for ( int i = 0; i < 4; ++i )
2736 if ( /*0 <= hexIndex[i] &&*/ hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
2738 Hexahedron* h = hexes[ hexIndex[i] ];
2739 // check if ip is really inside the hex
2741 if ( h->isOutParam( ip._uvw ))
2742 throw SALOME_Exception("ip outside a hex");
2744 h->_eIntPoints.push_back( & ip );
2750 //================================================================================
2752 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
2754 bool Hexahedron::findChain( _Node* n1,
2757 vector<_Node*>& chn )
2760 chn.push_back( n1 );
2761 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2762 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2763 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
2764 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2766 chn.push_back( quad._eIntNodes[ iP ]);
2767 chn.push_back( n2 );
2768 quad._eIntNodes[ iP ]->_usedInFace = &quad;
2775 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2776 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2777 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2779 chn.push_back( quad._eIntNodes[ iP ]);
2780 found = quad._eIntNodes[ iP ]->_usedInFace = &quad;
2783 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
2785 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
2786 chn.push_back( n2 );
2788 return chn.size() > 1;
2790 //================================================================================
2792 * \brief Try to heal a polygon whose ends are not connected
2794 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
2796 int i = -1, nbLinks = polygon->_links.size();
2799 vector< _OrientedLink > newLinks;
2800 // find a node lying on the same FACE as the last one
2801 _Node* node = polygon->_links.back().LastNode();
2802 int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
2803 for ( i = nbLinks - 2; i >= 0; --i )
2804 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
2808 for ( ; i < nbLinks; ++i )
2809 newLinks.push_back( polygon->_links[i] );
2813 // find a node lying on the same FACE as the first one
2814 node = polygon->_links[0].FirstNode();
2815 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
2816 for ( i = 1; i < nbLinks; ++i )
2817 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
2820 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
2821 newLinks.push_back( polygon->_links[i] );
2823 if ( newLinks.size() > 1 )
2825 polygon->_links.swap( newLinks );
2827 chainNodes.push_back( polygon->_links.back().LastNode() );
2828 chainNodes.push_back( polygon->_links[0].FirstNode() );
2833 //================================================================================
2835 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
2837 * This function is for a case where an EDGE lies on a quad which lies on a FACE
2838 * so that a part of quad in ON and another part in IN
2840 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
2841 const _OrientedLink& prevSplit,
2842 const _OrientedLink& avoidSplit,
2845 vector<_Node*>& chn )
2847 if ( !isImplementEdges() )
2850 _Node* pn1 = prevSplit.FirstNode();
2851 _Node* pn2 = prevSplit.LastNode();
2852 int avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
2853 if ( avoidFace < 1 && pn1->_intPoint )
2856 _Node* n, *stopNode = avoidSplit.LastNode();
2859 if ( !quad._eIntNodes.empty() )
2861 chn.push_back( pn2 );
2866 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2867 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
2868 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
2869 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
2871 chn.push_back( quad._eIntNodes[ iP ]);
2872 found = quad._eIntNodes[ iP ]->_usedInFace = &quad;
2880 for ( i = splits.size()-1; i >= 0; --i )
2885 n = splits[i].LastNode();
2886 if ( n == stopNode )
2889 ( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2890 ( !avoidFace || n->IsOnFace( avoidFace )))
2893 n = splits[i].FirstNode();
2894 if ( n == stopNode )
2896 if (( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2897 ( !avoidFace || n->IsOnFace( avoidFace )))
2901 if ( n && n != stopNode)
2904 chn.push_back( pn2 );
2911 //================================================================================
2913 * \brief Checks transition at the ginen intersection node of a link
2915 bool Hexahedron::isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const
2919 const bool moreIntPoints = ( iP+1 < link._fIntPoints.size() );
2922 _Node* n1 = link._fIntNodes[ iP ];
2924 n1 = link._nodes[0];
2925 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
2926 if ( !n2 || !n2->Node() )
2927 n2 = link._nodes[1];
2931 // get all FACEs under n1 and n2
2932 set< TGeomID > faceIDs;
2933 if ( moreIntPoints ) faceIDs.insert( link._fIntPoints[iP+1]->_faceIDs.begin(),
2934 link._fIntPoints[iP+1]->_faceIDs.end() );
2935 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
2936 n2->_intPoint->_faceIDs.end() );
2937 if ( faceIDs.empty() )
2938 return false; // n2 is inside
2939 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
2940 n1->_intPoint->_faceIDs.end() );
2941 faceIDs.insert( link._fIntPoints[iP]->_faceIDs.begin(),
2942 link._fIntPoints[iP]->_faceIDs.end() );
2944 // get a point between 2 nodes
2945 gp_Pnt p1 = n1->Point();
2946 gp_Pnt p2 = n2->Point();
2947 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
2949 TopLoc_Location loc;
2951 set< TGeomID >::iterator faceID = faceIDs.begin();
2952 for ( ; faceID != faceIDs.end(); ++faceID )
2954 // project pOnLink on a FACE
2955 if ( *faceID < 1 ) continue;
2956 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( *faceID ));
2957 GeomAPI_ProjectPointOnSurf& proj =
2958 helper.GetProjector( face, loc, 0.1*_grid->_tol );
2959 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
2960 proj.Perform( testPnt );
2961 if ( proj.IsDone() && proj.NbPoints() > 0 )
2963 Quantity_Parameter u,v;
2964 proj.LowerDistanceParameters( u,v );
2966 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
2972 // find isOut by normals
2974 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
2979 if ( face.Orientation() == TopAbs_REVERSED )
2981 gp_Vec v( proj.NearestPoint(), testPnt );
2982 isOut = ( v * normal > 0 );
2987 // classify a projection
2988 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
2990 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
2991 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
2992 if ( state == TopAbs_OUT )
3004 //================================================================================
3006 * \brief Sort nodes on a FACE
3008 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
3010 if ( nodes.size() > 20 ) return;
3012 // get shapes under nodes
3013 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
3014 for ( size_t i = 0; i < nodes.size(); ++i )
3015 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
3018 // get shapes of the FACE
3019 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( faceID ));
3020 list< TopoDS_Edge > edges;
3021 list< int > nbEdges;
3022 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
3024 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
3025 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
3026 list< int >::iterator nE = nbEdges.begin();
3027 for ( ; nbW > 0; ++nE, --nbW )
3029 std::advance( eEnd, *nE );
3030 for ( ; e != eEnd; ++e )
3031 for ( int i = 0; i < 2; ++i )
3034 _grid->_shapes.FindIndex( *e ) :
3035 _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ));
3037 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
3039 edges.erase( eEnd, edges.end() ); // remove rest wires
3040 e = eEnd = edges.end();
3047 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
3050 // rotate edges to have the first one at least partially out of the hexa
3051 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
3052 for ( ; e != edges.end(); ++e )
3054 if ( !_grid->_shapes.FindIndex( *e ))
3059 for ( int i = 0; i < 2 && !isOut; ++i )
3063 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
3064 p = BRep_Tool::Pnt( v );
3066 else if ( eMidOut == edges.end() )
3068 TopLoc_Location loc;
3069 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
3070 if ( c.IsNull() ) break;
3071 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
3078 _grid->ComputeUVW( p.XYZ(), uvw );
3079 if ( isOutParam( uvw ))
3090 if ( e != edges.end() )
3091 edges.splice( edges.end(), edges, edges.begin(), e );
3092 else if ( eMidOut != edges.end() )
3093 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
3095 // sort nodes accoring to the order of edges
3096 _Node* orderNodes [20];
3097 TGeomID orderShapeIDs[20];
3100 for ( e = edges.begin(); e != edges.end(); ++e )
3102 if (( id = _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
3103 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3105 orderShapeIDs[ nbN ] = id;
3106 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3109 if (( id = _grid->_shapes.FindIndex( *e )) &&
3110 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3112 orderShapeIDs[ nbN ] = id;
3113 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3117 if ( nbN != nodes.size() )
3120 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
3121 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
3123 for ( size_t i = 0; i < nodes.size(); ++i )
3124 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
3127 //================================================================================
3129 * \brief Adds computed elements to the mesh
3131 int Hexahedron::addElements(SMESH_MesherHelper& helper)
3134 // add elements resulted from hexahedron intersection
3135 //for ( size_t i = 0; i < _volumeDefs.size(); ++i )
3137 vector< const SMDS_MeshNode* > nodes( _volumeDefs._nodes.size() );
3138 for ( size_t iN = 0; iN < nodes.size(); ++iN )
3139 if ( !( nodes[iN] = _volumeDefs._nodes[iN]->Node() ))
3141 if ( const E_IntersectPoint* eip = _volumeDefs._nodes[iN]->EdgeIntPnt() )
3142 nodes[iN] = _volumeDefs._nodes[iN]->_intPoint->_node =
3143 helper.AddNode( eip->_point.X(),
3147 throw SALOME_Exception("Bug: no node at intersection point");
3150 if ( !_volumeDefs._quantities.empty() )
3152 helper.AddPolyhedralVolume( nodes, _volumeDefs._quantities );
3156 switch ( nodes.size() )
3158 case 8: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
3159 nodes[4],nodes[5],nodes[6],nodes[7] );
3161 case 4: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
3163 case 6: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3], nodes[4],nodes[5] );
3166 helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
3170 nbAdded += int ( _volumeDefs._nodes.size() > 0 );
3175 //================================================================================
3177 * \brief Return true if the element is in a hole
3179 bool Hexahedron::isInHole() const
3181 if ( !_vIntNodes.empty() )
3184 const int ijk[3] = { _i, _j, _k };
3185 F_IntersectPoint curIntPnt;
3187 // consider a cell to be in a hole if all links in any direction
3188 // comes OUT of geometry
3189 for ( int iDir = 0; iDir < 3; ++iDir )
3191 const vector<double>& coords = _grid->_coords[ iDir ];
3192 LineIndexer li = _grid->GetLineIndexer( iDir );
3193 li.SetIJK( _i,_j,_k );
3194 size_t lineIndex[4] = { li.LineIndex (),
3198 bool allLinksOut = true, hasLinks = false;
3199 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
3201 const _Link& link = _hexLinks[ iL + 4*iDir ];
3202 // check transition of the first node of a link
3203 const F_IntersectPoint* firstIntPnt = 0;
3204 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
3206 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0];
3207 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
3208 multiset< F_IntersectPoint >::const_iterator ip =
3209 line._intPoints.upper_bound( curIntPnt );
3211 firstIntPnt = &(*ip);
3213 else if ( !link._fIntPoints.empty() )
3215 firstIntPnt = link._fIntPoints[0];
3221 allLinksOut = ( firstIntPnt->_transition == Trans_OUT );
3224 if ( hasLinks && allLinksOut )
3230 //================================================================================
3232 * \brief Return true if a polyhedron passes _sizeThreshold criterion
3234 bool Hexahedron::checkPolyhedronSize() const
3237 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3239 const _Face& polygon = _polygons[iP];
3240 if ( polygon._links.empty() )
3242 gp_XYZ area (0,0,0);
3243 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
3244 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3246 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
3250 volume += p1 * area;
3254 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
3256 return volume > initVolume / _sizeThreshold;
3258 //================================================================================
3260 * \brief Tries to create a hexahedron
3262 bool Hexahedron::addHexa()
3264 int nbQuad = 0, iQuad = -1;
3265 for ( size_t i = 0; i < _polygons.size(); ++i )
3267 if ( _polygons[i]._links.empty() )
3269 if ( _polygons[i]._links.size() != 4 )
3280 for ( int iL = 0; iL < 4; ++iL )
3283 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
3286 // find a top node above the base node
3287 _Link* link = _polygons[iQuad]._links[iL]._link;
3288 if ( !link->_faces[0] || !link->_faces[1] )
3289 return debugDumpLink( link );
3290 // a quadrangle sharing <link> with _polygons[iQuad]
3291 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
3292 for ( int i = 0; i < 4; ++i )
3293 if ( quad->_links[i]._link == link )
3295 // 1st node of a link opposite to <link> in <quad>
3296 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
3302 _volumeDefs.set( &nodes[0], 8 );
3306 //================================================================================
3308 * \brief Tries to create a tetrahedron
3310 bool Hexahedron::addTetra()
3313 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
3314 if ( _polygons[i]._links.size() == 3 )
3320 nodes[0] = _polygons[iTria]._links[0].FirstNode();
3321 nodes[1] = _polygons[iTria]._links[1].FirstNode();
3322 nodes[2] = _polygons[iTria]._links[2].FirstNode();
3324 _Link* link = _polygons[iTria]._links[0]._link;
3325 if ( !link->_faces[0] || !link->_faces[1] )
3326 return debugDumpLink( link );
3328 // a triangle sharing <link> with _polygons[0]
3329 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
3330 for ( int i = 0; i < 3; ++i )
3331 if ( tria->_links[i]._link == link )
3333 nodes[3] = tria->_links[(i+1)%3].LastNode();
3334 _volumeDefs.set( &nodes[0], 4 );
3340 //================================================================================
3342 * \brief Tries to create a pentahedron
3344 bool Hexahedron::addPenta()
3346 // find a base triangular face
3348 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
3349 if ( _polygons[ iF ]._links.size() == 3 )
3351 if ( iTri < 0 ) return false;
3356 for ( int iL = 0; iL < 3; ++iL )
3359 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
3362 // find a top node above the base node
3363 _Link* link = _polygons[ iTri ]._links[iL]._link;
3364 if ( !link->_faces[0] || !link->_faces[1] )
3365 return debugDumpLink( link );
3366 // a quadrangle sharing <link> with a base triangle
3367 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
3368 if ( quad->_links.size() != 4 ) return false;
3369 for ( int i = 0; i < 4; ++i )
3370 if ( quad->_links[i]._link == link )
3372 // 1st node of a link opposite to <link> in <quad>
3373 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
3379 _volumeDefs.set( &nodes[0], 6 );
3381 return ( nbN == 6 );
3383 //================================================================================
3385 * \brief Tries to create a pyramid
3387 bool Hexahedron::addPyra()
3389 // find a base quadrangle
3391 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
3392 if ( _polygons[ iF ]._links.size() == 4 )
3394 if ( iQuad < 0 ) return false;
3398 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
3399 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
3400 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
3401 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
3403 _Link* link = _polygons[iQuad]._links[0]._link;
3404 if ( !link->_faces[0] || !link->_faces[1] )
3405 return debugDumpLink( link );
3407 // a triangle sharing <link> with a base quadrangle
3408 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
3409 if ( tria->_links.size() != 3 ) return false;
3410 for ( int i = 0; i < 3; ++i )
3411 if ( tria->_links[i]._link == link )
3413 nodes[4] = tria->_links[(i+1)%3].LastNode();
3414 _volumeDefs.set( &nodes[0], 5 );
3420 //================================================================================
3422 * \brief Dump a link and return \c false
3424 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
3427 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
3428 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
3429 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
3430 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
3434 //================================================================================
3436 * \brief Classify a point by grid paremeters
3438 bool Hexahedron::isOutParam(const double uvw[3]) const
3440 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
3441 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
3442 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
3443 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
3444 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
3445 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
3448 //================================================================================
3450 * \brief computes exact bounding box with axes parallel to given ones
3452 //================================================================================
3454 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
3455 const double* axesDirs,
3459 TopoDS_Compound allFacesComp;
3460 b.MakeCompound( allFacesComp );
3461 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
3462 b.Add( allFacesComp, faceVec[ iF ] );
3464 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
3465 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
3467 for ( int i = 0; i < 6; ++i )
3468 farDist = Max( farDist, 10 * sP[i] );
3470 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
3471 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
3472 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
3473 axis[0].Normalize();
3474 axis[1].Normalize();
3475 axis[2].Normalize();
3477 gp_Mat basis( axis[0], axis[1], axis[2] );
3478 gp_Mat bi = basis.Inverted();
3481 for ( int iDir = 0; iDir < 3; ++iDir )
3483 gp_XYZ axis0 = axis[ iDir ];
3484 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
3485 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
3486 for ( int isMax = 0; isMax < 2; ++isMax )
3488 double shift = isMax ? farDist : -farDist;
3489 gp_XYZ orig = shift * axis0;
3490 gp_XYZ norm = axis1 ^ axis2;
3491 gp_Pln pln( orig, norm );
3492 norm = pln.Axis().Direction().XYZ();
3493 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
3495 gp_Pnt& pAxis = isMax ? pMax : pMin;
3496 gp_Pnt pPlane, pFaces;
3497 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
3502 for ( int i = 0; i < 2; ++i ) {
3503 corner.SetCoord( 1, sP[ i*3 ]);
3504 for ( int j = 0; j < 2; ++j ) {
3505 corner.SetCoord( 2, sP[ i*3 + 1 ]);
3506 for ( int k = 0; k < 2; ++k )
3508 corner.SetCoord( 3, sP[ i*3 + 2 ]);
3514 corner = isMax ? bb.CornerMax() : bb.CornerMin();
3515 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
3519 gp_XYZ pf = pFaces.XYZ() * bi;
3520 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
3526 shapeBox.Add( pMin );
3527 shapeBox.Add( pMax );
3534 //=============================================================================
3536 * \brief Generates 3D structured Cartesian mesh in the internal part of
3537 * solid shapes and polyhedral volumes near the shape boundary.
3538 * \param theMesh - mesh to fill in
3539 * \param theShape - a compound of all SOLIDs to mesh
3540 * \retval bool - true in case of success
3542 //=============================================================================
3544 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
3545 const TopoDS_Shape & theShape)
3547 // The algorithm generates the mesh in following steps:
3549 // 1) Intersection of grid lines with the geometry boundary.
3550 // This step allows to find out if a given node of the initial grid is
3551 // inside or outside the geometry.
3553 // 2) For each cell of the grid, check how many of it's nodes are outside
3554 // of the geometry boundary. Depending on a result of this check
3555 // - skip a cell, if all it's nodes are outside
3556 // - skip a cell, if it is too small according to the size threshold
3557 // - add a hexahedron in the mesh, if all nodes are inside
3558 // - add a polyhedron in the mesh, if some nodes are inside and some outside
3560 _computeCanceled = false;
3562 SMESH_MesherHelper helper( theMesh );
3567 grid._helper = &helper;
3569 vector< TopoDS_Shape > faceVec;
3571 TopTools_MapOfShape faceMap;
3572 TopExp_Explorer fExp;
3573 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
3574 if ( !faceMap.Add( fExp.Current() ))
3575 faceMap.Remove( fExp.Current() ); // remove a face shared by two solids
3577 for ( fExp.ReInit(); fExp.More(); fExp.Next() )
3578 if ( faceMap.Contains( fExp.Current() ))
3579 faceVec.push_back( fExp.Current() );
3581 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
3582 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
3583 TopExp_Explorer eExp;
3585 for ( int i = 0; i < faceVec.size(); ++i )
3587 facesItersectors[i]._face = TopoDS::Face ( faceVec[i] );
3588 facesItersectors[i]._faceID = grid._shapes.Add( faceVec[i] );
3589 facesItersectors[i]._grid = &grid;
3590 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
3592 if ( _hyp->GetToAddEdges() )
3594 helper.SetSubShape( faceVec[i] );
3595 for ( eExp.Init( faceVec[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
3597 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
3598 if ( !SMESH_Algo::isDegenerated( edge ) &&
3599 !helper.IsRealSeam( edge ))
3600 edge2faceIDsMap[ grid._shapes.Add( edge )].push_back( facesItersectors[i]._faceID );
3605 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
3607 vector<double> xCoords, yCoords, zCoords;
3608 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
3610 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
3612 if ( _computeCanceled ) return false;
3615 { // copy partner faces and curves of not thread-safe types
3616 set< const Standard_Transient* > tshapes;
3617 BRepBuilderAPI_Copy copier;
3618 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3620 if ( !facesItersectors[i].IsThreadSafe(tshapes) )
3622 copier.Perform( facesItersectors[i]._face );
3623 facesItersectors[i]._face = TopoDS::Face( copier );
3627 // Intersection of grid lines with the geometry boundary.
3628 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
3629 ParallelIntersector( facesItersectors ),
3630 tbb::simple_partitioner());
3632 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3633 facesItersectors[i].Intersect();
3636 // put interesection points onto the GridLine's; this is done after intersection
3637 // to avoid contention of facesItersectors for writing into the same GridLine
3638 // in case of parallel work of facesItersectors
3639 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3640 facesItersectors[i].StoreIntersections();
3642 TopExp_Explorer solidExp (theShape, TopAbs_SOLID);
3643 helper.SetSubShape( solidExp.Current() );
3644 helper.SetElementsOnShape( true );
3646 if ( _computeCanceled ) return false;
3648 // create nodes on the geometry
3649 grid.ComputeNodes(helper);
3651 if ( _computeCanceled ) return false;
3653 // create volume elements
3654 Hexahedron hex( _hyp->GetSizeThreshold(), &grid );
3655 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
3657 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3660 // make all SOLIDs computed
3661 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
3663 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
3664 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
3666 const SMDS_MeshElement* vol = volIt->next();
3667 sm1->RemoveElement( vol, /*isElemDeleted=*/false );
3668 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
3671 // make other sub-shapes computed
3672 setSubmeshesComputed( theMesh, theShape );
3675 // remove free nodes
3676 if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
3678 TIDSortedNodeSet nodesToRemove;
3679 // get intersection nodes
3680 for ( int iDir = 0; iDir < 3; ++iDir )
3682 vector< GridLine >& lines = grid._lines[ iDir ];
3683 for ( size_t i = 0; i < lines.size(); ++i )
3685 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
3686 for ( ; ip != lines[i]._intPoints.end(); ++ip )
3687 if ( ip->_node && ip->_node->NbInverseElements() == 0 )
3688 nodesToRemove.insert( nodesToRemove.end(), ip->_node );
3692 for ( size_t i = 0; i < grid._nodes.size(); ++i )
3693 if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 )
3694 nodesToRemove.insert( nodesToRemove.end(), grid._nodes[i] );
3697 TIDSortedNodeSet::iterator n = nodesToRemove.begin();
3698 for ( ; n != nodesToRemove.end(); ++n )
3699 meshDS->RemoveFreeNode( *n, smDS, /*fromGroups=*/false );
3705 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
3706 catch ( SMESH_ComputeError& e)
3708 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
3713 //=============================================================================
3717 //=============================================================================
3719 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & theMesh,
3720 const TopoDS_Shape & theShape,
3721 MapShapeNbElems& theResMap)
3724 // std::vector<int> aResVec(SMDSEntity_Last);
3725 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
3726 // if(IsQuadratic) {
3727 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3728 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
3729 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
3732 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
3733 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3735 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
3736 // aResMap.insert(std::make_pair(sm,aResVec));
3741 //=============================================================================
3745 * \brief Event listener setting/unsetting _alwaysComputed flag to
3746 * submeshes of inferior levels to prevent their computing
3748 struct _EventListener : public SMESH_subMeshEventListener
3752 _EventListener(const string& algoName):
3753 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
3756 // --------------------------------------------------------------------------------
3757 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
3759 static void setAlwaysComputed( const bool isComputed,
3760 SMESH_subMesh* subMeshOfSolid)
3762 SMESH_subMeshIteratorPtr smIt =
3763 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3764 while ( smIt->more() )
3766 SMESH_subMesh* sm = smIt->next();
3767 sm->SetIsAlwaysComputed( isComputed );
3769 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3772 // --------------------------------------------------------------------------------
3773 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
3775 virtual void ProcessEvent(const int event,
3776 const int eventType,
3777 SMESH_subMesh* subMeshOfSolid,
3778 SMESH_subMeshEventListenerData* data,
3779 const SMESH_Hypothesis* hyp = 0)
3781 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
3783 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
3788 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
3789 if ( !algo3D || _algoName != algo3D->GetName() )
3790 setAlwaysComputed( false, subMeshOfSolid );
3794 // --------------------------------------------------------------------------------
3795 // set the event listener
3797 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
3799 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
3804 }; // struct _EventListener
3808 //================================================================================
3810 * \brief Sets event listener to submeshes if necessary
3811 * \param subMesh - submesh where algo is set
3812 * This method is called when a submesh gets HYP_OK algo_state.
3813 * After being set, event listener is notified on each event of a submesh.
3815 //================================================================================
3817 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
3819 _EventListener::SetOn( subMesh, GetName() );
3822 //================================================================================
3824 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
3826 //================================================================================
3828 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
3829 const TopoDS_Shape& theShape)
3831 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
3832 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));