1 // Copyright (C) 2007-2016 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 //=============================================================================
107 //=============================================================================
109 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, int studyId, SMESH_Gen * gen)
110 :SMESH_3D_Algo(hypId, studyId, gen)
112 _name = "Cartesian_3D";
113 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
114 _compatibleHypothesis.push_back("CartesianParameters3D");
116 _onlyUnaryInput = false; // to mesh all SOLIDs at once
117 _requireDiscreteBoundary = false; // 2D mesh not needed
118 _supportSubmeshes = false; // do not use any existing mesh
121 //=============================================================================
123 * Check presence of a hypothesis
125 //=============================================================================
127 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
128 const TopoDS_Shape& aShape,
129 Hypothesis_Status& aStatus)
131 aStatus = SMESH_Hypothesis::HYP_MISSING;
133 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
134 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
135 if ( h == hyps.end())
140 for ( ; h != hyps.end(); ++h )
142 if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
144 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
149 return aStatus == HYP_OK;
156 //=============================================================================
157 // Definitions of internal utils
158 // --------------------------------------------------------------------------
160 Trans_TANGENT = IntCurveSurface_Tangent,
161 Trans_IN = IntCurveSurface_In,
162 Trans_OUT = IntCurveSurface_Out,
165 // --------------------------------------------------------------------------
167 * \brief Common data of any intersection between a Grid and a shape
169 struct B_IntersectPoint
171 mutable const SMDS_MeshNode* _node;
172 mutable vector< TGeomID > _faceIDs;
174 B_IntersectPoint(): _node(NULL) {}
175 void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
176 int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
177 bool IsOnFace( int faceID ) const;
178 virtual ~B_IntersectPoint() {}
180 // --------------------------------------------------------------------------
182 * \brief Data of intersection between a GridLine and a TopoDS_Face
184 struct F_IntersectPoint : public B_IntersectPoint
187 mutable Transition _transition;
188 mutable size_t _indexOnLine;
190 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
192 // --------------------------------------------------------------------------
194 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
196 struct E_IntersectPoint : public B_IntersectPoint
202 // --------------------------------------------------------------------------
204 * \brief A line of the grid and its intersections with 2D geometry
209 double _length; // line length
210 multiset< F_IntersectPoint > _intPoints;
212 void RemoveExcessIntPoints( const double tol );
213 bool GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut );
215 // --------------------------------------------------------------------------
217 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
222 vector< gp_XYZ > _origins; // origin points of all planes in one direction
223 vector< double > _zProjs; // projections of origins to _zNorm
225 // --------------------------------------------------------------------------
227 * \brief Iterator on the parallel grid lines of one direction
233 size_t _iVar1, _iVar2, _iConst;
234 string _name1, _name2, _nameConst;
236 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
237 size_t iv1, size_t iv2, size_t iConst,
238 const string& nv1, const string& nv2, const string& nConst )
240 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
241 _curInd[0] = _curInd[1] = _curInd[2] = 0;
242 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
243 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
246 size_t I() const { return _curInd[0]; }
247 size_t J() const { return _curInd[1]; }
248 size_t K() const { return _curInd[2]; }
249 void SetIJK( size_t i, size_t j, size_t k )
251 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
255 if ( ++_curInd[_iVar1] == _size[_iVar1] )
256 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
258 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
259 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
260 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
261 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
262 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
263 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
264 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
266 // --------------------------------------------------------------------------
268 * \brief Container of GridLine's
272 vector< double > _coords[3]; // coordinates of grid nodes
273 gp_XYZ _axes [3]; // axis directions
274 vector< GridLine > _lines [3]; // in 3 directions
275 double _tol, _minCellSize;
277 gp_Mat _invB; // inverted basis of _axes
279 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
280 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
282 list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
283 TopTools_IndexedMapOfShape _shapes;
285 SMESH_MesherHelper* _helper;
287 size_t CellIndex( size_t i, size_t j, size_t k ) const
289 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
291 size_t NodeIndex( size_t i, size_t j, size_t k ) const
293 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
295 size_t NodeIndexDX() const { return 1; }
296 size_t NodeIndexDY() const { return _coords[0].size(); }
297 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
299 LineIndexer GetLineIndexer(size_t iDir) const;
301 void SetCoordinates(const vector<double>& xCoords,
302 const vector<double>& yCoords,
303 const vector<double>& zCoords,
304 const double* axesDirs,
305 const Bnd_Box& bndBox );
306 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
307 void ComputeNodes(SMESH_MesherHelper& helper);
309 // --------------------------------------------------------------------------
311 * \brief Intersector of TopoDS_Face with all GridLine's
313 struct FaceGridIntersector
319 IntCurvesFace_Intersector* _surfaceInt;
320 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
322 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
325 void StoreIntersections()
327 for ( size_t i = 0; i < _intersections.size(); ++i )
329 multiset< F_IntersectPoint >::iterator ip =
330 _intersections[i].first->_intPoints.insert( _intersections[i].second );
331 ip->_faceIDs.reserve( 1 );
332 ip->_faceIDs.push_back( _faceID );
335 const Bnd_Box& GetFaceBndBox()
337 GetCurveFaceIntersector();
340 IntCurvesFace_Intersector* GetCurveFaceIntersector()
344 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
345 _bndBox = _surfaceInt->Bounding();
346 if ( _bndBox.IsVoid() )
347 BRepBndLib::Add (_face, _bndBox);
351 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
353 // --------------------------------------------------------------------------
355 * \brief Intersector of a surface with a GridLine
357 struct FaceLineIntersector
360 double _u, _v, _w; // params on the face and the line
361 Transition _transition; // transition of at intersection (see IntCurveSurface.cdl)
362 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
365 gp_Cylinder _cylinder;
369 IntCurvesFace_Intersector* _surfaceInt;
371 vector< F_IntersectPoint > _intPoints;
373 void IntersectWithPlane (const GridLine& gridLine);
374 void IntersectWithCylinder(const GridLine& gridLine);
375 void IntersectWithCone (const GridLine& gridLine);
376 void IntersectWithSphere (const GridLine& gridLine);
377 void IntersectWithTorus (const GridLine& gridLine);
378 void IntersectWithSurface (const GridLine& gridLine);
380 bool UVIsOnFace() const;
381 void addIntPoint(const bool toClassify=true);
382 bool isParamOnLineOK( const double linLength )
384 return -_tol < _w && _w < linLength + _tol;
386 FaceLineIntersector():_surfaceInt(0) {}
387 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
389 // --------------------------------------------------------------------------
391 * \brief Class representing topology of the hexahedron and creating a mesh
392 * volume basing on analysis of hexahedron intersection with geometry
396 // --------------------------------------------------------------------------------
399 // --------------------------------------------------------------------------------
400 struct _Node //!< node either at a hexahedron corner or at intersection
402 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
403 const B_IntersectPoint* _intPoint;
404 const _Face* _usedInFace;
406 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
407 :_node(n), _intPoint(ip), _usedInFace(0) {}
408 const SMDS_MeshNode* Node() const
409 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
410 const E_IntersectPoint* EdgeIntPnt() const
411 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
412 bool IsUsedInFace( const _Face* polygon = 0 )
414 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
416 void Add( const E_IntersectPoint* ip )
421 else if ( !_intPoint->_node ) {
422 ip->Add( _intPoint->_faceIDs );
426 _intPoint->Add( ip->_faceIDs );
429 TGeomID IsLinked( const B_IntersectPoint* other,
430 TGeomID avoidFace=-1 ) const // returns id of a common face
432 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
434 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
436 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
440 if ( const SMDS_MeshNode* n = Node() )
441 return SMESH_TNodeXYZ( n );
442 if ( const E_IntersectPoint* eip =
443 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
445 return gp_Pnt( 1e100, 0, 0 );
447 TGeomID ShapeID() const
449 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
450 return eip->_shapeID;
454 // --------------------------------------------------------------------------------
455 struct _Link // link connecting two _Node's
458 _Face* _faces[2]; // polygons sharing a link
459 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
460 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
461 vector< _Link > _splits;
462 _Link() { _faces[0] = 0; }
464 // --------------------------------------------------------------------------------
469 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
470 void Reverse() { _reverse = !_reverse; }
471 int NbResultLinks() const { return _link->_splits.size(); }
472 _OrientedLink ResultLink(int i) const
474 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
476 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
477 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
478 operator bool() const { return _link; }
479 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
481 vector< TGeomID > faces;
482 const B_IntersectPoint *ip0, *ip1;
483 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
484 ( ip1 = _link->_nodes[1]->_intPoint ))
486 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
487 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
488 !usedIDs.count( ip0->_faceIDs[i] ) )
489 faces.push_back( ip0->_faceIDs[i] );
493 bool HasEdgeNodes() const
495 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
496 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
500 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
502 void AddFace( _Face* f )
504 if ( _link->_faces[0] )
506 _link->_faces[1] = f;
510 _link->_faces[0] = f;
511 _link->_faces[1] = 0;
514 void RemoveFace( _Face* f )
516 if ( !_link->_faces[0] ) return;
518 if ( _link->_faces[1] == f )
520 _link->_faces[1] = 0;
522 else if ( _link->_faces[0] == f )
524 _link->_faces[0] = 0;
525 if ( _link->_faces[1] )
527 _link->_faces[0] = _link->_faces[1];
528 _link->_faces[1] = 0;
533 // --------------------------------------------------------------------------------
536 vector< _OrientedLink > _links; // links on GridLine's
537 vector< _Link > _polyLinks; // links added to close a polygonal face
538 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
539 bool IsPolyLink( const _OrientedLink& ol )
541 return _polyLinks.empty() ? false :
542 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
544 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
546 if ( faceToFindEqual && faceToFindEqual != this ) {
547 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
548 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
549 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
552 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
559 _polyLinks.push_back( l );
560 _links.push_back( _OrientedLink( &_polyLinks.back() ));
563 // --------------------------------------------------------------------------------
564 struct _volumeDef // holder of nodes of a volume mesh element
566 vector< _Node* > _nodes;
567 vector< int > _quantities;
568 typedef boost::shared_ptr<_volumeDef> Ptr;
569 void set( const vector< _Node* >& nodes,
570 const vector< int >& quant = vector< int >() )
571 { _nodes = nodes; _quantities = quant; }
572 void set( _Node** nodes, int nb )
573 { _nodes.assign( nodes, nodes + nb ); }
576 // topology of a hexahedron
579 _Link _hexLinks [12];
582 // faces resulted from hexahedron intersection
583 vector< _Face > _polygons;
585 // intresections with EDGEs
586 vector< const E_IntersectPoint* > _eIntPoints;
588 // additional nodes created at intersection points
589 vector< _Node > _intNodes;
591 // nodes inside the hexahedron (at VERTEXes)
592 vector< _Node* > _vIntNodes;
594 // computed volume elements
595 //vector< _volumeDef::Ptr > _volumeDefs;
596 _volumeDef _volumeDefs;
599 double _sizeThreshold, _sideLength[3];
600 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
601 int _origNodeInd; // index of _hexNodes[0] node within the _grid
605 Hexahedron(const double sizeThreshold, Grid* grid);
606 int MakeElements(SMESH_MesherHelper& helper,
607 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
608 void ComputeElements();
609 void Init() { init( _i, _j, _k ); }
612 Hexahedron(const Hexahedron& other );
613 void init( size_t i, size_t j, size_t k );
614 void init( size_t i );
615 void addEdges(SMESH_MesherHelper& helper,
616 vector< Hexahedron* >& intersectedHex,
617 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
618 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
619 double proj, BRepAdaptor_Curve& curve,
620 const gp_XYZ& axis, const gp_XYZ& origin );
621 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
622 bool addIntersection( const E_IntersectPoint& ip,
623 vector< Hexahedron* >& hexes,
624 int ijk[], int dIJK[] );
625 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
626 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
627 bool findChainOnEdge( const vector< _OrientedLink >& splits,
628 const _OrientedLink& prevSplit,
629 const _OrientedLink& avoidSplit,
632 vector<_Node*>& chn);
633 int addElements(SMESH_MesherHelper& helper);
634 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const;
635 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
636 bool isInHole() const;
637 bool checkPolyhedronSize() const;
642 bool debugDumpLink( _Link* link );
643 _Node* findEqualNode( vector< _Node* >& nodes,
644 const E_IntersectPoint* ip,
647 for ( size_t i = 0; i < nodes.size(); ++i )
648 if ( nodes[i]->EdgeIntPnt() == ip ||
649 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
653 bool isImplementEdges() const { return !_grid->_edgeIntP.empty(); }
654 bool isOutParam(const double uvw[3]) const;
658 // --------------------------------------------------------------------------
660 * \brief Hexahedron computing volumes in one thread
662 struct ParallelHexahedron
664 vector< Hexahedron* >& _hexVec;
665 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
666 void operator() ( const tbb::blocked_range<size_t>& r ) const
668 for ( size_t i = r.begin(); i != r.end(); ++i )
669 if ( Hexahedron* hex = _hexVec[ i ] )
670 hex->ComputeElements();
673 // --------------------------------------------------------------------------
675 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
677 struct ParallelIntersector
679 vector< FaceGridIntersector >& _faceVec;
680 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
681 void operator() ( const tbb::blocked_range<size_t>& r ) const
683 for ( size_t i = r.begin(); i != r.end(); ++i )
684 _faceVec[i].Intersect();
689 //=============================================================================
690 // Implementation of internal utils
691 //=============================================================================
693 * \brief adjust \a i to have \a val between values[i] and values[i+1]
695 inline void locateValue( int & i, double val, const vector<double>& values,
696 int& di, double tol )
698 //val += values[0]; // input \a val is measured from 0.
699 if ( i > (int) values.size()-2 )
702 while ( i+2 < (int) values.size() && val > values[ i+1 ])
704 while ( i > 0 && val < values[ i ])
707 if ( i > 0 && val - values[ i ] < tol )
709 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
714 //=============================================================================
716 * Remove coincident intersection points
718 void GridLine::RemoveExcessIntPoints( const double tol )
720 if ( _intPoints.size() < 2 ) return;
722 set< Transition > tranSet;
723 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
724 while ( ip2 != _intPoints.end() )
728 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
730 tranSet.insert( ip1->_transition );
731 tranSet.insert( ip2->_transition );
732 ip2->Add( ip1->_faceIDs );
733 _intPoints.erase( ip1 );
736 if ( tranSet.size() > 1 ) // points with different transition coincide
738 bool isIN = tranSet.count( Trans_IN );
739 bool isOUT = tranSet.count( Trans_OUT );
741 (*ip1)._transition = Trans_TANGENT;
743 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
747 //================================================================================
749 * Return "is OUT" state for nodes before the given intersection point
751 bool GridLine::GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut )
753 if ( ip->_transition == Trans_IN )
755 if ( ip->_transition == Trans_OUT )
757 if ( ip->_transition == Trans_APEX )
759 // singularity point (apex of a cone)
760 if ( _intPoints.size() == 1 || ip == _intPoints.begin() )
762 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
763 if ( ipAft == _intPoints.end() )
766 if ( ipBef->_transition != ipAft->_transition )
767 return ( ipBef->_transition == Trans_OUT );
768 return ( ipBef->_transition != Trans_OUT );
770 // _transition == Trans_TANGENT
773 //================================================================================
777 void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
778 const SMDS_MeshNode* n) const
780 if ( _faceIDs.empty() )
783 for ( size_t i = 0; i < fIDs.size(); ++i )
785 vector< TGeomID >::iterator it =
786 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
787 if ( it == _faceIDs.end() )
788 _faceIDs.push_back( fIDs[i] );
793 //================================================================================
795 * Returns index of a common face if any, else zero
797 int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
800 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
801 if ( avoidFace != other->_faceIDs[i] &&
802 IsOnFace ( other->_faceIDs[i] ))
803 return other->_faceIDs[i];
806 //================================================================================
808 * Returns \c true if \a faceID in in this->_faceIDs
810 bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
812 vector< TGeomID >::const_iterator it =
813 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
814 return ( it != _faceIDs.end() );
816 //================================================================================
818 * Return an iterator on GridLine's in a given direction
820 LineIndexer Grid::GetLineIndexer(size_t iDir) const
822 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
823 const string s [] = { "X", "Y", "Z" };
824 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
825 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
826 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
829 //=============================================================================
831 * Creates GridLine's of the grid
833 void Grid::SetCoordinates(const vector<double>& xCoords,
834 const vector<double>& yCoords,
835 const vector<double>& zCoords,
836 const double* axesDirs,
837 const Bnd_Box& shapeBox)
839 _coords[0] = xCoords;
840 _coords[1] = yCoords;
841 _coords[2] = zCoords;
843 _axes[0].SetCoord( axesDirs[0],
846 _axes[1].SetCoord( axesDirs[3],
849 _axes[2].SetCoord( axesDirs[6],
852 _axes[0].Normalize();
853 _axes[1].Normalize();
854 _axes[2].Normalize();
856 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
860 _minCellSize = Precision::Infinite();
861 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
863 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
865 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
866 if ( cellLen < _minCellSize )
867 _minCellSize = cellLen;
870 if ( _minCellSize < Precision::Confusion() )
871 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
872 SMESH_Comment("Too small cell size: ") << _minCellSize );
873 _tol = _minCellSize / 1000.;
875 // attune grid extremities to shape bounding box
877 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
878 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
879 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
880 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
881 for ( int i = 0; i < 6; ++i )
882 if ( fabs( sP[i] - *cP[i] ) < _tol )
883 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
885 for ( int iDir = 0; iDir < 3; ++iDir )
887 if ( _coords[iDir][0] - sP[iDir] > _tol )
889 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
890 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
892 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
894 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
895 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
898 _tol = _minCellSize / 1000.;
900 _origin = ( _coords[0][0] * _axes[0] +
901 _coords[1][0] * _axes[1] +
902 _coords[2][0] * _axes[2] );
905 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
907 LineIndexer li = GetLineIndexer( iDir );
908 _lines[iDir].resize( li.NbLines() );
909 double len = _coords[ iDir ].back() - _coords[iDir].front();
910 for ( ; li.More(); ++li )
912 GridLine& gl = _lines[iDir][ li.LineIndex() ];
913 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
914 _coords[1][li.J()] * _axes[1] +
915 _coords[2][li.K()] * _axes[2] );
916 gl._line.SetDirection( _axes[ iDir ]);
921 //================================================================================
923 * Computes coordinates of a point in the grid CS
925 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
927 gp_XYZ p = P * _invB;
928 p.Coord( UVW[0], UVW[1], UVW[2] );
930 //================================================================================
934 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
936 // state of each node of the grid relative to the geometry
937 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
938 vector< bool > isNodeOut( nbGridNodes, false );
939 _nodes.resize( nbGridNodes, 0 );
940 _gridIntP.resize( nbGridNodes, NULL );
942 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
944 LineIndexer li = GetLineIndexer( iDir );
946 // find out a shift of node index while walking along a GridLine in this direction
947 li.SetIndexOnLine( 0 );
948 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
949 li.SetIndexOnLine( 1 );
950 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
952 const vector<double> & coords = _coords[ iDir ];
953 for ( ; li.More(); ++li ) // loop on lines in iDir
955 li.SetIndexOnLine( 0 );
956 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
958 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
959 const gp_XYZ lineLoc = line._line.Location().XYZ();
960 const gp_XYZ lineDir = line._line.Direction().XYZ();
961 line.RemoveExcessIntPoints( _tol );
962 multiset< F_IntersectPoint >& intPnts = line._intPoints;
963 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
966 const double* nodeCoord = & coords[0];
967 const double* coord0 = nodeCoord;
968 const double* coordEnd = coord0 + coords.size();
969 double nodeParam = 0;
970 for ( ; ip != intPnts.end(); ++ip )
972 // set OUT state or just skip IN nodes before ip
973 if ( nodeParam < ip->_paramOnLine - _tol )
975 isOut = line.GetIsOutBefore( ip, isOut );
977 while ( nodeParam < ip->_paramOnLine - _tol )
980 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = isOut;
981 if ( ++nodeCoord < coordEnd )
982 nodeParam = *nodeCoord - *coord0;
986 if ( nodeCoord == coordEnd ) break;
988 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
989 if ( nodeParam > ip->_paramOnLine + _tol )
991 // li.SetIndexOnLine( 0 );
992 // double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
993 // xyz[ li._iConst ] += ip->_paramOnLine;
994 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
995 ip->_node = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
996 ip->_indexOnLine = nodeCoord-coord0-1;
998 // create a mesh node at ip concident with a grid node
1001 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1002 if ( !_nodes[ nodeIndex ] )
1004 //li.SetIndexOnLine( nodeCoord-coord0 );
1005 //double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1006 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1007 _nodes [ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1008 _gridIntP[ nodeIndex ] = & * ip;
1010 if ( _gridIntP[ nodeIndex ] )
1011 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1013 _gridIntP[ nodeIndex ] = & * ip;
1014 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1015 ip->_indexOnLine = nodeCoord-coord0;
1016 if ( ++nodeCoord < coordEnd )
1017 nodeParam = *nodeCoord - *coord0;
1020 // set OUT state to nodes after the last ip
1021 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1022 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = true;
1026 // Create mesh nodes at !OUT nodes of the grid
1028 for ( size_t z = 0; z < _coords[2].size(); ++z )
1029 for ( size_t y = 0; y < _coords[1].size(); ++y )
1030 for ( size_t x = 0; x < _coords[0].size(); ++x )
1032 size_t nodeIndex = NodeIndex( x, y, z );
1033 if ( !isNodeOut[ nodeIndex ] && !_nodes[ nodeIndex] )
1035 //_nodes[ nodeIndex ] = helper.AddNode( _coords[0][x], _coords[1][y], _coords[2][z] );
1036 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1037 _coords[1][y] * _axes[1] +
1038 _coords[2][z] * _axes[2] );
1039 _nodes[ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1044 // check validity of transitions
1045 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1046 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1048 LineIndexer li = GetLineIndexer( iDir );
1049 for ( ; li.More(); ++li )
1051 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1052 if ( intPnts.empty() ) continue;
1053 if ( intPnts.size() == 1 )
1055 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1056 intPnts.begin()->_transition != Trans_APEX )
1057 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1058 SMESH_Comment("Wrong SOLE transition of GridLine (")
1059 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1060 << ") along " << li._nameConst
1061 << ": " << trName[ intPnts.begin()->_transition] );
1065 if ( intPnts.begin()->_transition == Trans_OUT )
1066 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1067 SMESH_Comment("Wrong START transition of GridLine (")
1068 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1069 << ") along " << li._nameConst
1070 << ": " << trName[ intPnts.begin()->_transition ]);
1071 if ( intPnts.rbegin()->_transition == Trans_IN )
1072 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1073 SMESH_Comment("Wrong END transition of GridLine (")
1074 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1075 << ") along " << li._nameConst
1076 << ": " << trName[ intPnts.rbegin()->_transition ]);
1083 //=============================================================================
1085 * Intersects TopoDS_Face with all GridLine's
1087 void FaceGridIntersector::Intersect()
1089 FaceLineIntersector intersector;
1090 intersector._surfaceInt = GetCurveFaceIntersector();
1091 intersector._tol = _grid->_tol;
1092 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1093 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1095 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1096 PIntFun interFunction;
1098 bool isDirect = true;
1099 BRepAdaptor_Surface surf( _face );
1100 switch ( surf.GetType() ) {
1102 intersector._plane = surf.Plane();
1103 interFunction = &FaceLineIntersector::IntersectWithPlane;
1104 isDirect = intersector._plane.Direct();
1106 case GeomAbs_Cylinder:
1107 intersector._cylinder = surf.Cylinder();
1108 interFunction = &FaceLineIntersector::IntersectWithCylinder;
1109 isDirect = intersector._cylinder.Direct();
1112 intersector._cone = surf.Cone();
1113 interFunction = &FaceLineIntersector::IntersectWithCone;
1114 //isDirect = intersector._cone.Direct();
1116 case GeomAbs_Sphere:
1117 intersector._sphere = surf.Sphere();
1118 interFunction = &FaceLineIntersector::IntersectWithSphere;
1119 isDirect = intersector._sphere.Direct();
1122 intersector._torus = surf.Torus();
1123 interFunction = &FaceLineIntersector::IntersectWithTorus;
1124 //isDirect = intersector._torus.Direct();
1127 interFunction = &FaceLineIntersector::IntersectWithSurface;
1130 std::swap( intersector._transOut, intersector._transIn );
1132 _intersections.clear();
1133 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1135 if ( surf.GetType() == GeomAbs_Plane )
1137 // check if all lines in this direction are parallel to a plane
1138 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1139 Precision::Angular()))
1141 // find out a transition, that is the same for all lines of a direction
1142 gp_Dir plnNorm = intersector._plane.Axis().Direction();
1143 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1144 intersector._transition =
1145 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1147 if ( surf.GetType() == GeomAbs_Cylinder )
1149 // check if all lines in this direction are parallel to a cylinder
1150 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1151 Precision::Angular()))
1155 // intersect the grid lines with the face
1156 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1158 GridLine& gridLine = _grid->_lines[iDir][iL];
1159 if ( _bndBox.IsOut( gridLine._line )) continue;
1161 intersector._intPoints.clear();
1162 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1163 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1164 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1168 //================================================================================
1170 * Return true if (_u,_v) is on the face
1172 bool FaceLineIntersector::UVIsOnFace() const
1174 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1175 return ( state == TopAbs_IN || state == TopAbs_ON );
1177 //================================================================================
1179 * Store an intersection if it is IN or ON the face
1181 void FaceLineIntersector::addIntPoint(const bool toClassify)
1183 if ( !toClassify || UVIsOnFace() )
1186 p._paramOnLine = _w;
1187 p._transition = _transition;
1188 _intPoints.push_back( p );
1191 //================================================================================
1193 * Intersect a line with a plane
1195 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
1197 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1198 _w = linPlane.ParamOnConic(1);
1199 if ( isParamOnLineOK( gridLine._length ))
1201 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1205 //================================================================================
1207 * Intersect a line with a cylinder
1209 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1211 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1212 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1214 _w = linCylinder.ParamOnConic(1);
1215 if ( linCylinder.NbPoints() == 1 )
1216 _transition = Trans_TANGENT;
1218 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1219 if ( isParamOnLineOK( gridLine._length ))
1221 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1224 if ( linCylinder.NbPoints() > 1 )
1226 _w = linCylinder.ParamOnConic(2);
1227 if ( isParamOnLineOK( gridLine._length ))
1229 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1230 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1236 //================================================================================
1238 * Intersect a line with a cone
1240 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1242 IntAna_IntConicQuad linCone(gridLine._line,_cone);
1243 if ( !linCone.IsDone() ) return;
1245 gp_Vec du, dv, norm;
1246 for ( int i = 1; i <= linCone.NbPoints(); ++i )
1248 _w = linCone.ParamOnConic( i );
1249 if ( !isParamOnLineOK( gridLine._length )) continue;
1250 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1253 ElSLib::D1( _u, _v, _cone, P, du, dv );
1255 double normSize2 = norm.SquareMagnitude();
1256 if ( normSize2 > Precision::Angular() * Precision::Angular() )
1258 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1259 cos /= sqrt( normSize2 );
1260 if ( cos < -Precision::Angular() )
1261 _transition = _transIn;
1262 else if ( cos > Precision::Angular() )
1263 _transition = _transOut;
1265 _transition = Trans_TANGENT;
1269 _transition = Trans_APEX;
1271 addIntPoint( /*toClassify=*/false);
1275 //================================================================================
1277 * Intersect a line with a sphere
1279 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
1281 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1282 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1284 _w = linSphere.ParamOnConic(1);
1285 if ( linSphere.NbPoints() == 1 )
1286 _transition = Trans_TANGENT;
1288 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1289 if ( isParamOnLineOK( gridLine._length ))
1291 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1294 if ( linSphere.NbPoints() > 1 )
1296 _w = linSphere.ParamOnConic(2);
1297 if ( isParamOnLineOK( gridLine._length ))
1299 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
1300 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1306 //================================================================================
1308 * Intersect a line with a torus
1310 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
1312 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
1313 if ( !linTorus.IsDone()) return;
1315 gp_Vec du, dv, norm;
1316 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
1318 _w = linTorus.ParamOnLine( i );
1319 if ( !isParamOnLineOK( gridLine._length )) continue;
1320 linTorus.ParamOnTorus( i, _u,_v );
1323 ElSLib::D1( _u, _v, _torus, P, du, dv );
1325 double normSize = norm.Magnitude();
1326 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1328 if ( cos < -Precision::Angular() )
1329 _transition = _transIn;
1330 else if ( cos > Precision::Angular() )
1331 _transition = _transOut;
1333 _transition = Trans_TANGENT;
1334 addIntPoint( /*toClassify=*/false);
1338 //================================================================================
1340 * Intersect a line with a non-analytical surface
1342 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
1344 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
1345 if ( !_surfaceInt->IsDone() ) return;
1346 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
1348 _transition = Transition( _surfaceInt->Transition( i ) );
1349 _w = _surfaceInt->WParameter( i );
1350 addIntPoint(/*toClassify=*/false);
1353 //================================================================================
1355 * check if its face can be safely intersected in a thread
1357 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
1362 TopLoc_Location loc;
1363 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
1364 Handle(Geom_RectangularTrimmedSurface) ts =
1365 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
1366 while( !ts.IsNull() ) {
1367 surf = ts->BasisSurface();
1368 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
1370 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
1371 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
1372 #if OCC_VERSION_MAJOR < 7
1373 if ( !noSafeTShapes.insert((const Standard_Transient*) _face.TShape() ).second )
1375 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
1380 TopExp_Explorer exp( _face, TopAbs_EDGE );
1381 for ( ; exp.More(); exp.Next() )
1383 bool edgeIsSafe = true;
1384 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1387 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
1390 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1391 while( !tc.IsNull() ) {
1392 c = tc->BasisCurve();
1393 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1395 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
1396 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
1403 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
1406 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1407 while( !tc.IsNull() ) {
1408 c2 = tc->BasisCurve();
1409 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1411 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
1412 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
1416 #if OCC_VERSION_MAJOR < 7
1417 if ( !edgeIsSafe && !noSafeTShapes.insert((const Standard_Transient*) e.TShape() ).second )
1419 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
1425 //================================================================================
1427 * \brief Creates topology of the hexahedron
1429 Hexahedron::Hexahedron(const double sizeThreshold, Grid* grid)
1430 : _grid( grid ), _sizeThreshold( sizeThreshold ), _nbFaceIntNodes(0)
1432 _polygons.reserve(100); // to avoid reallocation;
1434 //set nodes shift within grid->_nodes from the node 000
1435 size_t dx = _grid->NodeIndexDX();
1436 size_t dy = _grid->NodeIndexDY();
1437 size_t dz = _grid->NodeIndexDZ();
1439 size_t i100 = i000 + dx;
1440 size_t i010 = i000 + dy;
1441 size_t i110 = i010 + dx;
1442 size_t i001 = i000 + dz;
1443 size_t i101 = i100 + dz;
1444 size_t i011 = i010 + dz;
1445 size_t i111 = i110 + dz;
1446 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
1447 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
1448 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
1449 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
1450 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
1451 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
1452 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
1453 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
1455 vector< int > idVec;
1456 // set nodes to links
1457 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
1459 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
1460 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
1461 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
1462 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
1465 // set links to faces
1466 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
1467 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
1469 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
1470 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
1471 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
1472 faceID == SMESH_Block::ID_Fx1z ||
1473 faceID == SMESH_Block::ID_F0yz );
1474 quad._links.resize(4);
1475 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
1476 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
1477 for ( int i = 0; i < 4; ++i )
1479 bool revLink = revFace;
1480 if ( i > 1 ) // reverse links u1 and v0
1482 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
1483 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
1488 //================================================================================
1490 * \brief Copy constructor
1492 Hexahedron::Hexahedron( const Hexahedron& other )
1493 :_grid( other._grid ), _sizeThreshold( other._sizeThreshold ), _nbFaceIntNodes(0)
1495 _polygons.reserve(100); // to avoid reallocation;
1497 for ( int i = 0; i < 8; ++i )
1498 _nodeShift[i] = other._nodeShift[i];
1500 for ( int i = 0; i < 12; ++i )
1502 const _Link& srcLink = other._hexLinks[ i ];
1503 _Link& tgtLink = this->_hexLinks[ i ];
1504 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
1505 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
1508 for ( int i = 0; i < 6; ++i )
1510 const _Face& srcQuad = other._hexQuads[ i ];
1511 _Face& tgtQuad = this->_hexQuads[ i ];
1512 tgtQuad._links.resize(4);
1513 for ( int j = 0; j < 4; ++j )
1515 const _OrientedLink& srcLink = srcQuad._links[ j ];
1516 _OrientedLink& tgtLink = tgtQuad._links[ j ];
1517 tgtLink._reverse = srcLink._reverse;
1518 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
1523 //================================================================================
1525 * \brief Initializes its data by given grid cell
1527 void Hexahedron::init( size_t i, size_t j, size_t k )
1529 _i = i; _j = j; _k = k;
1530 // set nodes of grid to nodes of the hexahedron and
1531 // count nodes at hexahedron corners located IN and ON geometry
1532 _nbCornerNodes = _nbBndNodes = 0;
1533 _origNodeInd = _grid->NodeIndex( i,j,k );
1534 for ( int iN = 0; iN < 8; ++iN )
1536 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _nodeShift[iN] ];
1537 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _nodeShift[iN] ];
1538 _nbCornerNodes += bool( _hexNodes[iN]._node );
1539 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
1541 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
1542 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
1543 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
1548 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
1549 _nbFaceIntNodes + _nbCornerNodes + _eIntPoints.size() > 3)
1551 _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
1553 // this method can be called in parallel, so use own helper
1554 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
1556 // create sub-links (_splits) by splitting links with _fIntPoints
1558 for ( int iLink = 0; iLink < 12; ++iLink )
1560 _Link& link = _hexLinks[ iLink ];
1561 link._fIntNodes.resize( link._fIntPoints.size() );
1562 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
1564 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
1565 link._fIntNodes[ i ] = & _intNodes.back();
1568 link._splits.clear();
1569 split._nodes[ 0 ] = link._nodes[0];
1570 bool isOut = ( ! link._nodes[0]->Node() );
1571 bool checkTransition;
1572 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
1574 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
1575 if ( !isGridNode ) // intersection non-coincident with a grid node
1577 if ( split._nodes[ 0 ]->Node() && !isOut )
1579 split._nodes[ 1 ] = link._fIntNodes[i];
1580 link._splits.push_back( split );
1582 split._nodes[ 0 ] = link._fIntNodes[i];
1583 checkTransition = true;
1585 else // FACE intersection coincident with a grid node (at link ends)
1587 checkTransition = ( i == 0 && link._nodes[0]->Node() );
1589 if ( checkTransition )
1591 if ( link._fIntPoints[i]->_faceIDs.size() > 1 || _eIntPoints.size() > 0 )
1592 isOut = isOutPoint( link, i, helper );
1594 switch ( link._fIntPoints[i]->_transition ) {
1595 case Trans_OUT: isOut = true; break;
1596 case Trans_IN : isOut = false; break;
1598 isOut = isOutPoint( link, i, helper );
1602 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
1604 split._nodes[ 1 ] = link._nodes[1];
1605 link._splits.push_back( split );
1609 // Create _Node's at intersections with EDGEs.
1611 const double tol2 = _grid->_tol * _grid->_tol;
1612 int facets[3], nbFacets, subEntity;
1614 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
1616 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
1617 _Node* equalNode = 0;
1618 switch( nbFacets ) {
1619 case 1: // in a _Face
1621 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
1622 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1624 equalNode->Add( _eIntPoints[ iP ] );
1627 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1628 quad._eIntNodes.push_back( & _intNodes.back() );
1632 case 2: // on a _Link
1634 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
1635 if ( link._splits.size() > 0 )
1637 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
1639 equalNode->Add( _eIntPoints[ iP ] );
1643 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1644 for ( int iF = 0; iF < 2; ++iF )
1646 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1647 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1649 equalNode->Add( _eIntPoints[ iP ] );
1652 quad._eIntNodes.push_back( & _intNodes.back() );
1658 case 3: // at a corner
1660 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
1661 if ( node.Node() > 0 )
1663 if ( node._intPoint )
1664 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
1668 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1669 for ( int iF = 0; iF < 3; ++iF )
1671 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1672 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1674 equalNode->Add( _eIntPoints[ iP ] );
1677 quad._eIntNodes.push_back( & _intNodes.back() );
1683 } // switch( nbFacets )
1685 if ( nbFacets == 0 ||
1686 _grid->_shapes( _eIntPoints[ iP ]->_shapeID ).ShapeType() == TopAbs_VERTEX )
1688 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
1690 equalNode->Add( _eIntPoints[ iP ] );
1692 else if ( nbFacets == 0 ) {
1693 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
1694 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1695 _vIntNodes.push_back( & _intNodes.back() );
1698 } // loop on _eIntPoints
1700 else if ( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) // _nbFaceIntNodes == 0
1703 // create sub-links (_splits) of whole links
1704 for ( int iLink = 0; iLink < 12; ++iLink )
1706 _Link& link = _hexLinks[ iLink ];
1707 link._splits.clear();
1708 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
1710 split._nodes[ 0 ] = link._nodes[0];
1711 split._nodes[ 1 ] = link._nodes[1];
1712 link._splits.push_back( split );
1718 //================================================================================
1720 * \brief Initializes its data by given grid cell (countered from zero)
1722 void Hexahedron::init( size_t iCell )
1724 size_t iNbCell = _grid->_coords[0].size() - 1;
1725 size_t jNbCell = _grid->_coords[1].size() - 1;
1726 _i = iCell % iNbCell;
1727 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
1728 _k = iCell / iNbCell / jNbCell;
1732 //================================================================================
1734 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
1736 void Hexahedron::ComputeElements()
1740 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
1741 if ( _nbCornerNodes + nbIntersections < 4 )
1744 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
1748 _polygons.reserve( 20 );
1750 // Create polygons from quadrangles
1751 // --------------------------------
1753 vector< _OrientedLink > splits;
1754 vector<_Node*> chainNodes;
1755 _Face* coplanarPolyg;
1757 bool hasEdgeIntersections = !_eIntPoints.empty();
1759 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
1761 _Face& quad = _hexQuads[ iF ] ;
1763 _polygons.resize( _polygons.size() + 1 );
1764 _Face* polygon = &_polygons.back();
1765 polygon->_polyLinks.reserve( 20 );
1768 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
1769 for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
1770 splits.push_back( quad._links[ iE ].ResultLink( iS ));
1772 // add splits of links to a polygon and add _polyLinks to make
1773 // polygon's boundary closed
1775 int nbSplits = splits.size();
1776 if (( nbSplits == 1 ) &&
1777 ( quad._eIntNodes.empty() ||
1778 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
1779 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
1783 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
1784 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
1785 quad._eIntNodes[ iP ]->_usedInFace = 0;
1787 size_t nbUsedEdgeNodes = 0;
1788 _Face* prevPolyg = 0; // polygon previously created from this quad
1790 while ( nbSplits > 0 )
1793 while ( !splits[ iS ] )
1796 if ( !polygon->_links.empty() )
1798 _polygons.resize( _polygons.size() + 1 );
1799 polygon = &_polygons.back();
1800 polygon->_polyLinks.reserve( 20 );
1802 polygon->_links.push_back( splits[ iS ] );
1803 splits[ iS++ ]._link = 0;
1806 _Node* nFirst = polygon->_links.back().FirstNode();
1807 _Node *n1,*n2 = polygon->_links.back().LastNode();
1808 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
1810 _OrientedLink& split = splits[ iS ];
1811 if ( !split ) continue;
1813 n1 = split.FirstNode();
1816 n1->_intPoint->_faceIDs.size() > 1 )
1818 // n1 is at intersection with EDGE
1819 if ( findChainOnEdge( splits, polygon->_links.back(), split, iS, quad, chainNodes ))
1821 for ( size_t i = 1; i < chainNodes.size(); ++i )
1822 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1823 prevPolyg = polygon;
1824 n2 = chainNodes.back();
1828 else if ( n1 != n2 )
1830 // try to connect to intersections with EDGEs
1831 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
1832 findChain( n2, n1, quad, chainNodes ))
1834 for ( size_t i = 1; i < chainNodes.size(); ++i )
1836 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
1837 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
1839 if ( chainNodes.back() != n1 )
1841 n2 = chainNodes.back();
1846 // try to connect to a split ending on the same FACE
1849 _OrientedLink foundSplit;
1850 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
1851 if (( foundSplit = splits[ i ]) &&
1852 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
1858 foundSplit._link = 0;
1862 if ( n2 != foundSplit.FirstNode() )
1864 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
1865 n2 = foundSplit.FirstNode();
1871 if ( n2->IsLinked( nFirst->_intPoint ))
1873 polygon->AddPolyLink( n2, n1, prevPolyg );
1876 } // if ( n1 != n2 )
1878 polygon->_links.push_back( split );
1881 n2 = polygon->_links.back().LastNode();
1885 if ( nFirst != n2 ) // close a polygon
1887 if ( !findChain( n2, nFirst, quad, chainNodes ))
1889 if ( !closePolygon( polygon, chainNodes ))
1890 if ( !isImplementEdges() )
1891 chainNodes.push_back( nFirst );
1893 for ( size_t i = 1; i < chainNodes.size(); ++i )
1895 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1896 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
1900 if ( polygon->_links.size() < 3 && nbSplits > 0 )
1902 polygon->_polyLinks.clear();
1903 polygon->_links.clear();
1905 } // while ( nbSplits > 0 )
1907 if ( polygon->_links.size() < 3 )
1909 _polygons.pop_back();
1911 } // loop on 6 hexahedron sides
1913 // Create polygons closing holes in a polyhedron
1914 // ----------------------------------------------
1916 // clear _usedInFace
1917 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
1918 _intNodes[ iN ]._usedInFace = 0;
1920 // add polygons to their links and mark used nodes
1921 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1923 _Face& polygon = _polygons[ iP ];
1924 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1926 polygon._links[ iL ].AddFace( &polygon );
1927 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
1931 vector< _OrientedLink* > freeLinks;
1932 freeLinks.reserve(20);
1933 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1935 _Face& polygon = _polygons[ iP ];
1936 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1937 if ( polygon._links[ iL ].NbFaces() < 2 )
1938 freeLinks.push_back( & polygon._links[ iL ]);
1940 int nbFreeLinks = freeLinks.size();
1941 if ( nbFreeLinks == 1 ) return;
1943 // put not used intersection nodes to _vIntNodes
1944 int nbVertexNodes = 0; // nb not used vertex nodes
1946 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
1947 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
1949 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
1950 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
1952 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
1953 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
1955 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
1958 _vIntNodes.push_back( &_intNodes[ iN ]);
1964 set<TGeomID> usedFaceIDs;
1965 vector< TGeomID > faces;
1966 TGeomID curFace = 0;
1967 const size_t nbQuadPolygons = _polygons.size();
1968 E_IntersectPoint ipTmp;
1970 // create polygons by making closed chains of free links
1971 size_t iPolygon = _polygons.size();
1972 while ( nbFreeLinks > 0 )
1974 if ( iPolygon == _polygons.size() )
1976 _polygons.resize( _polygons.size() + 1 );
1977 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
1978 _polygons[ iPolygon ]._links.reserve( 20 );
1980 _Face& polygon = _polygons[ iPolygon ];
1982 _OrientedLink* curLink = 0;
1984 if (( !hasEdgeIntersections ) ||
1985 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
1987 // get a remaining link to start from
1988 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
1989 if (( curLink = freeLinks[ iL ] ))
1990 freeLinks[ iL ] = 0;
1991 polygon._links.push_back( *curLink );
1995 // find all links connected to curLink
1996 curNode = curLink->FirstNode();
1998 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
1999 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2001 curLink = freeLinks[ iL ];
2002 freeLinks[ iL ] = 0;
2004 polygon._links.push_back( *curLink );
2006 } while ( curLink );
2008 else // there are intersections with EDGEs
2010 // get a remaining link to start from, one lying on minimal nb of FACEs
2012 typedef pair< TGeomID, int > TFaceOfLink;
2013 TFaceOfLink faceOfLink( -1, -1 );
2014 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
2015 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2016 if ( freeLinks[ iL ] )
2018 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2019 if ( faces.size() == 1 )
2021 faceOfLink = TFaceOfLink( faces[0], iL );
2022 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2024 facesOfLink[0] = faceOfLink;
2026 else if ( facesOfLink[0].first < 0 )
2028 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
2029 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
2032 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
2033 faceOfLink = facesOfLink[i];
2035 if ( faceOfLink.first < 0 ) // all faces used
2037 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
2038 if (( curLink = freeLinks[ iL ]))
2041 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2042 faceOfLink.second = iL;
2044 usedFaceIDs.clear();
2046 curFace = faceOfLink.first;
2047 curLink = freeLinks[ faceOfLink.second ];
2048 freeLinks[ faceOfLink.second ] = 0;
2050 usedFaceIDs.insert( curFace );
2051 polygon._links.push_back( *curLink );
2054 // find all links lying on a curFace
2057 // go forward from curLink
2058 curNode = curLink->LastNode();
2060 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2061 if ( freeLinks[ iL ] &&
2062 freeLinks[ iL ]->FirstNode() == curNode &&
2063 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
2065 curLink = freeLinks[ iL ];
2066 freeLinks[ iL ] = 0;
2067 polygon._links.push_back( *curLink );
2070 } while ( curLink );
2072 std::reverse( polygon._links.begin(), polygon._links.end() );
2074 curLink = & polygon._links.back();
2077 // go backward from curLink
2078 curNode = curLink->FirstNode();
2080 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2081 if ( freeLinks[ iL ] &&
2082 freeLinks[ iL ]->LastNode() == curNode &&
2083 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
2085 curLink = freeLinks[ iL ];
2086 freeLinks[ iL ] = 0;
2087 polygon._links.push_back( *curLink );
2090 } while ( curLink );
2092 curNode = polygon._links.back().FirstNode();
2094 if ( polygon._links[0].LastNode() != curNode )
2096 if ( nbVertexNodes > 0 )
2098 // add links with _vIntNodes if not already used
2100 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2101 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
2102 _vIntNodes[ iN ]->IsOnFace( curFace ))
2104 _vIntNodes[ iN ]->_usedInFace = &polygon;
2105 chainNodes.push_back( _vIntNodes[ iN ] );
2107 if ( chainNodes.size() > 1 )
2109 sortVertexNodes( chainNodes, curNode, curFace );
2111 for ( size_t i = 0; i < chainNodes.size(); ++i )
2113 polygon.AddPolyLink( chainNodes[ i ], curNode );
2114 curNode = chainNodes[ i ];
2115 freeLinks.push_back( &polygon._links.back() );
2118 nbVertexNodes -= chainNodes.size();
2120 // if ( polygon._links.size() > 1 )
2122 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
2123 freeLinks.push_back( &polygon._links.back() );
2127 } // if there are intersections with EDGEs
2129 if ( polygon._links.size() < 2 ||
2130 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
2131 return; // closed polygon not found -> invalid polyhedron
2133 if ( polygon._links.size() == 2 )
2135 if ( freeLinks.back() == &polygon._links.back() )
2137 freeLinks.pop_back();
2140 if ( polygon._links.front().NbFaces() > 0 )
2141 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
2142 if ( polygon._links.back().NbFaces() > 0 )
2143 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
2145 if ( iPolygon == _polygons.size()-1 )
2146 _polygons.pop_back();
2148 else // polygon._links.size() >= 2
2150 // add polygon to its links
2151 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2153 polygon._links[ iL ].AddFace( &polygon );
2154 polygon._links[ iL ].Reverse();
2156 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
2158 // check that a polygon does not lie on a hexa side
2160 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
2162 if ( polygon._links[ iL ].NbFaces() < 2 )
2163 continue; // it's a just added free link
2164 // look for a polygon made on a hexa side and sharing
2165 // two or more haxa links
2167 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
2168 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
2169 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
2170 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
2171 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
2172 coplanarPolyg < & _polygons[ nbQuadPolygons ])
2174 if ( iL2 == polygon._links.size() )
2177 if ( coplanarPolyg ) // coplanar polygon found
2179 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
2180 nbFreeLinks -= polygon._polyLinks.size();
2182 // an E_IntersectPoint used to mark nodes of coplanarPolyg
2183 // as lying on curFace while they are not at intersection with geometry
2184 ipTmp._faceIDs.resize(1);
2185 ipTmp._faceIDs[0] = curFace;
2187 // fill freeLinks with links not shared by coplanarPolyg and polygon
2188 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2189 if ( polygon._links[ iL ]._link->_faces[1] &&
2190 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
2192 _Face* p = polygon._links[ iL ]._link->_faces[0];
2193 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2194 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
2196 freeLinks.push_back( & p->_links[ iL2 ] );
2198 freeLinks.back()->RemoveFace( &polygon );
2202 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
2203 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
2204 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
2206 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
2207 if ( p == coplanarPolyg )
2208 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
2209 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2210 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
2212 // set links of coplanarPolyg in place of used freeLinks
2213 // to re-create coplanarPolyg next
2215 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
2216 if ( iL3 < freeLinks.size() )
2217 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
2219 freeLinks.push_back( & p->_links[ iL2 ] );
2221 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
2222 // mark nodes of coplanarPolyg as lying on curFace
2223 for ( int iN = 0; iN < 2; ++iN )
2225 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
2226 if ( n->_intPoint ) n->_intPoint->Add( ipTmp._faceIDs );
2227 else n->_intPoint = &ipTmp;
2232 // set coplanarPolyg to be re-created next
2233 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2234 if ( coplanarPolyg == & _polygons[ iP ] )
2237 _polygons[ iPolygon ]._links.clear();
2238 _polygons[ iPolygon ]._polyLinks.clear();
2241 _polygons.pop_back();
2242 usedFaceIDs.erase( curFace );
2244 } // if ( coplanarPolyg )
2245 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
2247 iPolygon = _polygons.size();
2249 } // end of case ( polygon._links.size() > 2 )
2250 } // while ( nbFreeLinks > 0 )
2252 if ( ! checkPolyhedronSize() )
2257 for ( size_t i = 0; i < 8; ++i )
2258 if ( _hexNodes[ i ]._intPoint == &ipTmp )
2259 _hexNodes[ i ]._intPoint = 0;
2261 // create a classic cell if possible
2264 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2265 nbPolygons += (_polygons[ iF ]._links.size() > 0 );
2267 //const int nbNodes = _nbCornerNodes + nbIntersections;
2269 for ( size_t i = 0; i < 8; ++i )
2270 nbNodes += _hexNodes[ i ].IsUsedInFace();
2271 for ( size_t i = 0; i < _intNodes.size(); ++i )
2272 nbNodes += _intNodes[ i ].IsUsedInFace();
2274 bool isClassicElem = false;
2275 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
2276 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
2277 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
2278 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
2279 if ( !isClassicElem )
2281 _volumeDefs._nodes.clear();
2282 _volumeDefs._quantities.clear();
2284 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2286 const size_t nbLinks = _polygons[ iF ]._links.size();
2287 if ( nbLinks == 0 ) continue;
2288 _volumeDefs._quantities.push_back( nbLinks );
2289 for ( size_t iL = 0; iL < nbLinks; ++iL )
2290 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
2294 //================================================================================
2296 * \brief Create elements in the mesh
2298 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
2299 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2301 SMESHDS_Mesh* mesh = helper.GetMeshDS();
2303 size_t nbCells[3] = { _grid->_coords[0].size() - 1,
2304 _grid->_coords[1].size() - 1,
2305 _grid->_coords[2].size() - 1 };
2306 const size_t nbGridCells = nbCells[0] * nbCells[1] * nbCells[2];
2307 vector< Hexahedron* > allHexa( nbGridCells, 0 );
2310 // set intersection nodes from GridLine's to links of allHexa
2311 int i,j,k, iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
2312 for ( int iDir = 0; iDir < 3; ++iDir )
2314 int dInd[4][3] = { {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
2315 dInd[1][ iDirOther[iDir][0] ] = -1;
2316 dInd[2][ iDirOther[iDir][1] ] = -1;
2317 dInd[3][ iDirOther[iDir][0] ] = -1; dInd[3][ iDirOther[iDir][1] ] = -1;
2318 // loop on GridLine's parallel to iDir
2319 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
2320 for ( ; lineInd.More(); ++lineInd )
2322 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
2323 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
2324 for ( ; ip != line._intPoints.end(); ++ip )
2326 // if ( !ip->_node ) continue; // intersection at a grid node
2327 lineInd.SetIndexOnLine( ip->_indexOnLine );
2328 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
2330 i = int(lineInd.I()) + dInd[iL][0];
2331 j = int(lineInd.J()) + dInd[iL][1];
2332 k = int(lineInd.K()) + dInd[iL][2];
2333 if ( i < 0 || i >= (int) nbCells[0] ||
2334 j < 0 || j >= (int) nbCells[1] ||
2335 k < 0 || k >= (int) nbCells[2] ) continue;
2337 const size_t hexIndex = _grid->CellIndex( i,j,k );
2338 Hexahedron *& hex = allHexa[ hexIndex ];
2341 hex = new Hexahedron( *this );
2347 const int iLink = iL + iDir * 4;
2348 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
2349 hex->_nbFaceIntNodes += bool( ip->_node );
2355 // implement geom edges into the mesh
2356 addEdges( helper, allHexa, edge2faceIDsMap );
2358 // add not split hexadrons to the mesh
2360 vector< Hexahedron* > intHexa( nbIntHex, (Hexahedron*) NULL );
2361 for ( size_t i = 0; i < allHexa.size(); ++i )
2363 Hexahedron * & hex = allHexa[ i ];
2366 intHexa.push_back( hex );
2367 if ( hex->_nbFaceIntNodes > 0 || hex->_eIntPoints.size() > 0 )
2368 continue; // treat intersected hex later
2369 this->init( hex->_i, hex->_j, hex->_k );
2375 if (( _nbCornerNodes == 8 ) &&
2376 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
2378 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
2379 SMDS_MeshElement* el =
2380 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
2381 _hexNodes[3].Node(), _hexNodes[1].Node(),
2382 _hexNodes[4].Node(), _hexNodes[6].Node(),
2383 _hexNodes[7].Node(), _hexNodes[5].Node() );
2384 mesh->SetMeshElementOnShape( el, helper.GetSubShapeID() );
2389 else if ( _nbCornerNodes > 3 && !hex )
2391 // all intersection of hex with geometry are at grid nodes
2392 hex = new Hexahedron( *this );
2396 intHexa.push_back( hex );
2400 // add elements resulted from hexadron intersection
2402 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
2403 ParallelHexahedron( intHexa ),
2404 tbb::simple_partitioner()); // ComputeElements() is called here
2405 for ( size_t i = 0; i < intHexa.size(); ++i )
2406 if ( Hexahedron * hex = intHexa[ i ] )
2407 nbAdded += hex->addElements( helper );
2409 for ( size_t i = 0; i < intHexa.size(); ++i )
2410 if ( Hexahedron * hex = intHexa[ i ] )
2412 hex->ComputeElements();
2413 nbAdded += hex->addElements( helper );
2417 for ( size_t i = 0; i < allHexa.size(); ++i )
2419 delete allHexa[ i ];
2424 //================================================================================
2426 * \brief Implements geom edges into the mesh
2428 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
2429 vector< Hexahedron* >& hexes,
2430 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2432 if ( edge2faceIDsMap.empty() ) return;
2434 // Prepare planes for intersecting with EDGEs
2437 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
2439 GridPlanes& planes = pln[ iDirZ ];
2440 int iDirX = ( iDirZ + 1 ) % 3;
2441 int iDirY = ( iDirZ + 2 ) % 3;
2442 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
2443 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
2444 planes._zProjs [0] = 0;
2445 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
2446 const vector< double > & u = _grid->_coords[ iDirZ ];
2447 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
2449 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
2453 const double deflection = _grid->_minCellSize / 20.;
2454 const double tol = _grid->_tol;
2455 E_IntersectPoint ip;
2457 // Intersect EDGEs with the planes
2458 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
2459 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
2461 const TGeomID edgeID = e2fIt->first;
2462 const TopoDS_Edge & E = TopoDS::Edge( _grid->_shapes( edgeID ));
2463 BRepAdaptor_Curve curve( E );
2464 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
2465 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
2467 ip._faceIDs = e2fIt->second;
2468 ip._shapeID = edgeID;
2470 // discretize the EGDE
2471 GCPnts_UniformDeflection discret( curve, deflection, true );
2472 if ( !discret.IsDone() || discret.NbPoints() < 2 )
2475 // perform intersection
2476 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
2478 GridPlanes& planes = pln[ iDirZ ];
2479 int iDirX = ( iDirZ + 1 ) % 3;
2480 int iDirY = ( iDirZ + 2 ) % 3;
2481 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
2482 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
2483 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
2484 int dIJK[3], d000[3] = { 0,0,0 };
2485 double o[3] = { _grid->_coords[0][0],
2486 _grid->_coords[1][0],
2487 _grid->_coords[2][0] };
2489 // locate the 1st point of a segment within the grid
2490 gp_XYZ p1 = discret.Value( 1 ).XYZ();
2491 double u1 = discret.Parameter( 1 );
2492 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
2494 _grid->ComputeUVW( p1, ip._uvw );
2495 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
2496 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
2497 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
2498 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
2499 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
2500 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
2502 int ijk[3]; // grid index where a segment intersect a plane
2507 // add the 1st vertex point to a hexahedron
2511 ip._shapeID = _grid->_shapes.Add( v1 );
2512 _grid->_edgeIntP.push_back( ip );
2513 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2514 _grid->_edgeIntP.pop_back();
2515 ip._shapeID = edgeID;
2517 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
2519 // locate the 2nd point of a segment within the grid
2520 gp_XYZ p2 = discret.Value( iP ).XYZ();
2521 double u2 = discret.Parameter( iP );
2522 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
2524 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
2526 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
2528 // treat intersections with planes between 2 end points of a segment
2529 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
2530 int iZ = iZ1 + ( iZ1 < iZ2 );
2531 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
2533 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
2534 planes._zProjs[ iZ ],
2535 curve, planes._zNorm, _grid->_origin );
2536 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
2537 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2538 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2541 // add ip to hex "above" the plane
2542 _grid->_edgeIntP.push_back( ip );
2544 bool added = addIntersection(_grid->_edgeIntP.back(), hexes, ijk, dIJK);
2546 // add ip to hex "below" the plane
2547 ijk[ iDirZ ] = iZ-1;
2548 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, dIJK ) &&
2550 _grid->_edgeIntP.pop_back();
2558 // add the 2nd vertex point to a hexahedron
2561 ip._shapeID = _grid->_shapes.Add( v2 );
2563 _grid->ComputeUVW( p1, ip._uvw );
2564 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2565 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2567 _grid->_edgeIntP.push_back( ip );
2568 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2569 _grid->_edgeIntP.pop_back();
2570 ip._shapeID = edgeID;
2572 } // loop on 3 grid directions
2577 //================================================================================
2579 * \brief Finds intersection of a curve with a plane
2580 * \param [in] u1 - parameter of one curve point
2581 * \param [in] proj1 - projection of the curve point to the plane normal
2582 * \param [in] u2 - parameter of another curve point
2583 * \param [in] proj2 - projection of the other curve point to the plane normal
2584 * \param [in] proj - projection of a point where the curve intersects the plane
2585 * \param [in] curve - the curve
2586 * \param [in] axis - the plane normal
2587 * \param [in] origin - the plane origin
2588 * \return gp_Pnt - the found intersection point
2590 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
2591 double u2, double proj2,
2593 BRepAdaptor_Curve& curve,
2595 const gp_XYZ& origin)
2597 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
2598 double u = u1 * ( 1 - r ) + u2 * r;
2599 gp_Pnt p = curve.Value( u );
2600 double newProj = axis * ( p.XYZ() - origin );
2601 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
2604 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
2606 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
2611 //================================================================================
2613 * \brief Returns indices of a hexahedron sub-entities holding a point
2614 * \param [in] ip - intersection point
2615 * \param [out] facets - 0-3 facets holding a point
2616 * \param [out] sub - index of a vertex or an edge holding a point
2617 * \return int - number of facets holding a point
2619 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
2621 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
2623 int vertex = 0, egdeMask = 0;
2625 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
2626 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
2629 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
2630 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
2634 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
2635 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
2638 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
2639 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
2643 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
2644 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
2647 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
2648 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
2655 case 0: sub = 0; break;
2656 case 1: sub = facets[0]; break;
2658 const int edge [3][8] = {
2659 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
2660 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
2661 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
2662 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
2663 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
2664 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
2666 switch ( egdeMask ) {
2667 case X | Y: sub = edge[ 0 ][ vertex ]; break;
2668 case X | Z: sub = edge[ 1 ][ vertex ]; break;
2669 default: sub = edge[ 2 ][ vertex ];
2675 sub = vertex + SMESH_Block::ID_FirstV;
2680 //================================================================================
2682 * \brief Adds intersection with an EDGE
2684 bool Hexahedron::addIntersection( const E_IntersectPoint& ip,
2685 vector< Hexahedron* >& hexes,
2686 int ijk[], int dIJK[] )
2690 size_t hexIndex[4] = {
2691 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
2692 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
2693 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
2694 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
2696 for ( int i = 0; i < 4; ++i )
2698 if ( /*0 <= hexIndex[i] &&*/ hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
2700 Hexahedron* h = hexes[ hexIndex[i] ];
2701 // check if ip is really inside the hex
2703 if ( h->isOutParam( ip._uvw ))
2704 throw SALOME_Exception("ip outside a hex");
2706 h->_eIntPoints.push_back( & ip );
2712 //================================================================================
2714 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
2716 bool Hexahedron::findChain( _Node* n1,
2719 vector<_Node*>& chn )
2722 chn.push_back( n1 );
2723 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2724 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2725 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
2726 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2728 chn.push_back( quad._eIntNodes[ iP ]);
2729 chn.push_back( n2 );
2730 quad._eIntNodes[ iP ]->_usedInFace = &quad;
2737 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2738 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2739 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2741 chn.push_back( quad._eIntNodes[ iP ]);
2742 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
2745 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
2747 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
2748 chn.push_back( n2 );
2750 return chn.size() > 1;
2752 //================================================================================
2754 * \brief Try to heal a polygon whose ends are not connected
2756 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
2758 int i = -1, nbLinks = polygon->_links.size();
2761 vector< _OrientedLink > newLinks;
2762 // find a node lying on the same FACE as the last one
2763 _Node* node = polygon->_links.back().LastNode();
2764 int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
2765 for ( i = nbLinks - 2; i >= 0; --i )
2766 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
2770 for ( ; i < nbLinks; ++i )
2771 newLinks.push_back( polygon->_links[i] );
2775 // find a node lying on the same FACE as the first one
2776 node = polygon->_links[0].FirstNode();
2777 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
2778 for ( i = 1; i < nbLinks; ++i )
2779 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
2782 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
2783 newLinks.push_back( polygon->_links[i] );
2785 if ( newLinks.size() > 1 )
2787 polygon->_links.swap( newLinks );
2789 chainNodes.push_back( polygon->_links.back().LastNode() );
2790 chainNodes.push_back( polygon->_links[0].FirstNode() );
2795 //================================================================================
2797 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
2799 * This function is for a case where an EDGE lies on a quad which lies on a FACE
2800 * so that a part of quad in ON and another part in IN
2802 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
2803 const _OrientedLink& prevSplit,
2804 const _OrientedLink& avoidSplit,
2807 vector<_Node*>& chn )
2809 if ( !isImplementEdges() )
2812 _Node* pn1 = prevSplit.FirstNode();
2813 _Node* pn2 = prevSplit.LastNode();
2814 int avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
2815 if ( avoidFace < 1 && pn1->_intPoint )
2818 _Node* n, *stopNode = avoidSplit.LastNode();
2821 if ( !quad._eIntNodes.empty() )
2823 chn.push_back( pn2 );
2828 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2829 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
2830 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
2831 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
2833 chn.push_back( quad._eIntNodes[ iP ]);
2834 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
2842 for ( i = splits.size()-1; i >= 0; --i )
2847 n = splits[i].LastNode();
2848 if ( n == stopNode )
2851 ( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2852 ( !avoidFace || n->IsOnFace( avoidFace )))
2855 n = splits[i].FirstNode();
2856 if ( n == stopNode )
2858 if (( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2859 ( !avoidFace || n->IsOnFace( avoidFace )))
2863 if ( n && n != stopNode)
2866 chn.push_back( pn2 );
2873 //================================================================================
2875 * \brief Checks transition at the ginen intersection node of a link
2877 bool Hexahedron::isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const
2881 const bool moreIntPoints = ( iP+1 < (int) link._fIntPoints.size() );
2884 _Node* n1 = link._fIntNodes[ iP ];
2886 n1 = link._nodes[0];
2887 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
2888 if ( !n2 || !n2->Node() )
2889 n2 = link._nodes[1];
2893 // get all FACEs under n1 and n2
2894 set< TGeomID > faceIDs;
2895 if ( moreIntPoints ) faceIDs.insert( link._fIntPoints[iP+1]->_faceIDs.begin(),
2896 link._fIntPoints[iP+1]->_faceIDs.end() );
2897 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
2898 n2->_intPoint->_faceIDs.end() );
2899 if ( faceIDs.empty() )
2900 return false; // n2 is inside
2901 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
2902 n1->_intPoint->_faceIDs.end() );
2903 faceIDs.insert( link._fIntPoints[iP]->_faceIDs.begin(),
2904 link._fIntPoints[iP]->_faceIDs.end() );
2906 // get a point between 2 nodes
2907 gp_Pnt p1 = n1->Point();
2908 gp_Pnt p2 = n2->Point();
2909 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
2911 TopLoc_Location loc;
2913 set< TGeomID >::iterator faceID = faceIDs.begin();
2914 for ( ; faceID != faceIDs.end(); ++faceID )
2916 // project pOnLink on a FACE
2917 if ( *faceID < 1 ) continue;
2918 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( *faceID ));
2919 GeomAPI_ProjectPointOnSurf& proj =
2920 helper.GetProjector( face, loc, 0.1*_grid->_tol );
2921 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
2922 proj.Perform( testPnt );
2923 if ( proj.IsDone() && proj.NbPoints() > 0 )
2925 Quantity_Parameter u,v;
2926 proj.LowerDistanceParameters( u,v );
2928 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
2934 // find isOut by normals
2936 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
2941 if ( face.Orientation() == TopAbs_REVERSED )
2943 gp_Vec v( proj.NearestPoint(), testPnt );
2944 isOut = ( v * normal > 0 );
2949 // classify a projection
2950 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
2952 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
2953 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
2954 if ( state == TopAbs_OUT )
2966 //================================================================================
2968 * \brief Sort nodes on a FACE
2970 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
2972 if ( nodes.size() > 20 ) return;
2974 // get shapes under nodes
2975 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
2976 for ( size_t i = 0; i < nodes.size(); ++i )
2977 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
2980 // get shapes of the FACE
2981 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( faceID ));
2982 list< TopoDS_Edge > edges;
2983 list< int > nbEdges;
2984 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
2986 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
2987 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
2988 list< int >::iterator nE = nbEdges.begin();
2989 for ( ; nbW > 0; ++nE, --nbW )
2991 std::advance( eEnd, *nE );
2992 for ( ; e != eEnd; ++e )
2993 for ( int i = 0; i < 2; ++i )
2996 _grid->_shapes.FindIndex( *e ) :
2997 _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ));
2999 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
3001 edges.erase( eEnd, edges.end() ); // remove rest wires
3002 e = eEnd = edges.end();
3009 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
3012 // rotate edges to have the first one at least partially out of the hexa
3013 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
3014 for ( ; e != edges.end(); ++e )
3016 if ( !_grid->_shapes.FindIndex( *e ))
3021 for ( int i = 0; i < 2 && !isOut; ++i )
3025 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
3026 p = BRep_Tool::Pnt( v );
3028 else if ( eMidOut == edges.end() )
3030 TopLoc_Location loc;
3031 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
3032 if ( c.IsNull() ) break;
3033 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
3040 _grid->ComputeUVW( p.XYZ(), uvw );
3041 if ( isOutParam( uvw ))
3052 if ( e != edges.end() )
3053 edges.splice( edges.end(), edges, edges.begin(), e );
3054 else if ( eMidOut != edges.end() )
3055 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
3057 // sort nodes accoring to the order of edges
3058 _Node* orderNodes [20];
3059 TGeomID orderShapeIDs[20];
3061 TGeomID id, *pID = 0;
3062 for ( e = edges.begin(); e != edges.end(); ++e )
3064 if (( id = _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
3065 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3067 orderShapeIDs[ nbN ] = id;
3068 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3071 if (( id = _grid->_shapes.FindIndex( *e )) &&
3072 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3074 orderShapeIDs[ nbN ] = id;
3075 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3079 if ( nbN != nodes.size() )
3082 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
3083 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
3085 for ( size_t i = 0; i < nodes.size(); ++i )
3086 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
3089 //================================================================================
3091 * \brief Adds computed elements to the mesh
3093 int Hexahedron::addElements(SMESH_MesherHelper& helper)
3096 // add elements resulted from hexahedron intersection
3097 //for ( size_t i = 0; i < _volumeDefs.size(); ++i )
3099 vector< const SMDS_MeshNode* > nodes( _volumeDefs._nodes.size() );
3100 for ( size_t iN = 0; iN < nodes.size(); ++iN )
3101 if ( !( nodes[iN] = _volumeDefs._nodes[iN]->Node() ))
3103 if ( const E_IntersectPoint* eip = _volumeDefs._nodes[iN]->EdgeIntPnt() )
3104 nodes[iN] = _volumeDefs._nodes[iN]->_intPoint->_node =
3105 helper.AddNode( eip->_point.X(),
3109 throw SALOME_Exception("Bug: no node at intersection point");
3112 if ( !_volumeDefs._quantities.empty() )
3114 helper.AddPolyhedralVolume( nodes, _volumeDefs._quantities );
3118 switch ( nodes.size() )
3120 case 8: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
3121 nodes[4],nodes[5],nodes[6],nodes[7] );
3123 case 4: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
3125 case 6: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3], nodes[4],nodes[5] );
3128 helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
3132 nbAdded += int ( _volumeDefs._nodes.size() > 0 );
3137 //================================================================================
3139 * \brief Return true if the element is in a hole
3141 bool Hexahedron::isInHole() const
3143 if ( !_vIntNodes.empty() )
3146 const size_t ijk[3] = { _i, _j, _k };
3147 F_IntersectPoint curIntPnt;
3149 // consider a cell to be in a hole if all links in any direction
3150 // comes OUT of geometry
3151 for ( int iDir = 0; iDir < 3; ++iDir )
3153 const vector<double>& coords = _grid->_coords[ iDir ];
3154 LineIndexer li = _grid->GetLineIndexer( iDir );
3155 li.SetIJK( _i,_j,_k );
3156 size_t lineIndex[4] = { li.LineIndex (),
3160 bool allLinksOut = true, hasLinks = false;
3161 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
3163 const _Link& link = _hexLinks[ iL + 4*iDir ];
3164 // check transition of the first node of a link
3165 const F_IntersectPoint* firstIntPnt = 0;
3166 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
3168 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0];
3169 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
3170 multiset< F_IntersectPoint >::const_iterator ip =
3171 line._intPoints.upper_bound( curIntPnt );
3173 firstIntPnt = &(*ip);
3175 else if ( !link._fIntPoints.empty() )
3177 firstIntPnt = link._fIntPoints[0];
3183 allLinksOut = ( firstIntPnt->_transition == Trans_OUT );
3186 if ( hasLinks && allLinksOut )
3192 //================================================================================
3194 * \brief Return true if a polyhedron passes _sizeThreshold criterion
3196 bool Hexahedron::checkPolyhedronSize() const
3199 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3201 const _Face& polygon = _polygons[iP];
3202 if ( polygon._links.empty() )
3204 gp_XYZ area (0,0,0);
3205 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
3206 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3208 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
3212 volume += p1 * area;
3216 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
3218 return volume > initVolume / _sizeThreshold;
3220 //================================================================================
3222 * \brief Tries to create a hexahedron
3224 bool Hexahedron::addHexa()
3226 int nbQuad = 0, iQuad = -1;
3227 for ( size_t i = 0; i < _polygons.size(); ++i )
3229 if ( _polygons[i]._links.empty() )
3231 if ( _polygons[i]._links.size() != 4 )
3242 for ( int iL = 0; iL < 4; ++iL )
3245 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
3248 // find a top node above the base node
3249 _Link* link = _polygons[iQuad]._links[iL]._link;
3250 if ( !link->_faces[0] || !link->_faces[1] )
3251 return debugDumpLink( link );
3252 // a quadrangle sharing <link> with _polygons[iQuad]
3253 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
3254 for ( int i = 0; i < 4; ++i )
3255 if ( quad->_links[i]._link == link )
3257 // 1st node of a link opposite to <link> in <quad>
3258 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
3264 _volumeDefs.set( &nodes[0], 8 );
3268 //================================================================================
3270 * \brief Tries to create a tetrahedron
3272 bool Hexahedron::addTetra()
3275 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
3276 if ( _polygons[i]._links.size() == 3 )
3282 nodes[0] = _polygons[iTria]._links[0].FirstNode();
3283 nodes[1] = _polygons[iTria]._links[1].FirstNode();
3284 nodes[2] = _polygons[iTria]._links[2].FirstNode();
3286 _Link* link = _polygons[iTria]._links[0]._link;
3287 if ( !link->_faces[0] || !link->_faces[1] )
3288 return debugDumpLink( link );
3290 // a triangle sharing <link> with _polygons[0]
3291 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
3292 for ( int i = 0; i < 3; ++i )
3293 if ( tria->_links[i]._link == link )
3295 nodes[3] = tria->_links[(i+1)%3].LastNode();
3296 _volumeDefs.set( &nodes[0], 4 );
3302 //================================================================================
3304 * \brief Tries to create a pentahedron
3306 bool Hexahedron::addPenta()
3308 // find a base triangular face
3310 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
3311 if ( _polygons[ iF ]._links.size() == 3 )
3313 if ( iTri < 0 ) return false;
3318 for ( int iL = 0; iL < 3; ++iL )
3321 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
3324 // find a top node above the base node
3325 _Link* link = _polygons[ iTri ]._links[iL]._link;
3326 if ( !link->_faces[0] || !link->_faces[1] )
3327 return debugDumpLink( link );
3328 // a quadrangle sharing <link> with a base triangle
3329 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
3330 if ( quad->_links.size() != 4 ) return false;
3331 for ( int i = 0; i < 4; ++i )
3332 if ( quad->_links[i]._link == link )
3334 // 1st node of a link opposite to <link> in <quad>
3335 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
3341 _volumeDefs.set( &nodes[0], 6 );
3343 return ( nbN == 6 );
3345 //================================================================================
3347 * \brief Tries to create a pyramid
3349 bool Hexahedron::addPyra()
3351 // find a base quadrangle
3353 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
3354 if ( _polygons[ iF ]._links.size() == 4 )
3356 if ( iQuad < 0 ) return false;
3360 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
3361 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
3362 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
3363 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
3365 _Link* link = _polygons[iQuad]._links[0]._link;
3366 if ( !link->_faces[0] || !link->_faces[1] )
3367 return debugDumpLink( link );
3369 // a triangle sharing <link> with a base quadrangle
3370 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
3371 if ( tria->_links.size() != 3 ) return false;
3372 for ( int i = 0; i < 3; ++i )
3373 if ( tria->_links[i]._link == link )
3375 nodes[4] = tria->_links[(i+1)%3].LastNode();
3376 _volumeDefs.set( &nodes[0], 5 );
3382 //================================================================================
3384 * \brief Dump a link and return \c false
3386 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
3389 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
3390 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
3391 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
3392 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
3396 //================================================================================
3398 * \brief Classify a point by grid paremeters
3400 bool Hexahedron::isOutParam(const double uvw[3]) const
3402 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
3403 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
3404 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
3405 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
3406 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
3407 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
3410 //================================================================================
3412 * \brief computes exact bounding box with axes parallel to given ones
3414 //================================================================================
3416 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
3417 const double* axesDirs,
3421 TopoDS_Compound allFacesComp;
3422 b.MakeCompound( allFacesComp );
3423 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
3424 b.Add( allFacesComp, faceVec[ iF ] );
3426 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
3427 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
3429 for ( int i = 0; i < 6; ++i )
3430 farDist = Max( farDist, 10 * sP[i] );
3432 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
3433 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
3434 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
3435 axis[0].Normalize();
3436 axis[1].Normalize();
3437 axis[2].Normalize();
3439 gp_Mat basis( axis[0], axis[1], axis[2] );
3440 gp_Mat bi = basis.Inverted();
3443 for ( int iDir = 0; iDir < 3; ++iDir )
3445 gp_XYZ axis0 = axis[ iDir ];
3446 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
3447 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
3448 for ( int isMax = 0; isMax < 2; ++isMax )
3450 double shift = isMax ? farDist : -farDist;
3451 gp_XYZ orig = shift * axis0;
3452 gp_XYZ norm = axis1 ^ axis2;
3453 gp_Pln pln( orig, norm );
3454 norm = pln.Axis().Direction().XYZ();
3455 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
3457 gp_Pnt& pAxis = isMax ? pMax : pMin;
3458 gp_Pnt pPlane, pFaces;
3459 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
3464 for ( int i = 0; i < 2; ++i ) {
3465 corner.SetCoord( 1, sP[ i*3 ]);
3466 for ( int j = 0; j < 2; ++j ) {
3467 corner.SetCoord( 2, sP[ i*3 + 1 ]);
3468 for ( int k = 0; k < 2; ++k )
3470 corner.SetCoord( 3, sP[ i*3 + 2 ]);
3476 corner = isMax ? bb.CornerMax() : bb.CornerMin();
3477 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
3481 gp_XYZ pf = pFaces.XYZ() * bi;
3482 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
3488 shapeBox.Add( pMin );
3489 shapeBox.Add( pMax );
3496 //=============================================================================
3498 * \brief Generates 3D structured Cartesian mesh in the internal part of
3499 * solid shapes and polyhedral volumes near the shape boundary.
3500 * \param theMesh - mesh to fill in
3501 * \param theShape - a compound of all SOLIDs to mesh
3502 * \retval bool - true in case of success
3504 //=============================================================================
3506 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
3507 const TopoDS_Shape & theShape)
3509 // The algorithm generates the mesh in following steps:
3511 // 1) Intersection of grid lines with the geometry boundary.
3512 // This step allows to find out if a given node of the initial grid is
3513 // inside or outside the geometry.
3515 // 2) For each cell of the grid, check how many of it's nodes are outside
3516 // of the geometry boundary. Depending on a result of this check
3517 // - skip a cell, if all it's nodes are outside
3518 // - skip a cell, if it is too small according to the size threshold
3519 // - add a hexahedron in the mesh, if all nodes are inside
3520 // - add a polyhedron in the mesh, if some nodes are inside and some outside
3522 _computeCanceled = false;
3524 SMESH_MesherHelper helper( theMesh );
3529 grid._helper = &helper;
3531 vector< TopoDS_Shape > faceVec;
3533 TopTools_MapOfShape faceMap;
3534 TopExp_Explorer fExp;
3535 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
3536 if ( !faceMap.Add( fExp.Current() ))
3537 faceMap.Remove( fExp.Current() ); // remove a face shared by two solids
3539 for ( fExp.ReInit(); fExp.More(); fExp.Next() )
3540 if ( faceMap.Contains( fExp.Current() ))
3541 faceVec.push_back( fExp.Current() );
3543 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
3544 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
3545 TopExp_Explorer eExp;
3547 for ( size_t i = 0; i < faceVec.size(); ++i )
3549 facesItersectors[i]._face = TopoDS::Face ( faceVec[i] );
3550 facesItersectors[i]._faceID = grid._shapes.Add( faceVec[i] );
3551 facesItersectors[i]._grid = &grid;
3552 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
3554 if ( _hyp->GetToAddEdges() )
3556 helper.SetSubShape( faceVec[i] );
3557 for ( eExp.Init( faceVec[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
3559 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
3560 if ( !SMESH_Algo::isDegenerated( edge ) &&
3561 !helper.IsRealSeam( edge ))
3562 edge2faceIDsMap[ grid._shapes.Add( edge )].push_back( facesItersectors[i]._faceID );
3567 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
3569 vector<double> xCoords, yCoords, zCoords;
3570 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
3572 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
3574 if ( _computeCanceled ) return false;
3577 { // copy partner faces and curves of not thread-safe types
3578 set< const Standard_Transient* > tshapes;
3579 BRepBuilderAPI_Copy copier;
3580 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3582 if ( !facesItersectors[i].IsThreadSafe(tshapes) )
3584 copier.Perform( facesItersectors[i]._face );
3585 facesItersectors[i]._face = TopoDS::Face( copier );
3589 // Intersection of grid lines with the geometry boundary.
3590 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
3591 ParallelIntersector( facesItersectors ),
3592 tbb::simple_partitioner());
3594 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3595 facesItersectors[i].Intersect();
3598 // put interesection points onto the GridLine's; this is done after intersection
3599 // to avoid contention of facesItersectors for writing into the same GridLine
3600 // in case of parallel work of facesItersectors
3601 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3602 facesItersectors[i].StoreIntersections();
3604 TopExp_Explorer solidExp (theShape, TopAbs_SOLID);
3605 helper.SetSubShape( solidExp.Current() );
3606 helper.SetElementsOnShape( true );
3608 if ( _computeCanceled ) return false;
3610 // create nodes on the geometry
3611 grid.ComputeNodes(helper);
3613 if ( _computeCanceled ) return false;
3615 // create volume elements
3616 Hexahedron hex( _hyp->GetSizeThreshold(), &grid );
3617 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
3619 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3622 // make all SOLIDs computed
3623 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
3625 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
3626 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
3628 const SMDS_MeshElement* vol = volIt->next();
3629 sm1->RemoveElement( vol, /*isElemDeleted=*/false );
3630 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
3633 // make other sub-shapes computed
3634 setSubmeshesComputed( theMesh, theShape );
3637 // remove free nodes
3638 if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
3640 TIDSortedNodeSet nodesToRemove;
3641 // get intersection nodes
3642 for ( int iDir = 0; iDir < 3; ++iDir )
3644 vector< GridLine >& lines = grid._lines[ iDir ];
3645 for ( size_t i = 0; i < lines.size(); ++i )
3647 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
3648 for ( ; ip != lines[i]._intPoints.end(); ++ip )
3649 if ( ip->_node && ip->_node->NbInverseElements() == 0 )
3650 nodesToRemove.insert( nodesToRemove.end(), ip->_node );
3654 for ( size_t i = 0; i < grid._nodes.size(); ++i )
3655 if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 )
3656 nodesToRemove.insert( nodesToRemove.end(), grid._nodes[i] );
3659 TIDSortedNodeSet::iterator n = nodesToRemove.begin();
3660 for ( ; n != nodesToRemove.end(); ++n )
3661 meshDS->RemoveFreeNode( *n, smDS, /*fromGroups=*/false );
3667 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
3668 catch ( SMESH_ComputeError& e)
3670 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
3675 //=============================================================================
3679 //=============================================================================
3681 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & theMesh,
3682 const TopoDS_Shape & theShape,
3683 MapShapeNbElems& theResMap)
3686 // std::vector<int> aResVec(SMDSEntity_Last);
3687 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
3688 // if(IsQuadratic) {
3689 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3690 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
3691 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
3694 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
3695 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3697 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
3698 // aResMap.insert(std::make_pair(sm,aResVec));
3703 //=============================================================================
3707 * \brief Event listener setting/unsetting _alwaysComputed flag to
3708 * submeshes of inferior levels to prevent their computing
3710 struct _EventListener : public SMESH_subMeshEventListener
3714 _EventListener(const string& algoName):
3715 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
3718 // --------------------------------------------------------------------------------
3719 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
3721 static void setAlwaysComputed( const bool isComputed,
3722 SMESH_subMesh* subMeshOfSolid)
3724 SMESH_subMeshIteratorPtr smIt =
3725 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3726 while ( smIt->more() )
3728 SMESH_subMesh* sm = smIt->next();
3729 sm->SetIsAlwaysComputed( isComputed );
3731 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3734 // --------------------------------------------------------------------------------
3735 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
3737 virtual void ProcessEvent(const int event,
3738 const int eventType,
3739 SMESH_subMesh* subMeshOfSolid,
3740 SMESH_subMeshEventListenerData* data,
3741 const SMESH_Hypothesis* hyp = 0)
3743 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
3745 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
3750 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
3751 if ( !algo3D || _algoName != algo3D->GetName() )
3752 setAlwaysComputed( false, subMeshOfSolid );
3756 // --------------------------------------------------------------------------------
3757 // set the event listener
3759 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
3761 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
3766 }; // struct _EventListener
3770 //================================================================================
3772 * \brief Sets event listener to submeshes if necessary
3773 * \param subMesh - submesh where algo is set
3774 * This method is called when a submesh gets HYP_OK algo_state.
3775 * After being set, event listener is notified on each event of a submesh.
3777 //================================================================================
3779 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
3781 _EventListener::SetOn( subMesh, GetName() );
3784 //================================================================================
3786 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
3788 //================================================================================
3790 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
3791 const TopoDS_Shape& theShape)
3793 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
3794 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));