1 // Copyright (C) 2007-2023 CEA, EDF, 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"
26 #include "StdMeshers_CartesianParameters3D.hxx"
27 #include "StdMeshers_Cartesian_VL.hxx"
28 #include "StdMeshers_FaceSide.hxx"
29 #include "StdMeshers_ViscousLayers.hxx"
31 #include <ObjectPool.hxx>
32 #include <SMDS_LinearEdge.hxx>
33 #include <SMDS_MeshNode.hxx>
34 #include <SMDS_VolumeOfNodes.hxx>
35 #include <SMDS_VolumeTool.hxx>
36 #include <SMESHDS_Mesh.hxx>
37 #include <SMESH_Block.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_ControlsDef.hxx>
40 #include <SMESH_Mesh.hxx>
41 #include <SMESH_MeshAlgos.hxx>
42 #include <SMESH_MeshEditor.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_subMesh.hxx>
45 #include <SMESH_subMeshEventListener.hxx>
47 #include <utilities.h>
48 #include <Utils_ExceptHandlers.hxx>
50 #include <GEOMUtils.hxx>
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Surface.hxx>
54 #include <BRepBndLib.hxx>
55 #include <BRepBuilderAPI_Copy.hxx>
56 #include <BRepBuilderAPI_MakeFace.hxx>
57 #include <BRepTools.hxx>
58 #include <BRepTopAdaptor_FClass2d.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <Bnd_Box.hxx>
64 #include <GCPnts_UniformDeflection.hxx>
65 #include <Geom2d_BSplineCurve.hxx>
66 #include <Geom2d_BezierCurve.hxx>
67 #include <Geom2d_TrimmedCurve.hxx>
68 #include <GeomAPI_ProjectPointOnSurf.hxx>
69 #include <GeomLib.hxx>
70 #include <Geom_BSplineCurve.hxx>
71 #include <Geom_BSplineSurface.hxx>
72 #include <Geom_BezierCurve.hxx>
73 #include <Geom_BezierSurface.hxx>
74 #include <Geom_RectangularTrimmedSurface.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <IntAna_IntConicQuad.hxx>
77 #include <IntAna_IntLinTorus.hxx>
78 #include <IntAna_Quadric.hxx>
79 #include <IntCurveSurface_TransitionOnCurve.hxx>
80 #include <IntCurvesFace_Intersector.hxx>
81 #include <Poly_Triangulation.hxx>
82 #include <Precision.hxx>
84 #include <TopExp_Explorer.hxx>
85 #include <TopLoc_Location.hxx>
86 #include <TopTools_DataMapOfShapeInteger.hxx>
87 #include <TopTools_IndexedMapOfShape.hxx>
88 #include <TopTools_MapOfShape.hxx>
90 #include <TopoDS_Compound.hxx>
91 #include <TopoDS_Face.hxx>
92 #include <TopoDS_TShape.hxx>
93 #include <gp_Cone.hxx>
94 #include <gp_Cylinder.hxx>
97 #include <gp_Pnt2d.hxx>
98 #include <gp_Sphere.hxx>
99 #include <gp_Torus.hxx>
103 #include <boost/container/flat_map.hpp>
106 // #define _MY_DEBUG_
113 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
114 // Windows 10 = 0x0A00
115 #define WINVER 0x0A00
116 #define _WIN32_WINNT 0x0A00
119 #include <tbb/parallel_for.h>
120 //#include <tbb/enumerable_thread_specific.h>
124 using namespace SMESH;
126 //=============================================================================
130 //=============================================================================
132 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
133 :SMESH_3D_Algo(hypId, gen)
135 _name = "Cartesian_3D";
136 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
137 _compatibleHypothesis.push_back( "CartesianParameters3D" );
138 _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
140 _onlyUnaryInput = false; // to mesh all SOLIDs at once
141 _requireDiscreteBoundary = false; // 2D mesh not needed
142 _supportSubmeshes = false; // do not use any existing mesh
145 //=============================================================================
147 * Check presence of a hypothesis
149 //=============================================================================
151 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
152 const TopoDS_Shape& aShape,
153 Hypothesis_Status& aStatus)
155 aStatus = SMESH_Hypothesis::HYP_MISSING;
157 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, /*skipAux=*/false);
158 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
159 if ( h == hyps.end())
165 _hypViscousLayers = nullptr;
166 _isComputeOffset = false;
168 for ( ; h != hyps.end(); ++h )
170 if ( !_hyp && ( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
172 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
176 _hypViscousLayers = dynamic_cast<const StdMeshers_ViscousLayers*>( *h );
180 return aStatus == HYP_OK;
185 typedef int TGeomID; // IDs of sub-shapes
186 typedef TopTools_ShapeMapHasher TShapeHasher; // non-oriented shape hasher
187 typedef std::array< int, 3 > TIJK;
189 const TGeomID theUndefID = 1e+9;
191 //=============================================================================
192 // Definitions of internal utils
193 // --------------------------------------------------------------------------
195 Trans_TANGENT = IntCurveSurface_Tangent,
196 Trans_IN = IntCurveSurface_In,
197 Trans_OUT = IntCurveSurface_Out,
199 Trans_INTERNAL // for INTERNAL FACE
201 // --------------------------------------------------------------------------
203 * \brief Sub-entities of a FACE neighboring its concave VERTEX.
204 * Help to avoid linking nodes on EDGEs that seem connected
205 * by the concave FACE but the link actually lies outside the FACE
209 TGeomID _concaveFace;
210 TGeomID _edge1, _edge2;
212 ConcaveFace( int f=0, int e1=0, int e2=0, int v1=0, int v2=0 )
213 : _concaveFace(f), _edge1(e1), _edge2(e2), _v1(v1), _v2(v2) {}
214 bool HasEdge( TGeomID edge ) const { return edge == _edge1 || edge == _edge2; }
215 bool HasVertex( TGeomID v ) const { return v == _v1 || v == _v2; }
216 void SetEdge( TGeomID edge ) { ( _edge1 ? _edge2 : _edge1 ) = edge; }
217 void SetVertex( TGeomID v ) { ( _v1 ? _v2 : _v1 ) = v; }
219 typedef NCollection_DataMap< TGeomID, ConcaveFace > TConcaveVertex2Face;
220 // --------------------------------------------------------------------------
222 * \brief Container of IDs of SOLID sub-shapes
224 class Solid // sole SOLID contains all sub-shapes
226 TGeomID _id; // SOLID id
227 bool _hasInternalFaces;
228 TConcaveVertex2Face _concaveVertex; // concave VERTEX -> ConcaveFace
231 virtual bool Contains( TGeomID /*subID*/ ) const { return true; }
232 virtual bool ContainsAny( const vector< TGeomID>& /*subIDs*/ ) const { return true; }
233 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
234 virtual bool IsOutsideOriented( TGeomID /*faceID*/ ) const { return true; }
235 void SetID( TGeomID id ) { _id = id; }
236 TGeomID ID() const { return _id; }
237 void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
238 bool HasInternalFaces() const { return _hasInternalFaces; }
239 void SetConcave( TGeomID V, TGeomID F, TGeomID E1, TGeomID E2, TGeomID V1, TGeomID V2 )
240 { _concaveVertex.Bind( V, ConcaveFace{ F, E1, E2, V1, V2 }); }
241 bool HasConcaveVertex() const { return !_concaveVertex.IsEmpty(); }
242 const ConcaveFace* GetConcave( TGeomID V ) const { return _concaveVertex.Seek( V ); }
244 // --------------------------------------------------------------------------
245 class OneOfSolids : public Solid
247 TColStd_MapOfInteger _subIDs;
248 TopTools_MapOfShape _faces; // keep FACE orientation
249 TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
251 void Init( const TopoDS_Shape& solid,
252 TopAbs_ShapeEnum subType,
253 const SMESHDS_Mesh* mesh );
254 virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
255 virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
257 for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
260 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
262 const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
263 return sInMap.Orientation();
265 virtual bool IsOutsideOriented( TGeomID faceID ) const
267 return faceID == 0 || _outFaceIDs.Contains( faceID );
270 // --------------------------------------------------------------------------
272 * \brief Hold a vector of TGeomID and clear it at destruction
274 class GeomIDVecHelder
276 typedef std::vector< TGeomID > TVector;
277 const TVector& myVec;
281 GeomIDVecHelder( const TVector& idVec, bool isOwner ): myVec( idVec ), myOwn( isOwner ) {}
282 GeomIDVecHelder( const GeomIDVecHelder& holder ): myVec( holder.myVec ), myOwn( holder.myOwn )
284 const_cast< bool& >( holder.myOwn ) = false;
286 ~GeomIDVecHelder() { if ( myOwn ) const_cast<TVector&>( myVec ).clear(); }
287 size_t size() const { return myVec.size(); }
288 TGeomID operator[]( size_t i ) const { return i < size() ? myVec[i] : theUndefID; }
289 bool operator==( const GeomIDVecHelder& other ) const { return myVec == other.myVec; }
290 bool contain( const TGeomID& id ) const {
291 return std::find( myVec.begin(), myVec.end(), id ) != myVec.end();
293 TGeomID otherThan( const TGeomID& id ) const {
294 for ( const TGeomID& id2 : myVec )
299 TGeomID oneCommon( const GeomIDVecHelder& other ) const {
300 TGeomID common = theUndefID;
301 for ( const TGeomID& id : myVec )
302 if ( other.contain( id ))
304 if ( common != theUndefID )
311 // --------------------------------------------------------------------------
317 TopoDS_Shape _mainShape;
318 vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
320 map< TGeomID, OneOfSolids > _solidByID;
321 TColStd_MapOfInteger _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
322 TColStd_MapOfInteger _strangeEdges; // EDGEs shared by strange FACEs
323 TGeomID _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
325 TopTools_DataMapOfShapeInteger _shape2NbNodes; // nb of pre-existing nodes on shapes
327 Controls::ElementsOnShape _edgeClassifier;
328 Controls::ElementsOnShape _vertexClassifier;
330 bool IsOneSolid() const { return _solidByID.size() < 2; }
331 GeomIDVecHelder GetSolidIDsByShapeID( const vector< TGeomID >& shapeIDs ) const;
333 // --------------------------------------------------------------------------
335 * \brief Common data of any intersection between a Grid and a shape
337 struct B_IntersectPoint
339 mutable const SMDS_MeshNode* _node;
340 mutable vector< TGeomID > _faceIDs;
342 B_IntersectPoint(): _node(NULL) {}
343 bool Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
344 TGeomID HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace=-1 ) const;
345 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID * commonFaces ) const;
346 bool IsOnFace( TGeomID faceID ) const;
347 virtual ~B_IntersectPoint() {}
349 // --------------------------------------------------------------------------
351 * \brief Data of intersection between a GridLine and a TopoDS_Face
353 struct F_IntersectPoint : public B_IntersectPoint
357 mutable Transition _transition;
358 mutable size_t _indexOnLine;
360 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
362 // --------------------------------------------------------------------------
364 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
366 struct E_IntersectPoint : public B_IntersectPoint
370 TGeomID _shapeID; // ID of EDGE or VERTEX
372 // --------------------------------------------------------------------------
374 * \brief A line of the grid and its intersections with 2D geometry
379 double _length; // line length
380 multiset< F_IntersectPoint > _intPoints;
382 void RemoveExcessIntPoints( const double tol );
383 TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
384 const TGeomID prevID,
385 const Geometry& geom);
387 // --------------------------------------------------------------------------
389 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
394 vector< gp_XYZ > _origins; // origin points of all planes in one direction
395 vector< double > _zProjs; // projections of origins to _zNorm
397 // --------------------------------------------------------------------------
399 * \brief Iterator on the parallel grid lines of one direction
405 size_t _iVar1, _iVar2, _iConst;
406 string _name1, _name2, _nameConst;
408 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
409 size_t iv1, size_t iv2, size_t iConst,
410 const string& nv1, const string& nv2, const string& nConst )
412 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
413 _curInd[0] = _curInd[1] = _curInd[2] = 0;
414 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
415 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
418 size_t I() const { return _curInd[0]; }
419 size_t J() const { return _curInd[1]; }
420 size_t K() const { return _curInd[2]; }
421 void SetIJK( size_t i, size_t j, size_t k )
423 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
425 void SetLineIndex(size_t i)
427 _curInd[_iVar2] = i / _size[_iVar1];
428 _curInd[_iVar1] = i % _size[_iVar1];
432 if ( ++_curInd[_iVar1] == _size[_iVar1] )
433 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
435 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
436 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
437 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
438 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
439 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
440 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
441 bool IsValidIndexOnLine (size_t i) const { return i < _size[ _iConst ]; }
442 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
444 struct FaceGridIntersector;
445 // --------------------------------------------------------------------------
447 * \brief Container of GridLine's
451 vector< double > _coords[3]; // coordinates of grid nodes
452 gp_XYZ _axes [3]; // axis directions
453 vector< GridLine > _lines [3]; // in 3 directions
454 double _tol, _minCellSize;
456 gp_Mat _invB; // inverted basis of _axes
458 // index shift within _nodes of nodes of a cell from the 1st node
461 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
462 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
463 ObjectPool< E_IntersectPoint > _edgeIntPool; // intersections with EDGEs
464 ObjectPool< F_IntersectPoint > _extIntPool; // intersections with extended INTERNAL FACEs
465 //list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
470 bool _toConsiderInternalFaces;
471 bool _toUseThresholdForInternalFaces;
472 double _sizeThreshold;
474 SMESH_MesherHelper* _helper;
476 size_t CellIndex( size_t i, size_t j, size_t k ) const
478 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
480 size_t NodeIndex( size_t i, size_t j, size_t k ) const
482 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
484 size_t NodeIndex( const TIJK& ijk ) const
486 return NodeIndex( ijk[0], ijk[1], ijk[2] );
488 size_t NodeIndexDX() const { return 1; }
489 size_t NodeIndexDY() const { return _coords[0].size(); }
490 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
492 LineIndexer GetLineIndexer(size_t iDir) const;
493 size_t GetLineDir( const GridLine* line, size_t & index ) const;
495 E_IntersectPoint* Add( const E_IntersectPoint& ip )
497 E_IntersectPoint* eip = _edgeIntPool.getNew();
501 void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
503 TGeomID ShapeID( const TopoDS_Shape& s ) const;
504 const TopoDS_Shape& Shape( TGeomID id ) const;
505 TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
506 void InitGeometry( const TopoDS_Shape& theShape );
507 void InitClassifier( const TopoDS_Shape& mainShape,
508 TopAbs_ShapeEnum shapeType,
509 Controls::ElementsOnShape& classifier );
510 void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
511 const TopoDS_Shape& shape,
512 const vector< TopoDS_Shape >& faces );
513 void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
514 bool IsShared( TGeomID faceID ) const;
515 bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
516 bool IsInternal( TGeomID faceID ) const {
517 return ( faceID == PseudoIntExtFaceID() ||
518 Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
519 bool IsSolid( TGeomID shapeID ) const {
520 if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
521 else return _geometry._solidByID.count( shapeID ); }
522 bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
523 TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
524 Solid* GetSolid( TGeomID solidID = 0 );
525 Solid* GetOneOfSolids( TGeomID solidID );
526 const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
527 bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
528 bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
529 void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
530 TopoDS_Vertex* vertex = nullptr, bool unset = false );
531 void UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex );
532 bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
533 bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
535 void SetCoordinates(const vector<double>& xCoords,
536 const vector<double>& yCoords,
537 const vector<double>& zCoords,
538 const double* axesDirs,
539 const Bnd_Box& bndBox );
540 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
541 void ComputeNodes(SMESH_MesherHelper& helper);
543 // --------------------------------------------------------------------------
545 * \brief Return cells sharing a link
547 struct CellsAroundLink
555 CellsAroundLink( Grid* grid, int iDir ):
557 _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
558 _nbCells{ grid->_coords[0].size() - 1,
559 grid->_coords[1].size() - 1,
560 grid->_coords[2].size() - 1 },
563 const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
564 _dInd[1][ iDirOther[iDir][0] ] = -1;
565 _dInd[2][ iDirOther[iDir][1] ] = -1;
566 _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
568 void Init( int i, int j, int k, int link12 = 0 )
571 _i = i - _dInd[iL][0];
572 _j = j - _dInd[iL][1];
573 _k = k - _dInd[iL][2];
575 bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
577 i = _i + _dInd[iL][0];
578 j = _j + _dInd[iL][1];
579 k = _k + _dInd[iL][2];
580 if ( i < 0 || i >= (int)_nbCells[0] ||
581 j < 0 || j >= (int)_nbCells[1] ||
582 k < 0 || k >= (int)_nbCells[2] )
584 cellIndex = _grid->CellIndex( i,j,k );
585 linkIndex = iL + _iDir * 4;
589 // --------------------------------------------------------------------------
591 * \brief Intersector of TopoDS_Face with all GridLine's
593 struct FaceGridIntersector
599 IntCurvesFace_Intersector* _surfaceInt;
600 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
602 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
605 void StoreIntersections()
607 for ( size_t i = 0; i < _intersections.size(); ++i )
609 multiset< F_IntersectPoint >::iterator ip =
610 _intersections[i].first->_intPoints.insert( _intersections[i].second );
611 ip->_faceIDs.reserve( 1 );
612 ip->_faceIDs.push_back( _faceID );
615 const Bnd_Box& GetFaceBndBox()
617 GetCurveFaceIntersector();
620 IntCurvesFace_Intersector* GetCurveFaceIntersector()
624 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
625 _bndBox = _surfaceInt->Bounding();
626 if ( _bndBox.IsVoid() )
627 BRepBndLib::Add (_face, _bndBox);
631 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
633 // --------------------------------------------------------------------------
635 * \brief Intersector of a surface with a GridLine
637 struct FaceLineIntersector
640 double _u, _v, _w; // params on the face and the line
641 Transition _transition; // transition at intersection (see IntCurveSurface.cdl)
642 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
645 gp_Cylinder _cylinder;
649 IntCurvesFace_Intersector* _surfaceInt;
651 vector< F_IntersectPoint > _intPoints;
653 void IntersectWithPlane (const GridLine& gridLine);
654 void IntersectWithCylinder(const GridLine& gridLine);
655 void IntersectWithCone (const GridLine& gridLine);
656 void IntersectWithSphere (const GridLine& gridLine);
657 void IntersectWithTorus (const GridLine& gridLine);
658 void IntersectWithSurface (const GridLine& gridLine);
660 bool UVIsOnFace() const;
661 void addIntPoint(const bool toClassify=true);
662 bool isParamOnLineOK( const double linLength )
664 return -_tol < _w && _w < linLength + _tol;
666 FaceLineIntersector():_surfaceInt(0) {}
667 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
669 // --------------------------------------------------------------------------
671 * \brief Class representing topology of the hexahedron and creating a mesh
672 * volume basing on analysis of hexahedron intersection with geometry
676 // --------------------------------------------------------------------------------
679 enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
680 // --------------------------------------------------------------------------------
681 struct _Node //!< node either at a hexahedron corner or at intersection
683 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
684 const B_IntersectPoint* _intPoint;
685 const _Face* _usedInFace;
686 char _isInternalFlags;
688 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
689 :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {}
690 const SMDS_MeshNode* Node() const
691 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
692 const E_IntersectPoint* EdgeIntPnt() const
693 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
694 const F_IntersectPoint* FaceIntPnt() const
695 { return static_cast< const F_IntersectPoint* >( _intPoint ); }
696 const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
697 TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
698 void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
699 bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
700 bool IsUsedInFace( const _Face* polygon = 0 )
702 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
704 TGeomID IsLinked( const B_IntersectPoint* other,
705 TGeomID avoidFace=-1 ) const // returns id of a common face
707 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
709 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
711 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
713 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
715 return _intPoint && other ? _intPoint->GetCommonFaces( other, common ) : 0;
719 if ( const SMDS_MeshNode* n = Node() )
720 return SMESH_NodeXYZ( n );
721 if ( const E_IntersectPoint* eip =
722 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
724 return gp_Pnt( 1e100, 0, 0 );
726 TGeomID ShapeID() const
728 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
729 return eip->_shapeID;
732 void Add( const E_IntersectPoint* ip )
734 // Possible cases before Add(ip):
735 /// 1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
736 /// 2) _node == 0 && _intPoint._node != 0 --> link intersected by FACE
737 /// 3) _node == 0 && _intPoint._node == 0 --> _Node at EDGE intersection
739 // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
740 // at creation of elements
741 // To recognize this case, set _intPoint._node = Node()
742 const SMDS_MeshNode* node = Node();
747 ip->Add( _intPoint->_faceIDs );
751 _node = _intPoint->_node = node;
754 // --------------------------------------------------------------------------------
755 struct _Link // link connecting two _Node's
758 _Face* _faces[2]; // polygons sharing a link
759 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
760 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
761 vector< _Link > _splits;
762 _Link(): _faces{ 0, 0 } {}
764 // --------------------------------------------------------------------------------
769 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
770 void Reverse() { _reverse = !_reverse; }
771 size_t NbResultLinks() const { return _link->_splits.size(); }
772 _OrientedLink ResultLink(int i) const
774 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
776 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
777 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
778 operator bool() const { return _link; }
779 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
781 vector< TGeomID > faces;
782 const B_IntersectPoint *ip0, *ip1;
783 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
784 ( ip1 = _link->_nodes[1]->_intPoint ))
786 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
787 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
788 !usedIDs.count( ip0->_faceIDs[i] ) )
789 faces.push_back( ip0->_faceIDs[i] );
793 bool HasEdgeNodes() const
795 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
796 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
800 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
802 void AddFace( _Face* f )
804 if ( _link->_faces[0] )
806 _link->_faces[1] = f;
810 _link->_faces[0] = f;
811 _link->_faces[1] = 0;
814 void RemoveFace( _Face* f )
816 if ( !_link->_faces[0] ) return;
818 if ( _link->_faces[1] == f )
820 _link->_faces[1] = 0;
822 else if ( _link->_faces[0] == f )
824 _link->_faces[0] = 0;
825 if ( _link->_faces[1] )
827 _link->_faces[0] = _link->_faces[1];
828 _link->_faces[1] = 0;
833 // --------------------------------------------------------------------------------
834 struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
836 struct _Split // data of a link split
838 int _linkID; // hex link ID
840 int _iCheckIteration; // iteration where split is tried as Hexahedron split
841 _Link* _checkedSplit; // split set to hex links
842 bool _isUsed; // used in a volume
844 _Split( _Link & split, int iLink ):
845 _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
846 _iCheckIteration( 0 ), _isUsed( false )
848 bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
851 std::vector< _Split > _splits;
855 std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
857 _SplitIterator( _Link* hexLinks ):
858 _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
860 _freeNodes.reserve( 12 );
861 _splits.reserve( 24 );
862 for ( int iL = 0; iL < 12; ++iL )
863 for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
864 _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
867 bool More() const { return _nbUsed < _splits.size(); }
870 // --------------------------------------------------------------------------------
873 SMESH_Block::TShapeID _name;
874 vector< _OrientedLink > _links; // links on GridLine's
875 vector< _Link > _polyLinks; // links added to close a polygonal face
876 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
878 _Face():_name( SMESH_Block::ID_NONE )
880 bool IsPolyLink( const _OrientedLink& ol )
882 return _polyLinks.empty() ? false :
883 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
885 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
887 if ( faceToFindEqual && faceToFindEqual != this ) {
888 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
889 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
890 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
893 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
900 _polyLinks.push_back( l );
901 _links.push_back( _OrientedLink( &_polyLinks.back() ));
904 // --------------------------------------------------------------------------------
905 struct _volumeDef // holder of nodes of a volume mesh element
911 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
912 const B_IntersectPoint* _intPoint;
914 _nodeDef(): _node(0), _intPoint(0) {}
915 _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
916 const SMDS_MeshNode* Node() const
917 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
918 const E_IntersectPoint* EdgeIntPnt() const
919 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
920 _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
921 bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
924 vector< _nodeDef > _nodes;
925 vector< int > _quantities;
926 _volumeDef* _next; // to store several _volumeDefs in a chain
929 const SMDS_MeshElement* _volume; // new volume
931 vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
933 _volumeDef(): _next(0), _solidID(0), _size(0), _volume(0) {}
934 ~_volumeDef() { delete _next; }
935 _volumeDef( _volumeDef& other ):
936 _next(0), _solidID( other._solidID ), _size( other._size ), _volume( other._volume )
937 { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
938 _names.swap( other._names ); }
940 size_t size() const { return 1 + ( _next ? _next->size() : 0 ); } // nb _volumeDef in a chain
941 _volumeDef* at(int index)
942 { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
944 void Set( _Node** nodes, int nb )
945 { _nodes.assign( nodes, nodes + nb ); }
947 void SetNext( _volumeDef* vd )
948 { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
950 bool IsEmpty() const { return (( _nodes.empty() ) &&
951 ( !_next || _next->IsEmpty() )); }
952 bool IsPolyhedron() const { return ( !_quantities.empty() ||
953 ( _next && !_next->_quantities.empty() )); }
956 struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
958 _nodeDef _node1;//, _node2;
959 mutable /*const */_linkDef *_prev, *_next;
962 _linkDef():_prev(0), _next(0) {}
964 void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
966 _node1 = n1; //_node2 = n2;
970 if ( first > second ) std::swap( first, second );
972 void setNext( _linkDef* next )
980 // topology of a hexahedron
982 _Link _hexLinks [12];
985 // faces resulted from hexahedron intersection
986 vector< _Face > _polygons;
988 // intresections with EDGEs
989 vector< const E_IntersectPoint* > _eIntPoints;
991 // additional nodes created at intersection points
992 vector< _Node > _intNodes;
994 // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
995 vector< _Node* > _vIntNodes;
997 // computed volume elements
998 _volumeDef _volumeDefs;
1001 double _sideLength[3];
1002 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
1003 int _origNodeInd; // index of _hexNodes[0] node within the _grid
1009 Hexahedron(Grid* grid);
1010 int MakeElements(SMESH_MesherHelper& helper,
1011 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1012 void computeElements( const Solid* solid = 0, int solidIndex = -1 );
1015 Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
1016 void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
1017 void init( size_t i );
1018 void setIJK( size_t i );
1019 bool compute( const Solid* solid, const IsInternalFlag intFlag );
1020 size_t getSolids( TGeomID ids[] );
1021 bool isCutByInternalFace( IsInternalFlag & maxFlag );
1022 void addEdges(SMESH_MesherHelper& helper,
1023 vector< Hexahedron* >& intersectedHex,
1024 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1025 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
1026 double proj, BRepAdaptor_Curve& curve,
1027 const gp_XYZ& axis, const gp_XYZ& origin );
1028 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
1029 bool addIntersection( const E_IntersectPoint* ip,
1030 vector< Hexahedron* >& hexes,
1031 int ijk[], int dIJK[] );
1032 bool isQuadOnFace( const size_t iQuad );
1033 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
1034 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
1035 bool findChainOnEdge( const vector< _OrientedLink >& splits,
1036 const _OrientedLink& prevSplit,
1037 const _OrientedLink& avoidSplit,
1038 const std::set< TGeomID > & concaveFaces,
1041 vector<_Node*>& chn);
1042 int addVolumes(SMESH_MesherHelper& helper );
1043 void addFaces( SMESH_MesherHelper& helper,
1044 const vector< const SMDS_MeshElement* > & boundaryVolumes );
1045 void addSegments( SMESH_MesherHelper& helper,
1046 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
1047 void getVolumes( vector< const SMDS_MeshElement* > & volumes );
1048 void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
1049 void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
1050 void removeExcessNodes(vector< Hexahedron* >& allHexa);
1051 void preventVolumesOverlapping();
1052 TGeomID getAnyFace() const;
1053 void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
1054 const TColStd_MapOfInteger& intEdgeIDs );
1055 gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
1056 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
1057 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
1058 bool isInHole() const;
1059 bool hasStrangeEdge() const;
1060 bool checkPolyhedronSize( bool isCutByInternalFace, double & volSize ) const;
1065 bool debugDumpLink( _Link* link );
1066 _Node* findEqualNode( vector< _Node* >& nodes,
1067 const E_IntersectPoint* ip,
1070 for ( size_t i = 0; i < nodes.size(); ++i )
1071 if ( nodes[i]->EdgeIntPnt() == ip ||
1072 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
1076 bool isCorner( const _Node* node ) const { return ( node >= &_hexNodes[0] &&
1077 node - &_hexNodes[0] < 8 ); }
1078 bool hasEdgesAround( const ConcaveFace* cf ) const;
1079 bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
1080 bool isOutParam(const double uvw[3]) const;
1082 typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
1083 static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
1085 TID2Nb::value_type s0( id, 0 );
1086 TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
1089 }; // class Hexahedron
1092 // --------------------------------------------------------------------------
1094 * \brief Hexahedron computing volumes in one thread
1096 struct ParallelHexahedron
1098 vector< Hexahedron* >& _hexVec;
1099 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
1100 void operator() ( const tbb::blocked_range<size_t>& r ) const
1102 for ( size_t i = r.begin(); i != r.end(); ++i )
1103 if ( Hexahedron* hex = _hexVec[ i ] )
1104 hex->computeElements();
1107 // --------------------------------------------------------------------------
1109 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1111 struct ParallelIntersector
1113 vector< FaceGridIntersector >& _faceVec;
1114 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1115 void operator() ( const tbb::blocked_range<size_t>& r ) const
1117 for ( size_t i = r.begin(); i != r.end(); ++i )
1118 _faceVec[i].Intersect();
1123 //=============================================================================
1124 // Implementation of internal utils
1125 //=============================================================================
1127 * \brief adjust \a i to have \a val between values[i] and values[i+1]
1129 inline void locateValue( int & i, double val, const vector<double>& values,
1130 int& di, double tol )
1132 //val += values[0]; // input \a val is measured from 0.
1133 if ( i > (int) values.size()-2 )
1134 i = values.size()-2;
1136 while ( i+2 < (int) values.size() && val > values[ i+1 ])
1138 while ( i > 0 && val < values[ i ])
1141 if ( i > 0 && val - values[ i ] < tol )
1143 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1148 //=============================================================================
1150 * Return a vector of SOLIDS sharing given shapes
1152 GeomIDVecHelder Geometry::GetSolidIDsByShapeID( const vector< TGeomID >& theShapeIDs ) const
1154 if ( theShapeIDs.size() == 1 )
1155 return GeomIDVecHelder( _solidIDsByShapeID[ theShapeIDs[ 0 ]], /*owner=*/false );
1157 // look for an empty slot in _solidIDsByShapeID
1158 vector< TGeomID > * resultIDs = 0;
1159 for ( const vector< TGeomID >& vec : _solidIDsByShapeID )
1162 resultIDs = const_cast< vector< TGeomID > * >( & vec );
1165 // fill in resultIDs
1166 for ( const TGeomID& id : theShapeIDs )
1167 for ( const TGeomID& solid : _solidIDsByShapeID[ id ])
1169 if ( std::find( resultIDs->begin(), resultIDs->end(), solid ) == resultIDs->end() )
1170 resultIDs->push_back( solid );
1172 return GeomIDVecHelder( *resultIDs, /*owner=*/true );
1174 //=============================================================================
1176 * Remove coincident intersection points
1178 void GridLine::RemoveExcessIntPoints( const double tol )
1180 if ( _intPoints.size() < 2 ) return;
1182 set< Transition > tranSet;
1183 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1184 while ( ip2 != _intPoints.end() )
1188 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1190 tranSet.insert( ip1->_transition );
1191 tranSet.insert( ip2->_transition );
1192 ip2->Add( ip1->_faceIDs );
1193 _intPoints.erase( ip1 );
1196 if ( tranSet.size() > 1 ) // points with different transition coincide
1198 bool isIN = tranSet.count( Trans_IN );
1199 bool isOUT = tranSet.count( Trans_OUT );
1200 if ( isIN && isOUT )
1201 (*ip1)._transition = Trans_TANGENT;
1203 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1207 //================================================================================
1209 * Return ID of SOLID for nodes before the given intersection point
1211 TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1212 const TGeomID prevID,
1213 const Geometry& geom )
1215 if ( ip == _intPoints.begin() )
1218 if ( geom.IsOneSolid() )
1221 switch ( ip->_transition ) {
1222 case Trans_IN: isOut = true; break;
1223 case Trans_OUT: isOut = false; break;
1224 case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1227 // singularity point (apex of a cone)
1228 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1229 if ( ipAft == _intPoints.end() )
1234 if ( ipBef->_transition != ipAft->_transition )
1235 isOut = ( ipBef->_transition == Trans_OUT );
1237 isOut = ( ipBef->_transition != Trans_OUT );
1241 case Trans_INTERNAL: isOut = false;
1244 return isOut ? 0 : geom._soleSolid.ID();
1247 GeomIDVecHelder solids = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1250 if ( ip->_transition == Trans_INTERNAL )
1253 GeomIDVecHelder solidsBef = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1255 if ( ip->_transition == Trans_IN ||
1256 ip->_transition == Trans_OUT )
1258 if ( solidsBef.size() == 1 )
1260 if ( solidsBef[0] == prevID )
1261 return ip->_transition == Trans_OUT ? 0 : solidsBef[0];
1263 return solidsBef[0];
1266 if ( solids.size() == 2 )
1268 if ( solids == solidsBef )
1269 return solids.contain( prevID ) ? solids.otherThan( prevID ) : theUndefID; // bos #29212
1271 return solids.oneCommon( solidsBef );
1274 if ( solidsBef.size() == 1 )
1275 return solidsBef[0];
1277 return solids.oneCommon( solidsBef );
1279 //================================================================================
1283 bool B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1284 const SMDS_MeshNode* n) const
1286 size_t prevNbF = _faceIDs.size();
1288 if ( _faceIDs.empty() )
1291 for ( size_t i = 0; i < fIDs.size(); ++i )
1293 vector< TGeomID >::iterator it =
1294 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1295 if ( it == _faceIDs.end() )
1296 _faceIDs.push_back( fIDs[i] );
1301 return prevNbF < _faceIDs.size();
1303 //================================================================================
1305 * Return ID of a common face if any, else zero
1307 TGeomID B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace ) const
1310 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1311 if ( avoidFace != other->_faceIDs[i] &&
1312 IsOnFace ( other->_faceIDs[i] ))
1313 return other->_faceIDs[i];
1316 //================================================================================
1318 * Return faces common with other point
1320 size_t B_IntersectPoint::GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
1325 if ( _faceIDs.size() > other->_faceIDs.size() )
1326 return other->GetCommonFaces( this, common );
1327 for ( const TGeomID& face : _faceIDs )
1328 if ( other->IsOnFace( face ))
1329 common[ nbComm++ ] = face;
1332 //================================================================================
1334 * Return \c true if \a faceID in in this->_faceIDs
1336 bool B_IntersectPoint::IsOnFace( TGeomID faceID ) const // returns true if faceID is found
1338 vector< TGeomID >::const_iterator it =
1339 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1340 return ( it != _faceIDs.end() );
1342 //================================================================================
1344 * OneOfSolids initialization
1346 void OneOfSolids::Init( const TopoDS_Shape& solid,
1347 TopAbs_ShapeEnum subType,
1348 const SMESHDS_Mesh* mesh )
1350 SetID( mesh->ShapeToIndex( solid ));
1352 if ( subType == TopAbs_FACE )
1353 SetHasInternalFaces( false );
1355 for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1357 _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1358 if ( subType == TopAbs_FACE )
1360 _faces.Add( sub.Current() );
1361 if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1362 SetHasInternalFaces( true );
1364 TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1365 if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1366 sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1367 _outFaceIDs.Add( faceID );
1371 //================================================================================
1373 * Return an iterator on GridLine's in a given direction
1375 LineIndexer Grid::GetLineIndexer(size_t iDir) const
1377 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1378 const string s [] = { "X", "Y", "Z" };
1379 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
1380 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
1381 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1384 //================================================================================
1386 * Return direction [0,1,2] of a GridLine
1388 size_t Grid::GetLineDir( const GridLine* line, size_t & index ) const
1390 for ( size_t iDir = 0; iDir < 3; ++iDir )
1391 if ( &_lines[ iDir ][0] <= line && line <= &_lines[ iDir ].back() )
1393 index = line - &_lines[ iDir ][0];
1398 //=============================================================================
1400 * Creates GridLine's of the grid
1402 void Grid::SetCoordinates(const vector<double>& xCoords,
1403 const vector<double>& yCoords,
1404 const vector<double>& zCoords,
1405 const double* axesDirs,
1406 const Bnd_Box& shapeBox)
1408 _coords[0] = xCoords;
1409 _coords[1] = yCoords;
1410 _coords[2] = zCoords;
1412 _axes[0].SetCoord( axesDirs[0],
1415 _axes[1].SetCoord( axesDirs[3],
1418 _axes[2].SetCoord( axesDirs[6],
1421 _axes[0].Normalize();
1422 _axes[1].Normalize();
1423 _axes[2].Normalize();
1425 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1428 // compute tolerance
1429 _minCellSize = Precision::Infinite();
1430 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1432 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1434 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1435 if ( cellLen < _minCellSize )
1436 _minCellSize = cellLen;
1439 if ( _minCellSize < Precision::Confusion() )
1440 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1441 SMESH_Comment("Too small cell size: ") << _minCellSize );
1442 _tol = _minCellSize / 1000.;
1444 // attune grid extremities to shape bounding box
1446 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1447 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1448 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1449 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
1450 for ( int i = 0; i < 6; ++i )
1451 if ( fabs( sP[i] - *cP[i] ) < _tol )
1452 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1454 for ( int iDir = 0; iDir < 3; ++iDir )
1456 if ( _coords[iDir][0] - sP[iDir] > _tol )
1458 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1459 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1461 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
1463 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1464 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1467 _tol = _minCellSize / 1000.;
1469 _origin = ( _coords[0][0] * _axes[0] +
1470 _coords[1][0] * _axes[1] +
1471 _coords[2][0] * _axes[2] );
1474 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1476 LineIndexer li = GetLineIndexer( iDir );
1477 _lines[iDir].resize( li.NbLines() );
1478 double len = _coords[ iDir ].back() - _coords[iDir].front();
1479 for ( ; li.More(); ++li )
1481 GridLine& gl = _lines[iDir][ li.LineIndex() ];
1482 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1483 _coords[1][li.J()] * _axes[1] +
1484 _coords[2][li.K()] * _axes[2] );
1485 gl._line.SetDirection( _axes[ iDir ]);
1490 //================================================================================
1492 * Return local ID of shape
1494 TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1496 return _helper->GetMeshDS()->ShapeToIndex( s );
1498 //================================================================================
1500 * Return a shape by its local ID
1502 const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1504 return _helper->GetMeshDS()->IndexToShape( id );
1506 //================================================================================
1508 * Initialize _geometry
1510 void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1512 SMESH_Mesh* mesh = _helper->GetMesh();
1514 _geometry._mainShape = theShapeToMesh;
1515 _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1516 _geometry._soleSolid.SetID( 0 );
1517 _geometry._soleSolid.SetHasInternalFaces( false );
1519 InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1520 InitClassifier( theShapeToMesh, TopAbs_EDGE , _geometry._edgeClassifier );
1522 TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1524 bool isSeveralSolids = false;
1525 if ( _toConsiderInternalFaces ) // check nb SOLIDs
1528 isSeveralSolids = solidExp.More();
1529 _toConsiderInternalFaces = isSeveralSolids;
1532 if ( !isSeveralSolids ) // look for an internal FACE
1534 TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1535 for ( ; fExp.More() && !_toConsiderInternalFaces; fExp.Next() )
1536 _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1538 _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1539 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1541 else // fill Geometry::_solidByID
1543 for ( ; solidExp.More(); solidExp.Next() )
1545 OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1546 solid.Init( solidExp.Current(), TopAbs_FACE, mesh->GetMeshDS() );
1547 solid.Init( solidExp.Current(), TopAbs_EDGE, mesh->GetMeshDS() );
1548 solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1554 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1557 if ( !_toCreateFaces )
1559 int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1560 int nbSolidsLocal = _helper->Count( theShapeToMesh, TopAbs_SOLID, false );
1561 _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1564 TopTools_IndexedMapOfShape faces;
1565 TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1567 // find boundary FACEs on boundary of mesh->ShapeToMesh()
1568 if ( _toCreateFaces )
1569 for ( int i = 1; i <= faces.Size(); ++i )
1570 if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1571 _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1573 _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1576 if ( isSeveralSolids )
1577 for ( int i = 1; i <= faces.Size(); ++i )
1579 SetSolidFather( faces(i), theShapeToMesh );
1580 for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1582 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1583 SetSolidFather( edge, theShapeToMesh );
1584 SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1585 SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1589 // fill in _geometry._shape2NbNodes == find already meshed sub-shapes
1590 _geometry._shape2NbNodes.Clear();
1591 if ( mesh->NbNodes() > 0 )
1593 for ( TopAbs_ShapeEnum type : { TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX })
1594 for ( TopExp_Explorer exp( theShapeToMesh, type ); exp.More(); exp.Next() )
1596 if ( _geometry._shape2NbNodes.IsBound( exp.Current() ))
1598 if ( SMESHDS_SubMesh* sm = mesh->GetMeshDS()->MeshElements( exp.Current() ))
1599 if ( sm->NbNodes() > 0 )
1600 _geometry._shape2NbNodes.Bind( exp.Current(), sm->NbNodes() );
1604 // fill in Solid::_concaveVertex
1605 vector< TGeomID > soleSolidID( 1, _geometry._soleSolid.ID() );
1606 for ( int i = 1; i <= faces.Size(); ++i )
1608 const TopoDS_Face& F = TopoDS::Face( faces( i ));
1610 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *mesh, 0, error,
1611 nullptr, nullptr, false );
1612 for ( StdMeshers_FaceSidePtr& wire : wires )
1614 const int nbEdges = wire->NbEdges();
1615 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wire->Edge(0)))
1617 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1619 if ( SMESH_Algo::isDegenerated( wire->Edge( iE1 ))) continue;
1620 int iE2 = ( iE1 + 1 ) % nbEdges;
1621 while ( SMESH_Algo::isDegenerated( wire->Edge( iE2 )))
1622 iE2 = ( iE2 + 1 ) % nbEdges;
1623 TopoDS_Vertex V = wire->FirstVertex( iE2 );
1624 double angle = _helper->GetAngle( wire->Edge( iE1 ),
1625 wire->Edge( iE2 ), F, V );
1626 if ( angle < -5. * M_PI / 180. )
1628 TGeomID faceID = ShapeID( F );
1629 const vector< TGeomID > & solids =
1630 _geometry.IsOneSolid() ? soleSolidID : GetSolidIDs( faceID );
1631 for ( const TGeomID & solidID : solids )
1633 Solid* solid = GetSolid( solidID );
1634 TGeomID V1 = ShapeID( wire->FirstVertex( iE1 ));
1635 TGeomID V2 = ShapeID( wire->LastVertex ( iE2 ));
1636 solid->SetConcave( ShapeID( V ), faceID,
1637 wire->EdgeID( iE1 ), wire->EdgeID( iE2 ), V1, V2 );
1646 //================================================================================
1648 * Store ID of SOLID as father of its child shape ID
1650 void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1652 if ( _geometry._solidIDsByShapeID.empty() )
1653 _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1655 vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1656 if ( !solidIDs.empty() )
1658 solidIDs.reserve(2);
1659 PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1660 *_helper->GetMesh(),
1663 while ( const TopoDS_Shape* solid = solidIt->next() )
1664 solidIDs.push_back( ShapeID( *solid ));
1666 //================================================================================
1668 * Return IDs of solids given sub-shape belongs to
1670 const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1672 return _geometry._solidIDsByShapeID[ subShapeID ];
1674 //================================================================================
1676 * Check if a sub-shape belongs to several SOLIDs
1678 bool Grid::IsShared( TGeomID shapeID ) const
1680 return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1682 //================================================================================
1684 * Check if any of FACEs belongs to several SOLIDs
1686 bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1688 for ( size_t i = 0; i < faceIDs.size(); ++i )
1689 if ( IsShared( faceIDs[ i ]))
1693 //================================================================================
1695 * Return Solid by ID
1697 Solid* Grid::GetSolid( TGeomID solidID )
1699 if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1700 return & _geometry._soleSolid;
1702 return & _geometry._solidByID[ solidID ];
1704 //================================================================================
1706 * Return OneOfSolids by ID
1708 Solid* Grid::GetOneOfSolids( TGeomID solidID )
1710 map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1711 if ( is2s != _geometry._solidByID.end() )
1712 return & is2s->second;
1714 return & _geometry._soleSolid;
1716 //================================================================================
1718 * Check if transition on given FACE is correct for a given SOLID
1720 bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1722 if ( _geometry.IsOneSolid() )
1725 const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1726 return solidIDs[0] == solid->ID();
1729 //================================================================================
1731 * Assign to geometry a node at FACE intersection
1732 * Return a found supporting VERTEX
1734 void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
1735 TopoDS_Vertex* vertex, bool unset )
1738 SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1739 if ( ip._faceIDs.size() == 1 )
1741 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1743 else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1745 if ( unset ) mesh->UnSetNodeOnShape( n );
1746 mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1748 *vertex = TopoDS::Vertex( s );
1750 else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1752 if ( unset ) mesh->UnSetNodeOnShape( n );
1753 mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1755 else if ( ip._faceIDs.size() > 0 )
1757 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1759 else if ( !unset && _geometry.IsOneSolid() )
1761 mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1764 //================================================================================
1766 * Fill in B_IntersectPoint::_faceIDs with all FACEs sharing a VERTEX
1768 void Grid::UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex )
1770 if ( vertex.IsNull() )
1772 std::vector< int > faceID(1);
1773 PShapeIteratorPtr fIt = _helper->GetAncestors( vertex, *_helper->GetMesh(),
1774 TopAbs_FACE, & _geometry._mainShape );
1775 while ( const TopoDS_Shape* face = fIt->next() )
1777 faceID[ 0 ] = ShapeID( *face );
1781 //================================================================================
1783 * Initialize a classifier
1785 void Grid::InitClassifier( const TopoDS_Shape& mainShape,
1786 TopAbs_ShapeEnum shapeType,
1787 Controls::ElementsOnShape& classifier )
1789 TopTools_IndexedMapOfShape shapes;
1790 TopExp::MapShapes( mainShape, shapeType, shapes );
1792 TopoDS_Compound compound; BRep_Builder builder;
1793 builder.MakeCompound( compound );
1794 for ( int i = 1; i <= shapes.Size(); ++i )
1795 builder.Add( compound, shapes(i) );
1797 classifier.SetMesh( _helper->GetMeshDS() );
1798 //classifier.SetTolerance( _tol ); // _tol is not initialised
1799 classifier.SetShape( compound, SMDSAbs_Node );
1802 //================================================================================
1804 * Return EDGEs with FACEs to implement into the mesh
1806 void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1807 const TopoDS_Shape& shape,
1808 const vector< TopoDS_Shape >& faces )
1810 // check if there are strange EDGEs
1811 TopTools_IndexedMapOfShape faceMap;
1812 TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1813 int nbFacesGlobal = faceMap.Size();
1814 faceMap.Clear( false );
1815 TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1816 int nbFacesLocal = faceMap.Size();
1817 bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1818 if ( !_toAddEdges && !hasStrangeEdges )
1819 return; // no FACEs in contact with those meshed by other algo
1821 for ( size_t i = 0; i < faces.size(); ++i )
1823 _helper->SetSubShape( faces[i] );
1824 for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1826 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1827 if ( hasStrangeEdges )
1829 bool hasStrangeFace = false;
1830 PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1831 while ( const TopoDS_Shape* face = faceIt->next() )
1832 if (( hasStrangeFace = !faceMap.Contains( *face )))
1834 if ( !hasStrangeFace && !_toAddEdges )
1836 _geometry._strangeEdges.Add( ShapeID( edge ));
1837 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1838 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1840 if ( !SMESH_Algo::isDegenerated( edge ) &&
1841 !_helper->IsRealSeam( edge ))
1843 edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1850 //================================================================================
1852 * Computes coordinates of a point in the grid CS
1854 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1856 gp_XYZ p = P * _invB;
1857 p.Coord( UVW[0], UVW[1], UVW[2] );
1859 //================================================================================
1863 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1865 // state of each node of the grid relative to the geometry
1866 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1867 vector< TGeomID > shapeIDVec( nbGridNodes, theUndefID );
1868 _nodes.resize( nbGridNodes, 0 );
1869 _gridIntP.resize( nbGridNodes, NULL );
1871 SMESHDS_Mesh* mesh = helper.GetMeshDS();
1873 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1875 LineIndexer li = GetLineIndexer( iDir );
1877 // find out a shift of node index while walking along a GridLine in this direction
1878 li.SetIndexOnLine( 0 );
1879 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1880 li.SetIndexOnLine( 1 );
1881 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1883 const vector<double> & coords = _coords[ iDir ];
1884 for ( ; li.More(); ++li ) // loop on lines in iDir
1886 li.SetIndexOnLine( 0 );
1887 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1889 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1890 const gp_XYZ lineLoc = line._line.Location().XYZ();
1891 const gp_XYZ lineDir = line._line.Direction().XYZ();
1893 line.RemoveExcessIntPoints( _tol );
1894 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1895 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1897 // Create mesh nodes at intersections with geometry
1898 // and set OUT state of nodes between intersections
1900 TGeomID solidID = 0;
1901 const double* nodeCoord = & coords[0];
1902 const double* coord0 = nodeCoord;
1903 const double* coordEnd = coord0 + coords.size();
1904 double nodeParam = 0;
1905 for ( ; ip != intPnts.end(); ++ip )
1907 solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1909 // set OUT state or just skip IN nodes before ip
1910 if ( nodeParam < ip->_paramOnLine - _tol )
1912 while ( nodeParam < ip->_paramOnLine - _tol )
1914 TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1915 nodeShapeID = Min( solidID, nodeShapeID );
1916 if ( ++nodeCoord < coordEnd )
1917 nodeParam = *nodeCoord - *coord0;
1921 if ( nodeCoord == coordEnd ) break;
1923 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1924 if ( nodeParam > ip->_paramOnLine + _tol )
1926 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1927 ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1928 ip->_indexOnLine = nodeCoord-coord0-1;
1930 SetOnShape( ip->_node, *ip, & v );
1931 UpdateFacesOfVertex( *ip, v );
1933 // create a mesh node at ip coincident with a grid node
1936 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1937 if ( !_nodes[ nodeIndex ] )
1939 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1940 _nodes [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1941 //_gridIntP[ nodeIndex ] = & * ip;
1942 //SetOnShape( _nodes[ nodeIndex ], *ip );
1944 if ( _gridIntP[ nodeIndex ] )
1945 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1947 _gridIntP[ nodeIndex ] = & * ip;
1948 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1949 ip->_indexOnLine = nodeCoord-coord0;
1950 if ( ++nodeCoord < coordEnd )
1951 nodeParam = *nodeCoord - *coord0;
1954 // set OUT state to nodes after the last ip
1955 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1956 shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1960 // Create mesh nodes at !OUT nodes of the grid
1962 for ( size_t z = 0; z < _coords[2].size(); ++z )
1963 for ( size_t y = 0; y < _coords[1].size(); ++y )
1964 for ( size_t x = 0; x < _coords[0].size(); ++x )
1966 size_t nodeIndex = NodeIndex( x, y, z );
1967 if ( !_nodes[ nodeIndex ] &&
1968 0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < theUndefID )
1970 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1971 _coords[1][y] * _axes[1] +
1972 _coords[2][z] * _axes[2] );
1973 _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1974 mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1976 else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1977 !_nodes[ nodeIndex]->GetShapeID()*/ )
1980 SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ], & v );
1981 UpdateFacesOfVertex( *_gridIntP[ nodeIndex ], v );
1986 // check validity of transitions
1987 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1988 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1990 LineIndexer li = GetLineIndexer( iDir );
1991 for ( ; li.More(); ++li )
1993 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1994 if ( intPnts.empty() ) continue;
1995 if ( intPnts.size() == 1 )
1997 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1998 intPnts.begin()->_transition != Trans_APEX )
1999 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2000 SMESH_Comment("Wrong SOLE transition of GridLine (")
2001 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2002 << ") along " << li._nameConst
2003 << ": " << trName[ intPnts.begin()->_transition] );
2007 if ( intPnts.begin()->_transition == Trans_OUT )
2008 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2009 SMESH_Comment("Wrong START transition of GridLine (")
2010 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2011 << ") along " << li._nameConst
2012 << ": " << trName[ intPnts.begin()->_transition ]);
2013 if ( intPnts.rbegin()->_transition == Trans_IN )
2014 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2015 SMESH_Comment("Wrong END transition of GridLine (")
2016 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2017 << ") along " << li._nameConst
2018 << ": " << trName[ intPnts.rbegin()->_transition ]);
2027 //=============================================================================
2029 * Intersects TopoDS_Face with all GridLine's
2031 void FaceGridIntersector::Intersect()
2033 FaceLineIntersector intersector;
2034 intersector._surfaceInt = GetCurveFaceIntersector();
2035 intersector._tol = _grid->_tol;
2036 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
2037 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
2039 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
2040 PIntFun interFunction;
2042 bool isDirect = true;
2043 BRepAdaptor_Surface surf( _face );
2044 switch ( surf.GetType() ) {
2046 intersector._plane = surf.Plane();
2047 interFunction = &FaceLineIntersector::IntersectWithPlane;
2048 isDirect = intersector._plane.Direct();
2050 case GeomAbs_Cylinder:
2051 intersector._cylinder = surf.Cylinder();
2052 interFunction = &FaceLineIntersector::IntersectWithCylinder;
2053 isDirect = intersector._cylinder.Direct();
2056 intersector._cone = surf.Cone();
2057 interFunction = &FaceLineIntersector::IntersectWithCone;
2058 //isDirect = intersector._cone.Direct();
2060 case GeomAbs_Sphere:
2061 intersector._sphere = surf.Sphere();
2062 interFunction = &FaceLineIntersector::IntersectWithSphere;
2063 isDirect = intersector._sphere.Direct();
2066 intersector._torus = surf.Torus();
2067 interFunction = &FaceLineIntersector::IntersectWithTorus;
2068 //isDirect = intersector._torus.Direct();
2071 interFunction = &FaceLineIntersector::IntersectWithSurface;
2074 std::swap( intersector._transOut, intersector._transIn );
2076 _intersections.clear();
2077 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2079 if ( surf.GetType() == GeomAbs_Plane )
2081 // check if all lines in this direction are parallel to a plane
2082 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
2083 Precision::Angular()))
2085 // find out a transition, that is the same for all lines of a direction
2086 gp_Dir plnNorm = intersector._plane.Axis().Direction();
2087 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
2088 intersector._transition =
2089 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
2091 if ( surf.GetType() == GeomAbs_Cylinder )
2093 // check if all lines in this direction are parallel to a cylinder
2094 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
2095 Precision::Angular()))
2099 // intersect the grid lines with the face
2100 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
2102 GridLine& gridLine = _grid->_lines[iDir][iL];
2103 if ( _bndBox.IsOut( gridLine._line )) continue;
2105 intersector._intPoints.clear();
2106 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
2107 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
2108 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
2112 if ( _face.Orientation() == TopAbs_INTERNAL )
2114 for ( size_t i = 0; i < _intersections.size(); ++i )
2115 if ( _intersections[i].second._transition == Trans_IN ||
2116 _intersections[i].second._transition == Trans_OUT )
2118 _intersections[i].second._transition = Trans_INTERNAL;
2123 //================================================================================
2125 * Return true if (_u,_v) is on the face
2127 bool FaceLineIntersector::UVIsOnFace() const
2129 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
2130 return ( state == TopAbs_IN || state == TopAbs_ON );
2132 //================================================================================
2134 * Store an intersection if it is IN or ON the face
2136 void FaceLineIntersector::addIntPoint(const bool toClassify)
2138 if ( !toClassify || UVIsOnFace() )
2141 p._paramOnLine = _w;
2144 p._transition = _transition;
2145 _intPoints.push_back( p );
2148 //================================================================================
2150 * Intersect a line with a plane
2152 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
2154 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
2155 _w = linPlane.ParamOnConic(1);
2156 if ( isParamOnLineOK( gridLine._length ))
2158 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
2162 //================================================================================
2164 * Intersect a line with a cylinder
2166 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
2168 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
2169 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
2171 _w = linCylinder.ParamOnConic(1);
2172 if ( linCylinder.NbPoints() == 1 )
2173 _transition = Trans_TANGENT;
2175 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
2176 if ( isParamOnLineOK( gridLine._length ))
2178 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
2181 if ( linCylinder.NbPoints() > 1 )
2183 _w = linCylinder.ParamOnConic(2);
2184 if ( isParamOnLineOK( gridLine._length ))
2186 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
2187 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2193 //================================================================================
2195 * Intersect a line with a cone
2197 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
2199 IntAna_IntConicQuad linCone(gridLine._line,_cone);
2200 if ( !linCone.IsDone() ) return;
2202 gp_Vec du, dv, norm;
2203 for ( int i = 1; i <= linCone.NbPoints(); ++i )
2205 _w = linCone.ParamOnConic( i );
2206 if ( !isParamOnLineOK( gridLine._length )) continue;
2207 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
2210 ElSLib::D1( _u, _v, _cone, P, du, dv );
2212 double normSize2 = norm.SquareMagnitude();
2213 if ( normSize2 > Precision::Angular() * Precision::Angular() )
2215 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2216 cos /= sqrt( normSize2 );
2217 if ( cos < -Precision::Angular() )
2218 _transition = _transIn;
2219 else if ( cos > Precision::Angular() )
2220 _transition = _transOut;
2222 _transition = Trans_TANGENT;
2226 _transition = Trans_APEX;
2228 addIntPoint( /*toClassify=*/false);
2232 //================================================================================
2234 * Intersect a line with a sphere
2236 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
2238 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
2239 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
2241 _w = linSphere.ParamOnConic(1);
2242 if ( linSphere.NbPoints() == 1 )
2243 _transition = Trans_TANGENT;
2245 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
2246 if ( isParamOnLineOK( gridLine._length ))
2248 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2251 if ( linSphere.NbPoints() > 1 )
2253 _w = linSphere.ParamOnConic(2);
2254 if ( isParamOnLineOK( gridLine._length ))
2256 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2257 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2263 //================================================================================
2265 * Intersect a line with a torus
2267 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
2269 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2270 if ( !linTorus.IsDone()) return;
2272 gp_Vec du, dv, norm;
2273 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2275 _w = linTorus.ParamOnLine( i );
2276 if ( !isParamOnLineOK( gridLine._length )) continue;
2277 linTorus.ParamOnTorus( i, _u,_v );
2280 ElSLib::D1( _u, _v, _torus, P, du, dv );
2282 double normSize = norm.Magnitude();
2283 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2285 if ( cos < -Precision::Angular() )
2286 _transition = _transIn;
2287 else if ( cos > Precision::Angular() )
2288 _transition = _transOut;
2290 _transition = Trans_TANGENT;
2291 addIntPoint( /*toClassify=*/false);
2295 //================================================================================
2297 * Intersect a line with a non-analytical surface
2299 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2301 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2302 if ( !_surfaceInt->IsDone() ) return;
2303 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2305 _transition = Transition( _surfaceInt->Transition( i ) );
2306 _w = _surfaceInt->WParameter( i );
2307 addIntPoint(/*toClassify=*/false);
2310 //================================================================================
2312 * check if its face can be safely intersected in a thread
2314 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2319 TopLoc_Location loc;
2320 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2321 Handle(Geom_RectangularTrimmedSurface) ts =
2322 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2323 while( !ts.IsNull() ) {
2324 surf = ts->BasisSurface();
2325 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2327 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2328 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2329 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2333 TopExp_Explorer exp( _face, TopAbs_EDGE );
2334 for ( ; exp.More(); exp.Next() )
2336 bool edgeIsSafe = true;
2337 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2340 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2343 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2344 while( !tc.IsNull() ) {
2345 c = tc->BasisCurve();
2346 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2348 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2349 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2356 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2359 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2360 while( !tc.IsNull() ) {
2361 c2 = tc->BasisCurve();
2362 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2364 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2365 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2369 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2374 //================================================================================
2376 * \brief Creates topology of the hexahedron
2378 Hexahedron::Hexahedron(Grid* grid)
2379 : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2381 _polygons.reserve(100); // to avoid reallocation;
2383 //set nodes shift within grid->_nodes from the node 000
2384 size_t dx = _grid->NodeIndexDX();
2385 size_t dy = _grid->NodeIndexDY();
2386 size_t dz = _grid->NodeIndexDZ();
2388 size_t i100 = i000 + dx;
2389 size_t i010 = i000 + dy;
2390 size_t i110 = i010 + dx;
2391 size_t i001 = i000 + dz;
2392 size_t i101 = i100 + dz;
2393 size_t i011 = i010 + dz;
2394 size_t i111 = i110 + dz;
2395 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2396 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2397 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2398 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2399 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2400 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2401 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2402 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2404 vector< int > idVec;
2405 // set nodes to links
2406 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2408 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2409 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2410 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2411 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2414 // set links to faces
2415 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2416 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2418 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2419 quad._name = (SMESH_Block::TShapeID) faceID;
2421 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2422 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2423 faceID == SMESH_Block::ID_Fx1z ||
2424 faceID == SMESH_Block::ID_F0yz );
2425 quad._links.resize(4);
2426 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
2427 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2428 for ( int i = 0; i < 4; ++i )
2430 bool revLink = revFace;
2431 if ( i > 1 ) // reverse links u1 and v0
2433 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2434 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2439 //================================================================================
2441 * \brief Copy constructor
2443 Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2444 :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2446 _polygons.reserve(100); // to avoid reallocation;
2449 for ( int i = 0; i < 12; ++i )
2451 const _Link& srcLink = other._hexLinks[ i ];
2452 _Link& tgtLink = this->_hexLinks[ i ];
2453 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2454 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2457 for ( int i = 0; i < 6; ++i )
2459 const _Face& srcQuad = other._hexQuads[ i ];
2460 _Face& tgtQuad = this->_hexQuads[ i ];
2461 tgtQuad._name = srcQuad._name;
2462 tgtQuad._links.resize(4);
2463 for ( int j = 0; j < 4; ++j )
2465 const _OrientedLink& srcLink = srcQuad._links[ j ];
2466 _OrientedLink& tgtLink = tgtQuad._links[ j ];
2467 tgtLink._reverse = srcLink._reverse;
2468 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
2472 if (SALOME::VerbosityActivated())
2476 //================================================================================
2478 * \brief Return IDs of SOLIDs interfering with this Hexahedron
2480 size_t Hexahedron::getSolids( TGeomID ids[] )
2482 if ( _grid->_geometry.IsOneSolid() )
2484 ids[0] = _grid->GetSolid()->ID();
2487 // count intersection points belonging to each SOLID
2489 id2NbPoints.reserve( 3 );
2491 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2492 for ( int iN = 0; iN < 8; ++iN )
2494 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2495 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2497 if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2499 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2501 const vector< TGeomID > & solidIDs =
2502 _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2503 for ( size_t i = 0; i < solidIDs.size(); ++i )
2504 insertAndIncrement( solidIDs[i], id2NbPoints );
2507 else if ( _hexNodes[iN]._node ) // node inside a SOLID
2509 insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2513 for ( int iL = 0; iL < 12; ++iL )
2515 const _Link& link = _hexLinks[ iL ];
2516 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2518 for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2520 const vector< TGeomID > & solidIDs =
2521 _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2522 for ( size_t i = 0; i < solidIDs.size(); ++i )
2523 insertAndIncrement( solidIDs[i], id2NbPoints );
2528 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2530 const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2531 for ( size_t i = 0; i < solidIDs.size(); ++i )
2532 insertAndIncrement( solidIDs[i], id2NbPoints );
2535 size_t nbSolids = 0;
2536 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2537 if ( id2nb->second >= 3 )
2538 ids[ nbSolids++ ] = id2nb->first;
2543 //================================================================================
2545 * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2547 bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2550 id2NbPoints.reserve( 3 );
2552 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2553 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2555 if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2556 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2558 for ( size_t iN = 0; iN < 8; ++iN )
2559 if ( _hexNodes[iN]._intPoint )
2560 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2562 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2563 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2566 maxFlag = IS_NOT_INTERNAL;
2567 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2569 TGeomID intFace = id2nb->first;
2570 IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2571 if ( intFlag > maxFlag )
2574 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2575 if ( _intNodes[iN].IsOnFace( intFace ))
2576 _intNodes[iN].SetInternal( intFlag );
2578 for ( size_t iN = 0; iN < 8; ++iN )
2579 if ( _hexNodes[iN].IsOnFace( intFace ))
2580 _hexNodes[iN].SetInternal( intFlag );
2586 //================================================================================
2588 * \brief Return any FACE interfering with this Hexahedron
2590 TGeomID Hexahedron::getAnyFace() const
2593 id2NbPoints.reserve( 3 );
2595 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2596 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2597 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2599 for ( size_t iN = 0; iN < 8; ++iN )
2600 if ( _hexNodes[iN]._intPoint )
2601 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2602 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2604 for ( unsigned int minNb = 3; minNb > 0; --minNb )
2605 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2606 if ( id2nb->second >= minNb )
2607 return id2nb->first;
2612 //================================================================================
2614 * \brief Initializes IJK by Hexahedron index
2616 void Hexahedron::setIJK( size_t iCell )
2618 size_t iNbCell = _grid->_coords[0].size() - 1;
2619 size_t jNbCell = _grid->_coords[1].size() - 1;
2620 _i = iCell % iNbCell;
2621 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2622 _k = iCell / iNbCell / jNbCell;
2625 //================================================================================
2627 * \brief Initializes its data by given grid cell (countered from zero)
2629 void Hexahedron::init( size_t iCell )
2635 //================================================================================
2637 * \brief Initializes its data by given grid cell nodes and intersections
2639 void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2641 _i = i; _j = j; _k = k;
2643 bool isCompute = solid;
2645 solid = _grid->GetSolid();
2647 // set nodes of grid to nodes of the hexahedron and
2648 // count nodes at hexahedron corners located IN and ON geometry
2649 _nbCornerNodes = _nbBndNodes = 0;
2650 _origNodeInd = _grid->NodeIndex( i,j,k );
2651 for ( int iN = 0; iN < 8; ++iN )
2653 _hexNodes[iN]._isInternalFlags = 0;
2655 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2656 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2658 if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2659 _hexNodes[iN]._node = 0;
2660 if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2661 _hexNodes[iN]._intPoint = 0;
2663 _nbCornerNodes += bool( _hexNodes[iN]._node );
2664 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
2666 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2667 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2668 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2676 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
2677 _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2679 _intNodes.reserve( 3 * ( _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() ));
2681 // this method can be called in parallel, so use own helper
2682 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2684 // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2685 // ---------------------------------------------------------------
2687 for ( int iLink = 0; iLink < 12; ++iLink )
2689 _Link& link = _hexLinks[ iLink ];
2690 link._fIntNodes.clear();
2691 link._fIntNodes.reserve( link._fIntPoints.size() );
2692 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2693 if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2695 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2696 link._fIntNodes.push_back( & _intNodes.back() );
2699 link._splits.clear();
2700 split._nodes[ 0 ] = link._nodes[0];
2701 bool isOut = ( ! link._nodes[0]->Node() );
2702 bool checkTransition;
2703 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2705 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2706 if ( !isGridNode ) // intersection non-coincident with a grid node
2708 if ( split._nodes[ 0 ]->Node() && !isOut )
2710 split._nodes[ 1 ] = link._fIntNodes[i];
2711 link._splits.push_back( split );
2713 split._nodes[ 0 ] = link._fIntNodes[i];
2714 checkTransition = true;
2716 else // FACE intersection coincident with a grid node (at link ends)
2718 checkTransition = ( i == 0 && link._nodes[0]->Node() );
2720 if ( checkTransition )
2722 const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2723 if ( _grid->IsInternal( faceIDs.back() ))
2725 else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2726 isOut = isOutPoint( link, i, helper, solid );
2729 bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2730 switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2731 case Trans_OUT: isOut = okTransi; break;
2732 case Trans_IN : isOut = !okTransi; break;
2734 isOut = isOutPoint( link, i, helper, solid );
2739 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2741 split._nodes[ 1 ] = link._nodes[1];
2742 link._splits.push_back( split );
2746 // Create _Node's at intersections with EDGEs.
2747 // --------------------------------------------
2748 // 1) add this->_eIntPoints to _Face::_eIntNodes
2749 // 2) fill _intNodes and _vIntNodes
2751 const double tol2 = _grid->_tol * _grid->_tol * 4;
2752 int facets[3], nbFacets, subEntity;
2754 for ( int iF = 0; iF < 6; ++iF )
2755 _hexQuads[ iF ]._eIntNodes.clear();
2757 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2759 if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2761 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2762 _Node* equalNode = 0;
2763 switch( nbFacets ) {
2764 case 1: // in a _Face
2766 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2767 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2769 equalNode->Add( _eIntPoints[ iP ] );
2772 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2773 quad._eIntNodes.push_back( & _intNodes.back() );
2777 case 2: // on a _Link
2779 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2780 if ( link._splits.size() > 0 )
2782 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2784 equalNode->Add( _eIntPoints[ iP ] );
2785 else if ( link._splits.size() == 1 &&
2786 link._splits[0]._nodes[0] &&
2787 link._splits[0]._nodes[1] )
2788 link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2793 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2794 bool newNodeUsed = false;
2795 for ( int iF = 0; iF < 2; ++iF )
2797 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2798 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2800 equalNode->Add( _eIntPoints[ iP ] );
2803 quad._eIntNodes.push_back( & _intNodes.back() );
2808 _intNodes.pop_back();
2812 case 3: // at a corner
2814 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2817 if ( node._intPoint )
2818 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2822 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2823 for ( int iF = 0; iF < 3; ++iF )
2825 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2826 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2828 equalNode->Add( _eIntPoints[ iP ] );
2831 quad._eIntNodes.push_back( & _intNodes.back() );
2837 } // switch( nbFacets )
2839 if ( nbFacets == 0 ||
2840 _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2842 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2844 equalNode->Add( _eIntPoints[ iP ] );
2846 else if ( nbFacets == 0 ) {
2847 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2848 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2849 _vIntNodes.push_back( & _intNodes.back() );
2852 } // loop on _eIntPoints
2855 else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2856 ( !_grid->_geometry.IsOneSolid() ))
2859 // create sub-links (_splits) of whole links
2860 for ( int iLink = 0; iLink < 12; ++iLink )
2862 _Link& link = _hexLinks[ iLink ];
2863 link._splits.clear();
2864 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2866 split._nodes[ 0 ] = link._nodes[0];
2867 split._nodes[ 1 ] = link._nodes[1];
2868 link._splits.push_back( split );
2874 } // init( _i, _j, _k )
2876 //================================================================================
2878 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2880 void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2884 solid = _grid->GetSolid();
2885 if ( !_grid->_geometry.IsOneSolid() )
2887 TGeomID solidIDs[20] = { 0 };
2888 size_t nbSolids = getSolids( solidIDs );
2891 for ( size_t i = 0; i < nbSolids; ++i )
2893 solid = _grid->GetSolid( solidIDs[i] );
2894 computeElements( solid, i );
2895 if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2896 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2900 solid = _grid->GetSolid( solidIDs[0] );
2904 init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2906 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2907 if ( _nbCornerNodes + nbIntersections < 4 )
2910 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2911 return; // cell is in a hole
2913 IsInternalFlag intFlag = IS_NOT_INTERNAL;
2914 if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2916 for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2918 if ( compute( solid, intFlag ))
2919 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2924 if ( solidIndex >= 0 )
2925 intFlag = IS_CUT_BY_INTERNAL_FACE;
2927 compute( solid, intFlag );
2931 //================================================================================
2933 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2935 bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2938 _polygons.reserve( 20 );
2940 for ( int iN = 0; iN < 8; ++iN )
2941 _hexNodes[iN]._usedInFace = 0;
2943 if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2944 preventVolumesOverlapping();
2946 std::set< TGeomID > concaveFaces; // to avoid connecting nodes laying on them
2948 if ( solid->HasConcaveVertex() )
2950 for ( const E_IntersectPoint* ip : _eIntPoints )
2952 if ( const ConcaveFace* cf = solid->GetConcave( ip->_shapeID ))
2953 if ( this->hasEdgesAround( cf ))
2954 concaveFaces.insert( cf->_concaveFace );
2956 if ( concaveFaces.empty() || concaveFaces.size() * 3 < _eIntPoints.size() )
2957 for ( const _Node& hexNode: _hexNodes )
2959 if ( hexNode._node && hexNode._intPoint && hexNode._intPoint->_faceIDs.size() >= 3 )
2960 if ( const ConcaveFace* cf = solid->GetConcave( hexNode._node->GetShapeID() ))
2961 if ( this->hasEdgesAround( cf ))
2962 concaveFaces.insert( cf->_concaveFace );
2966 // Create polygons from quadrangles
2967 // --------------------------------
2969 vector< _OrientedLink > splits;
2970 vector<_Node*> chainNodes;
2971 _Face* coplanarPolyg;
2973 const bool hasEdgeIntersections = !_eIntPoints.empty();
2974 const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
2976 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2978 _Face& quad = _hexQuads[ iF ] ;
2980 _polygons.resize( _polygons.size() + 1 );
2981 _Face* polygon = &_polygons.back();
2982 polygon->_polyLinks.reserve( 20 );
2983 polygon->_name = quad._name;
2986 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
2987 for ( size_t iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
2988 splits.push_back( quad._links[ iE ].ResultLink( iS ));
2990 if ( splits.size() == 4 &&
2991 isQuadOnFace( iF )) // check if a quad on FACE is not split
2993 polygon->_links.swap( splits );
2994 continue; // goto the next quad
2997 // add splits of links to a polygon and add _polyLinks to make
2998 // polygon's boundary closed
3000 int nbSplits = splits.size();
3001 if (( nbSplits == 1 ) &&
3002 ( quad._eIntNodes.empty() ||
3003 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
3004 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
3007 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3008 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
3009 quad._eIntNodes[ iP ]->_usedInFace = 0;
3011 size_t nbUsedEdgeNodes = 0;
3012 _Face* prevPolyg = 0; // polygon previously created from this quad
3014 while ( nbSplits > 0 )
3017 while ( !splits[ iS ] )
3020 if ( !polygon->_links.empty() )
3022 _polygons.resize( _polygons.size() + 1 );
3023 polygon = &_polygons.back();
3024 polygon->_polyLinks.reserve( 20 );
3025 polygon->_name = quad._name;
3027 polygon->_links.push_back( splits[ iS ] );
3028 splits[ iS++ ]._link = 0;
3031 _Node* nFirst = polygon->_links.back().FirstNode();
3032 _Node *n1,*n2 = polygon->_links.back().LastNode();
3033 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
3035 _OrientedLink& split = splits[ iS ];
3036 if ( !split ) continue;
3038 n1 = split.FirstNode();
3041 (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
3042 ( n1->_isInternalFlags )))
3044 // n1 is at intersection with EDGE
3045 if ( findChainOnEdge( splits, polygon->_links.back(), split, concaveFaces,
3046 iS, quad, chainNodes ))
3048 for ( size_t i = 1; i < chainNodes.size(); ++i )
3049 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3050 if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
3052 prevPolyg = polygon;
3053 n2 = chainNodes.back();
3058 else if ( n1 != n2 )
3060 // try to connect to intersections with EDGEs
3061 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
3062 findChain( n2, n1, quad, chainNodes ))
3064 for ( size_t i = 1; i < chainNodes.size(); ++i )
3066 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
3067 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
3069 if ( chainNodes.back() != n1 )
3071 n2 = chainNodes.back();
3076 // try to connect to a split ending on the same FACE
3079 _OrientedLink foundSplit;
3080 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
3081 if (( foundSplit = splits[ i ]) &&
3082 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
3088 foundSplit._link = 0;
3092 if ( n2 != foundSplit.FirstNode() )
3094 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
3095 n2 = foundSplit.FirstNode();
3101 if ( n2->IsLinked( nFirst->_intPoint ))
3103 polygon->AddPolyLink( n2, n1, prevPolyg );
3106 } // if ( n1 != n2 )
3108 polygon->_links.push_back( split );
3111 n2 = polygon->_links.back().LastNode();
3115 if ( nFirst != n2 ) // close a polygon
3117 if ( !findChain( n2, nFirst, quad, chainNodes ))
3119 if ( !closePolygon( polygon, chainNodes ))
3120 if ( !isImplementEdges() )
3121 chainNodes.push_back( nFirst );
3123 for ( size_t i = 1; i < chainNodes.size(); ++i )
3125 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3126 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
3130 if ( polygon->_links.size() < 3 && nbSplits > 0 )
3132 polygon->_polyLinks.clear();
3133 polygon->_links.clear();
3135 } // while ( nbSplits > 0 )
3137 if ( polygon->_links.size() < 3 )
3139 _polygons.pop_back();
3141 } // loop on 6 hexahedron sides
3143 // Create polygons closing holes in a polyhedron
3144 // ----------------------------------------------
3146 // clear _usedInFace
3147 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
3148 _intNodes[ iN ]._usedInFace = 0;
3150 // add polygons to their links and mark used nodes
3151 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3153 _Face& polygon = _polygons[ iP ];
3154 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3156 polygon._links[ iL ].AddFace( &polygon );
3157 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
3161 vector< _OrientedLink* > freeLinks;
3162 freeLinks.reserve(20);
3163 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3165 _Face& polygon = _polygons[ iP ];
3166 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3167 if ( polygon._links[ iL ].NbFaces() < 2 )
3168 freeLinks.push_back( & polygon._links[ iL ]);
3170 int nbFreeLinks = freeLinks.size();
3171 if ( nbFreeLinks == 1 ) return false;
3173 // put not used intersection nodes to _vIntNodes
3174 int nbVertexNodes = 0; // nb not used vertex nodes
3176 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3177 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
3179 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
3180 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
3182 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
3183 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
3185 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
3188 _vIntNodes.push_back( &_intNodes[ iN ]);
3194 std::set<TGeomID> usedFaceIDs;
3195 std::vector< TGeomID > faces;
3196 TGeomID curFace = 0;
3197 const size_t nbQuadPolygons = _polygons.size();
3198 E_IntersectPoint ipTmp;
3199 std::map< TGeomID, std::vector< const B_IntersectPoint* > > tmpAddedFace; // face added to _intPoint
3201 // create polygons by making closed chains of free links
3202 size_t iPolygon = _polygons.size();
3203 while ( nbFreeLinks > 0 )
3205 if ( iPolygon == _polygons.size() )
3207 _polygons.resize( _polygons.size() + 1 );
3208 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
3209 _polygons[ iPolygon ]._links.reserve( 20 );
3211 _Face& polygon = _polygons[ iPolygon ];
3213 _OrientedLink* curLink = 0;
3215 if (( !hasEdgeIntersections ) ||
3216 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
3218 // get a remaining link to start from
3219 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3220 if (( curLink = freeLinks[ iL ] ))
3221 freeLinks[ iL ] = 0;
3222 polygon._links.push_back( *curLink );
3226 // find all links connected to curLink
3227 curNode = curLink->FirstNode();
3229 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3230 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
3232 curLink = freeLinks[ iL ];
3233 freeLinks[ iL ] = 0;
3235 polygon._links.push_back( *curLink );
3237 } while ( curLink );
3239 else // there are intersections with EDGEs
3241 // get a remaining link to start from, one lying on minimal nb of FACEs
3243 typedef pair< TGeomID, int > TFaceOfLink;
3244 TFaceOfLink faceOfLink( -1, -1 );
3245 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
3246 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
3247 if ( freeLinks[ iL ] )
3249 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
3250 if ( faces.size() == 1 )
3252 faceOfLink = TFaceOfLink( faces[0], iL );
3253 if ( !freeLinks[ iL ]->HasEdgeNodes() )
3255 facesOfLink[0] = faceOfLink;
3257 else if ( facesOfLink[0].first < 0 )
3259 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
3260 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
3263 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
3264 faceOfLink = facesOfLink[i];
3266 if ( faceOfLink.first < 0 ) // all faces used
3268 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
3269 if (( curLink = freeLinks[ iL ]))
3272 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
3273 faceOfLink.second = iL;
3275 usedFaceIDs.clear();
3277 curFace = faceOfLink.first;
3278 curLink = freeLinks[ faceOfLink.second ];
3279 freeLinks[ faceOfLink.second ] = 0;
3281 usedFaceIDs.insert( curFace );
3282 polygon._links.push_back( *curLink );
3285 // find all links lying on a curFace
3288 // go forward from curLink
3289 curNode = curLink->LastNode();
3291 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3292 if ( freeLinks[ iL ] &&
3293 freeLinks[ iL ]->FirstNode() == curNode &&
3294 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3296 curLink = freeLinks[ iL ];
3297 freeLinks[ iL ] = 0;
3298 polygon._links.push_back( *curLink );
3301 } while ( curLink );
3303 std::reverse( polygon._links.begin(), polygon._links.end() );
3305 curLink = & polygon._links.back();
3308 // go backward from curLink
3309 curNode = curLink->FirstNode();
3311 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3312 if ( freeLinks[ iL ] &&
3313 freeLinks[ iL ]->LastNode() == curNode &&
3314 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3316 curLink = freeLinks[ iL ];
3317 freeLinks[ iL ] = 0;
3318 polygon._links.push_back( *curLink );
3321 } while ( curLink );
3323 curNode = polygon._links.back().FirstNode();
3325 if ( polygon._links[0].LastNode() != curNode )
3327 if ( nbVertexNodes > 0 )
3329 // add links with _vIntNodes if not already used
3331 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3332 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3333 _vIntNodes[ iN ]->IsOnFace( curFace ))
3335 _vIntNodes[ iN ]->_usedInFace = &polygon;
3336 chainNodes.push_back( _vIntNodes[ iN ] );
3338 if ( chainNodes.size() > 1 &&
3339 curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3341 sortVertexNodes( chainNodes, curNode, curFace );
3343 for ( size_t i = 0; i < chainNodes.size(); ++i )
3345 polygon.AddPolyLink( chainNodes[ i ], curNode );
3346 curNode = chainNodes[ i ];
3347 freeLinks.push_back( &polygon._links.back() );
3350 nbVertexNodes -= chainNodes.size();
3352 // if ( polygon._links.size() > 1 )
3354 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3355 freeLinks.push_back( &polygon._links.back() );
3359 } // if there are intersections with EDGEs
3361 if ( polygon._links.size() < 2 ||
3362 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3365 break; // closed polygon not found -> invalid polyhedron
3368 if ( polygon._links.size() == 2 )
3370 if ( freeLinks.back() == &polygon._links.back() )
3372 freeLinks.pop_back();
3375 if ( polygon._links.front().NbFaces() > 0 )
3376 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3377 if ( polygon._links.back().NbFaces() > 0 )
3378 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3380 if ( iPolygon == _polygons.size()-1 )
3381 _polygons.pop_back();
3383 else // polygon._links.size() >= 2
3385 // add polygon to its links
3386 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3388 polygon._links[ iL ].AddFace( &polygon );
3389 polygon._links[ iL ].Reverse();
3391 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3393 // check that a polygon does not lie on a hexa side
3395 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3397 if ( polygon._links[ iL ].NbFaces() < 2 )
3398 continue; // it's a just added free link
3399 // look for a polygon made on a hexa side and sharing
3400 // two or more haxa links
3402 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3403 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3404 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3405 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
3406 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3407 coplanarPolyg < & _polygons[ nbQuadPolygons ])
3409 if ( iL2 == polygon._links.size() )
3412 if ( coplanarPolyg ) // coplanar polygon found
3414 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3415 nbFreeLinks -= polygon._polyLinks.size();
3417 // an E_IntersectPoint used to mark nodes of coplanarPolyg
3418 // as lying on curFace while they are not at intersection with geometry
3419 ipTmp._faceIDs.resize(1);
3420 ipTmp._faceIDs[0] = curFace;
3422 // fill freeLinks with links not shared by coplanarPolyg and polygon
3423 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3424 if ( polygon._links[ iL ]._link->_faces[1] &&
3425 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3427 _Face* p = polygon._links[ iL ]._link->_faces[0];
3428 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3429 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3431 freeLinks.push_back( & p->_links[ iL2 ] );
3433 freeLinks.back()->RemoveFace( &polygon );
3437 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3438 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3439 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3441 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3442 if ( p == coplanarPolyg )
3443 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3444 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3445 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3447 // set links of coplanarPolyg in place of used freeLinks
3448 // to re-create coplanarPolyg next
3450 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3451 if ( iL3 < freeLinks.size() )
3452 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3454 freeLinks.push_back( & p->_links[ iL2 ] );
3456 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3457 // mark nodes of coplanarPolyg as lying on curFace
3458 for ( int iN = 0; iN < 2; ++iN )
3460 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3462 if ( n->_intPoint ) added = n->_intPoint->Add( ipTmp._faceIDs );
3463 else n->_intPoint = &ipTmp;
3465 tmpAddedFace[ ipTmp._faceIDs[0] ].push_back( n->_intPoint );
3470 // set coplanarPolyg to be re-created next
3471 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3472 if ( coplanarPolyg == & _polygons[ iP ] )
3475 _polygons[ iPolygon ]._links.clear();
3476 _polygons[ iPolygon ]._polyLinks.clear();
3479 _polygons.pop_back();
3480 usedFaceIDs.erase( curFace );
3482 } // if ( coplanarPolyg )
3483 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3485 iPolygon = _polygons.size();
3487 } // end of case ( polygon._links.size() > 2 )
3488 } // while ( nbFreeLinks > 0 )
3490 for ( auto & face_ip : tmpAddedFace )
3492 curFace = face_ip.first;
3493 for ( const B_IntersectPoint* ip : face_ip.second )
3495 auto it = std::find( ip->_faceIDs.begin(), ip->_faceIDs.end(), curFace );
3496 if ( it != ip->_faceIDs.end() )
3497 ip->_faceIDs.erase( it );
3501 if ( _polygons.size() < 3 )
3504 // check volume size
3506 _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE, volSize );
3508 for ( size_t i = 0; i < 8; ++i )
3509 if ( _hexNodes[ i ]._intPoint == &ipTmp )
3510 _hexNodes[ i ]._intPoint = 0;
3513 return false; // too small volume
3516 // Try to find out names of no-name polygons (issue # 19887)
3517 if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3520 0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3521 0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3522 0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3523 for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3525 _Face& face = _polygons[ i ];
3528 for ( size_t iL = 0; iL < face._links.size(); ++iL )
3530 _Node* n = face._links[ iL ].FirstNode();
3531 gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3532 _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3535 gp_Pnt pMin = bb.CornerMin();
3536 if ( bb.IsXThin( _grid->_tol ))
3537 face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3538 else if ( bb.IsYThin( _grid->_tol ))
3539 face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3540 else if ( bb.IsZThin( _grid->_tol ))
3541 face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3545 _volumeDefs._nodes.clear();
3546 _volumeDefs._quantities.clear();
3547 _volumeDefs._names.clear();
3549 // create a classic cell if possible
3552 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3553 nbPolygons += (_polygons[ iF ]._links.size() > 2 );
3555 //const int nbNodes = _nbCornerNodes + nbIntersections;
3557 for ( size_t i = 0; i < 8; ++i )
3558 nbNodes += _hexNodes[ i ].IsUsedInFace();
3559 for ( size_t i = 0; i < _intNodes.size(); ++i )
3560 nbNodes += _intNodes[ i ].IsUsedInFace();
3562 bool isClassicElem = false;
3563 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3564 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3565 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3566 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3567 if ( !isClassicElem )
3569 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3571 const size_t nbLinks = _polygons[ iF ]._links.size();
3572 if ( nbLinks < 3 ) continue;
3573 _volumeDefs._quantities.push_back( nbLinks );
3574 _volumeDefs._names.push_back( _polygons[ iF ]._name );
3575 for ( size_t iL = 0; iL < nbLinks; ++iL )
3576 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3579 _volumeDefs._solidID = solid->ID();
3580 _volumeDefs._size = volSize;
3582 return !_volumeDefs._nodes.empty();
3584 //================================================================================
3586 * \brief Create elements in the mesh
3588 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
3589 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3591 SMESHDS_Mesh* mesh = helper.GetMeshDS();
3593 CellsAroundLink c( _grid, 0 );
3594 const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3595 vector< Hexahedron* > allHexa( nbGridCells, 0 );
3598 // set intersection nodes from GridLine's to links of allHexa
3599 int i,j,k, cellIndex, iLink;
3600 for ( int iDir = 0; iDir < 3; ++iDir )
3602 // loop on GridLine's parallel to iDir
3603 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3604 CellsAroundLink fourCells( _grid, iDir );
3605 for ( ; lineInd.More(); ++lineInd )
3607 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3608 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3609 for ( ; ip != line._intPoints.end(); ++ip )
3611 // if ( !ip->_node ) continue; // intersection at a grid node
3612 lineInd.SetIndexOnLine( ip->_indexOnLine );
3613 fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3614 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3616 if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3618 Hexahedron *& hex = allHexa[ cellIndex ];
3621 hex = new Hexahedron( *this, i, j, k, cellIndex );
3624 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3625 hex->_nbFaceIntNodes += bool( ip->_node );
3631 // implement geom edges into the mesh
3632 addEdges( helper, allHexa, edge2faceIDsMap );
3634 // add not split hexahedra to the mesh
3636 TGeomID solidIDs[20];
3637 vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3638 vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3639 for ( size_t i = 0; i < allHexa.size(); ++i )
3641 // initialize this by not cut allHexa[ i ]
3642 Hexahedron * & hex = allHexa[ i ];
3643 if ( hex ) // split hexahedron
3645 intHexa.push_back( hex );
3646 if ( hex->_nbFaceIntNodes > 0 ||
3647 hex->_eIntPoints.size() > 0 ||
3648 hex->getSolids( solidIDs ) > 1 )
3649 continue; // treat intersected hex later in parallel
3650 this->init( hex->_i, hex->_j, hex->_k );
3654 this->init( i ); // == init(i,j,k)
3656 if (( _nbCornerNodes == 8 ) &&
3657 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3659 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3660 SMDS_MeshElement* el =
3661 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3662 _hexNodes[3].Node(), _hexNodes[1].Node(),
3663 _hexNodes[4].Node(), _hexNodes[6].Node(),
3664 _hexNodes[7].Node(), _hexNodes[5].Node() );
3665 TGeomID solidID = 0;
3666 if ( _nbBndNodes < _nbCornerNodes )
3668 for ( int iN = 0; iN < 8 && !solidID; ++iN )
3669 if ( !_hexNodes[iN]._intPoint ) // no intersection
3670 solidID = _hexNodes[iN].Node()->GetShapeID();
3674 getSolids( solidIDs );
3675 solidID = solidIDs[0];
3677 mesh->SetMeshElementOnShape( el, solidID );
3681 if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3683 boundaryVolumes.push_back( el );
3684 el->setIsMarked( true );
3687 else if ( _nbCornerNodes > 3 && !hex )
3689 // all intersections of hex with geometry are at grid nodes
3690 hex = new Hexahedron( *this, _i, _j, _k, i );
3691 intHexa.push_back( hex );
3695 // compute definitions of volumes resulted from hexadron intersection
3697 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3698 ParallelHexahedron( intHexa ),
3699 tbb::simple_partitioner()); // computeElements() is called here
3701 for ( size_t i = 0; i < intHexa.size(); ++i )
3702 if ( Hexahedron * hex = intHexa[ i ] )
3703 hex->computeElements();
3706 // simplify polyhedrons
3707 if ( _grid->IsToRemoveExcessEntities() )
3709 for ( size_t i = 0; i < intHexa.size(); ++i )
3710 if ( Hexahedron * hex = intHexa[ i ] )
3711 hex->removeExcessSideDivision( allHexa );
3713 for ( size_t i = 0; i < intHexa.size(); ++i )
3714 if ( Hexahedron * hex = intHexa[ i ] )
3715 hex->removeExcessNodes( allHexa );
3719 for ( size_t i = 0; i < intHexa.size(); ++i )
3720 if ( Hexahedron * hex = intHexa[ i ] )
3721 nbAdded += hex->addVolumes( helper );
3723 // fill boundaryVolumes with volumes neighboring too small skipped volumes
3724 if ( _grid->_toCreateFaces )
3726 for ( size_t i = 0; i < intHexa.size(); ++i )
3727 if ( Hexahedron * hex = intHexa[ i ] )
3728 hex->getBoundaryElems( boundaryVolumes );
3731 // merge nodes on outer sub-shapes with pre-existing ones
3732 TopTools_DataMapIteratorOfDataMapOfShapeInteger s2nIt( _grid->_geometry._shape2NbNodes );
3733 for ( ; s2nIt.More(); s2nIt.Next() )
3734 if ( s2nIt.Value() > 0 )
3735 if ( SMESHDS_SubMesh* sm = mesh->MeshElements( s2nIt.Key() ))
3737 TIDSortedNodeSet smNodes( SMDS_MeshElement::iterator( sm->GetNodes() ),
3738 SMDS_MeshElement::iterator() );
3739 SMESH_MeshEditor::TListOfListOfNodes equalNodes;
3740 SMESH_MeshEditor editor( helper.GetMesh() );
3741 editor.FindCoincidentNodes( smNodes, 10 * _grid->_tol, equalNodes,
3742 /*SeparateCornersAndMedium =*/ false);
3743 if ((int) equalNodes.size() <= s2nIt.Value() )
3744 editor.MergeNodes( equalNodes );
3747 // create boundary mesh faces
3748 addFaces( helper, boundaryVolumes );
3750 // create mesh edges
3751 addSegments( helper, edge2faceIDsMap );
3753 for ( size_t i = 0; i < allHexa.size(); ++i )
3755 delete allHexa[ i ];
3760 //================================================================================
3762 * \brief Implements geom edges into the mesh
3764 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
3765 vector< Hexahedron* >& hexes,
3766 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3768 if ( edge2faceIDsMap.empty() ) return;
3770 // Prepare planes for intersecting with EDGEs
3773 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3775 GridPlanes& planes = pln[ iDirZ ];
3776 int iDirX = ( iDirZ + 1 ) % 3;
3777 int iDirY = ( iDirZ + 2 ) % 3;
3778 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3779 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3780 planes._zProjs [0] = 0;
3781 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3782 const vector< double > & u = _grid->_coords[ iDirZ ];
3783 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3785 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3789 const double deflection = _grid->_minCellSize / 20.;
3790 const double tol = _grid->_tol;
3791 E_IntersectPoint ip;
3793 TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3795 // Intersect EDGEs with the planes
3796 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3797 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3799 const TGeomID edgeID = e2fIt->first;
3800 const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3801 BRepAdaptor_Curve curve( E );
3802 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3803 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3805 ip._faceIDs = e2fIt->second;
3806 ip._shapeID = edgeID;
3808 bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3811 intEdgeIDs.Add( edgeID );
3812 intEdgeIDs.Add( _grid->ShapeID( v1 ));
3813 intEdgeIDs.Add( _grid->ShapeID( v2 ));
3816 // discretize the EDGE
3817 GCPnts_UniformDeflection discret( curve, deflection, true );
3818 if ( !discret.IsDone() || discret.NbPoints() < 2 )
3821 // perform intersection
3822 E_IntersectPoint* eip, *vip = 0;
3823 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3825 GridPlanes& planes = pln[ iDirZ ];
3826 int iDirX = ( iDirZ + 1 ) % 3;
3827 int iDirY = ( iDirZ + 2 ) % 3;
3828 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3829 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3830 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3831 int dIJK[3], d000[3] = { 0,0,0 };
3832 double o[3] = { _grid->_coords[0][0],
3833 _grid->_coords[1][0],
3834 _grid->_coords[2][0] };
3836 // locate the 1st point of a segment within the grid
3837 gp_XYZ p1 = discret.Value( 1 ).XYZ();
3838 double u1 = discret.Parameter( 1 );
3839 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3841 _grid->ComputeUVW( p1, ip._uvw );
3842 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3843 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3844 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3845 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3846 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3847 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3849 int ijk[3]; // grid index where a segment intersects a plane
3854 // add the 1st vertex point to a hexahedron
3858 ip._shapeID = _grid->ShapeID( v1 );
3859 vip = _grid->Add( ip );
3860 _grid->UpdateFacesOfVertex( *vip, v1 );
3862 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3863 if ( !addIntersection( vip, hexes, ijk, d000 ))
3864 _grid->Remove( vip );
3865 ip._shapeID = edgeID;
3867 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3869 // locate the 2nd point of a segment within the grid
3870 gp_XYZ p2 = discret.Value( iP ).XYZ();
3871 double u2 = discret.Parameter( iP );
3872 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3874 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3876 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3878 // treat intersections with planes between 2 end points of a segment
3879 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3880 int iZ = iZ1 + ( iZ1 < iZ2 );
3881 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3883 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3884 planes._zProjs[ iZ ],
3885 curve, planes._zNorm, _grid->_origin );
3886 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3887 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3888 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3891 // add ip to hex "above" the plane
3892 eip = _grid->Add( ip );
3894 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3896 bool added = addIntersection( eip, hexes, ijk, dIJK);
3898 // add ip to hex "below" the plane
3899 ijk[ iDirZ ] = iZ-1;
3900 if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3902 _grid->Remove( eip );
3910 // add the 2nd vertex point to a hexahedron
3914 ip._shapeID = _grid->ShapeID( v2 );
3915 _grid->ComputeUVW( p1, ip._uvw );
3916 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3917 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3919 bool sameV = ( v1.IsSame( v2 ));
3922 vip = _grid->Add( ip );
3923 _grid->UpdateFacesOfVertex( *vip, v2 );
3925 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3927 if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3928 _grid->Remove( vip );
3929 ip._shapeID = edgeID;
3931 } // loop on 3 grid directions
3935 if ( intEdgeIDs.Size() > 0 )
3936 cutByExtendedInternal( hexes, intEdgeIDs );
3941 //================================================================================
3943 * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3944 * Cut them by extended INTERNAL FACE.
3946 void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3947 const TColStd_MapOfInteger& intEdgeIDs )
3949 IntAna_IntConicQuad intersection;
3950 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3951 const double tol2 = _grid->_tol * _grid->_tol;
3953 for ( size_t iH = 0; iH < hexes.size(); ++iH )
3955 Hexahedron* hex = hexes[ iH ];
3956 if ( !hex || hex->_eIntPoints.size() < 2 )
3958 if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3961 // get 3 points on INTERNAL FACE to construct a cutting plane
3962 gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3963 gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3964 gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3966 gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3969 pln = gp_Pln( p1, norm );
3976 TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3977 TGeomID solidID = _grid->GetSolid( intFaceID )->ID();
3979 // cut links by the plane
3980 //bool isCut = false;
3981 for ( int iLink = 0; iLink < 12; ++iLink )
3983 _Link& link = hex->_hexLinks[ iLink ];
3984 if ( !link._fIntPoints.empty() )
3986 // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
3988 continue; // already cut link
3990 if ( !link._nodes[0]->Node() ||
3991 !link._nodes[1]->Node() )
3992 continue; // outside link
3994 if ( link._nodes[0]->IsOnFace( intFaceID ))
3996 if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3997 if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2 ||
3998 p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
3999 link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4000 continue; // link is cut by FACE being "extended"
4002 if ( link._nodes[1]->IsOnFace( intFaceID ))
4004 if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4005 if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2 ||
4006 p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
4007 link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4008 continue; // link is cut by FACE being "extended"
4010 gp_Pnt p4 = link._nodes[0]->Point();
4011 gp_Pnt p5 = link._nodes[1]->Point();
4012 gp_Lin line( p4, gp_Vec( p4, p5 ));
4014 intersection.Perform( line, pln );
4015 if ( !intersection.IsDone() ||
4016 intersection.IsInQuadric() ||
4017 intersection.IsParallel() ||
4018 intersection.NbPoints() < 1 )
4021 double u = intersection.ParamOnConic(1);
4022 if ( u + _grid->_tol < 0 )
4024 int iDir = iLink / 4;
4025 int index = (&hex->_i)[iDir];
4026 double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
4027 if ( u - _grid->_tol > linkLen )
4030 if ( u < _grid->_tol ||
4031 u > linkLen - _grid->_tol ) // intersection at grid node
4033 int i = ! ( u < _grid->_tol ); // [0,1]
4034 int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
4036 const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
4037 _grid->_nodeShift[iN] ];
4040 ip = _grid->_extIntPool.getNew();
4041 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4042 //ip->_transition = Trans_INTERNAL;
4044 else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4046 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4048 hex->_nbFaceIntNodes++;
4053 const gp_Pnt& p = intersection.Point( 1 );
4054 F_IntersectPoint* ip = _grid->_extIntPool.getNew();
4055 ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
4056 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4057 ip->_transition = Trans_INTERNAL;
4058 meshDS->SetNodeInVolume( ip->_node, solidID );
4060 CellsAroundLink fourCells( _grid, iDir );
4061 fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
4062 int i,j,k, cellIndex;
4063 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
4065 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
4067 Hexahedron * h = hexes[ cellIndex ];
4069 h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
4070 h->_hexLinks[iLink]._fIntPoints.push_back( ip );
4071 h->_nbFaceIntNodes++;
4078 // for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
4080 // if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
4081 // ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
4082 // hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4086 } // loop on all hexes
4090 //================================================================================
4092 * \brief Return intersection point on INTERNAL FACE most distant from given ones
4094 gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
4096 gp_Pnt resultPnt = p1;
4098 double maxDist2 = 0;
4099 for ( int iLink = 0; iLink < 12; ++iLink ) // check links
4101 _Link& link = _hexLinks[ iLink ];
4102 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
4103 if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
4104 _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
4105 link._fIntPoints[i]->_node )
4107 gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
4108 double d = p1.SquareDistance( p );
4116 d = p2.SquareDistance( p );
4126 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
4128 for ( size_t iN = 0; iN < 8; ++iN ) // check corners
4130 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
4131 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
4132 if ( _hexNodes[iN]._intPoint )
4133 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
4135 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
4137 gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
4138 double d = p1.SquareDistance( p );
4146 d = p2.SquareDistance( p );
4156 if ( maxDist2 < _grid->_tol * _grid->_tol )
4162 //================================================================================
4164 * \brief Finds intersection of a curve with a plane
4165 * \param [in] u1 - parameter of one curve point
4166 * \param [in] proj1 - projection of the curve point to the plane normal
4167 * \param [in] u2 - parameter of another curve point
4168 * \param [in] proj2 - projection of the other curve point to the plane normal
4169 * \param [in] proj - projection of a point where the curve intersects the plane
4170 * \param [in] curve - the curve
4171 * \param [in] axis - the plane normal
4172 * \param [in] origin - the plane origin
4173 * \return gp_Pnt - the found intersection point
4175 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
4176 double u2, double proj2,
4178 BRepAdaptor_Curve& curve,
4180 const gp_XYZ& origin)
4182 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
4183 double u = u1 * ( 1 - r ) + u2 * r;
4184 gp_Pnt p = curve.Value( u );
4185 double newProj = axis * ( p.XYZ() - origin );
4186 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
4189 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
4191 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
4196 //================================================================================
4198 * \brief Returns indices of a hexahedron sub-entities holding a point
4199 * \param [in] ip - intersection point
4200 * \param [out] facets - 0-3 facets holding a point
4201 * \param [out] sub - index of a vertex or an edge holding a point
4202 * \return int - number of facets holding a point
4204 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
4206 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
4208 int vertex = 0, edgeMask = 0;
4210 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
4211 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
4214 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
4215 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
4219 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
4220 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
4223 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
4224 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
4228 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
4229 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
4232 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
4233 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
4240 case 0: sub = 0; break;
4241 case 1: sub = facets[0]; break;
4243 const int edge [3][8] = {
4244 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
4245 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
4246 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
4247 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
4248 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
4249 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
4251 switch ( edgeMask ) {
4252 case X | Y: sub = edge[ 0 ][ vertex ]; break;
4253 case X | Z: sub = edge[ 1 ][ vertex ]; break;
4254 default: sub = edge[ 2 ][ vertex ];
4260 sub = vertex + SMESH_Block::ID_FirstV;
4265 //================================================================================
4267 * \brief Adds intersection with an EDGE
4269 bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
4270 vector< Hexahedron* >& hexes,
4271 int ijk[], int dIJK[] )
4275 size_t hexIndex[4] = {
4276 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
4277 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
4278 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
4279 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
4281 for ( int i = 0; i < 4; ++i )
4283 if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
4285 Hexahedron* h = hexes[ hexIndex[i] ];
4286 h->_eIntPoints.reserve(2);
4287 h->_eIntPoints.push_back( ip );
4290 // check if ip is really inside the hex
4291 if (SALOME::VerbosityActivated() && h->isOutParam( ip->_uvw ))
4292 throw SALOME_Exception("ip outside a hex");
4297 //================================================================================
4299 * \brief Check if a hexahedron facet lies on a FACE
4300 * Also return true if the facet does not interfere with any FACE
4302 bool Hexahedron::isQuadOnFace( const size_t iQuad )
4304 _Face& quad = _hexQuads[ iQuad ] ;
4306 int nbGridNodesInt = 0; // nb FACE intersections at grid nodes
4307 int nbNoGeomNodes = 0;
4308 for ( int iE = 0; iE < 4; ++iE )
4310 nbNoGeomNodes = ( !quad._links[ iE ].FirstNode()->_intPoint &&
4311 quad._links[ iE ].NbResultLinks() == 1 );
4313 ( quad._links[ iE ].FirstNode()->_intPoint &&
4314 quad._links[ iE ].NbResultLinks() == 1 &&
4315 quad._links[ iE ].ResultLink( 0 ).FirstNode() == quad._links[ iE ].FirstNode() &&
4316 quad._links[ iE ].ResultLink( 0 ).LastNode() == quad._links[ iE ].LastNode() );
4318 if ( nbNoGeomNodes == 4 )
4321 if ( nbGridNodesInt == 4 ) // all quad nodes are at FACE intersection
4323 size_t iEmin = 0, minNbFaces = 1000;
4324 for ( int iE = 0; iE < 4; ++iE ) // look for a node with min nb FACEs
4326 size_t nbFaces = quad._links[ iE ].FirstNode()->faces().size();
4327 if ( minNbFaces > nbFaces )
4330 minNbFaces = nbFaces;
4333 // check if there is a FACE passing through all 4 nodes
4334 for ( const TGeomID& faceID : quad._links[ iEmin ].FirstNode()->faces() )
4336 bool allNodesAtFace = true;
4337 for ( size_t iE = 0; iE < 4 && allNodesAtFace; ++iE )
4338 allNodesAtFace = ( iE == iEmin ||
4339 quad._links[ iE ].FirstNode()->IsOnFace( faceID ));
4340 if ( allNodesAtFace ) // quad if on faceID
4346 //================================================================================
4348 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
4350 bool Hexahedron::findChain( _Node* n1,
4353 vector<_Node*>& chn )
4356 chn.push_back( n1 );
4357 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4358 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4359 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
4360 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4362 chn.push_back( quad._eIntNodes[ iP ]);
4363 chn.push_back( n2 );
4364 quad._eIntNodes[ iP ]->_usedInFace = &quad;
4371 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4372 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4373 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4375 chn.push_back( quad._eIntNodes[ iP ]);
4376 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4379 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4381 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4382 chn.push_back( n2 );
4384 return chn.size() > 1;
4386 //================================================================================
4388 * \brief Try to heal a polygon whose ends are not connected
4390 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4392 int i = -1, nbLinks = polygon->_links.size();
4395 vector< _OrientedLink > newLinks;
4396 // find a node lying on the same FACE as the last one
4397 _Node* node = polygon->_links.back().LastNode();
4398 TGeomID avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4399 for ( i = nbLinks - 2; i >= 0; --i )
4400 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4404 for ( ; i < nbLinks; ++i )
4405 newLinks.push_back( polygon->_links[i] );
4409 // find a node lying on the same FACE as the first one
4410 node = polygon->_links[0].FirstNode();
4411 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4412 for ( i = 1; i < nbLinks; ++i )
4413 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4416 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4417 newLinks.push_back( polygon->_links[i] );
4419 if ( newLinks.size() > 1 )
4421 polygon->_links.swap( newLinks );
4423 chainNodes.push_back( polygon->_links.back().LastNode() );
4424 chainNodes.push_back( polygon->_links[0].FirstNode() );
4429 //================================================================================
4431 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4433 * This function is for
4434 * 1) a case where an EDGE lies on a quad which lies on a FACE
4435 * so that a part of quad in ON and another part is IN
4436 * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4438 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4439 const _OrientedLink& prevSplit,
4440 const _OrientedLink& avoidSplit,
4441 const std::set< TGeomID > & concaveFaces,
4444 vector<_Node*>& chn )
4446 _Node* pn1 = prevSplit.FirstNode();
4447 _Node* pn2 = prevSplit.LastNode(); // pn2 is on EDGE, if not on INTERNAL FACE
4448 _Node* an3 = avoidSplit.LastNode();
4449 TGeomID avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4450 if ( avoidFace < 1 && pn1->_intPoint )
4455 if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4457 chn.push_back( pn2 );
4462 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4463 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4464 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4465 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4467 chn.push_back( quad._eIntNodes[ iP ]);
4468 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4475 _Node* n = 0, *stopNode = avoidSplit.LastNode();
4477 if ( pn2 == prevSplit.LastNode() && // pn2 is at avoidSplit.FirstNode()
4478 !isCorner( stopNode )) // stopNode is in the middle of a _hexLinks
4480 // move stopNode to a _hexNodes
4481 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
4482 for ( size_t iL = 0; iL < quad._links[ iE ].NbResultLinks(); ++iL )
4484 const _Link* sideSplit = & quad._links[ iE ]._link->_splits[ iL ];
4485 if ( sideSplit == avoidSplit._link )
4487 if ( quad._links[ iE ].LastNode()->Node() )
4488 stopNode = quad._links[ iE ].LastNode();
4495 // connect pn2 (probably new, at _eIntNodes) with a split
4499 TGeomID commonFaces[20];
4500 _Node* nPrev = nullptr;
4501 for ( i = splits.size()-1; i >= 0; --i )
4507 for ( int is1st = 0; is1st < 2; ++is1st )
4509 _Node* nConn = is1st ? splits[i].FirstNode() : splits[i].LastNode();
4510 if ( nConn == nPrev )
4517 if (( stop = ( nConn == stopNode )))
4519 // find a FACE connecting nConn with pn2 but not with an3
4520 if (( nConn != pn1 ) &&
4521 ( nConn->_intPoint && !nConn->_intPoint->_faceIDs.empty() ) &&
4522 ( nbCommon = nConn->GetCommonFaces( pn2->_intPoint, commonFaces )))
4524 bool a3Coonect = true;
4525 for ( size_t iF = 0; iF < nbCommon && a3Coonect; ++iF )
4526 a3Coonect = an3->IsOnFace( commonFaces[ iF ]) || concaveFaces.count( commonFaces[ iF ]);
4535 if ( nbCommon > 1 ) // nConn is linked with pn2 by an EDGE
4551 if ( n && n != stopNode )
4554 chn.push_back( pn2 );
4559 else if ( !chn.empty() && chn.back()->_isInternalFlags )
4561 // INTERNAL FACE partially cuts the quad
4562 for ( int ip = chn.size() - 2; ip >= 0; --ip )
4563 chn.push_back( chn[ ip ]);
4568 //================================================================================
4570 * \brief Checks transition at the ginen intersection node of a link
4572 bool Hexahedron::isOutPoint( _Link& link, int iP,
4573 SMESH_MesherHelper& helper, const Solid* solid ) const
4577 if ( link._fIntNodes[iP]->faces().size() == 1 &&
4578 _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4581 const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4584 _Node* n1 = link._fIntNodes[ iP ];
4586 n1 = link._nodes[0];
4587 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4588 if ( !n2 || !n2->Node() )
4589 n2 = link._nodes[1];
4593 // get all FACEs under n1 and n2
4594 set< TGeomID > faceIDs;
4595 if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4596 link._fIntNodes[iP+1]->faces().end() );
4597 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4598 n2->_intPoint->_faceIDs.end() );
4599 if ( faceIDs.empty() )
4600 return false; // n2 is inside
4601 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4602 n1->_intPoint->_faceIDs.end() );
4603 faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4604 link._fIntNodes[iP]->faces().end() );
4606 // get a point between 2 nodes
4607 gp_Pnt p1 = n1->Point();
4608 gp_Pnt p2 = n2->Point();
4609 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4611 TopLoc_Location loc;
4613 set< TGeomID >::iterator faceID = faceIDs.begin();
4614 for ( ; faceID != faceIDs.end(); ++faceID )
4616 // project pOnLink on a FACE
4617 if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4618 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4619 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4620 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4621 proj.Perform( testPnt );
4622 if ( proj.IsDone() && proj.NbPoints() > 0 )
4625 proj.LowerDistanceParameters( u,v );
4627 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4633 // find isOut by normals
4635 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4640 if ( solid->Orientation( face ) == TopAbs_REVERSED )
4642 gp_Vec v( proj.NearestPoint(), testPnt );
4643 isOut = ( v * normal > 0 );
4648 // classify a projection
4649 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4651 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4652 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4653 if ( state == TopAbs_OUT )
4665 //================================================================================
4667 * \brief Sort nodes on a FACE
4669 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4671 if ( nodes.size() > 20 ) return;
4673 // get shapes under nodes
4674 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4675 for ( size_t i = 0; i < nodes.size(); ++i )
4676 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4679 // get shapes of the FACE
4680 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( faceID ));
4681 list< TopoDS_Edge > edges;
4682 list< int > nbEdges;
4683 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4685 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4686 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4687 list< int >::iterator nE = nbEdges.begin();
4688 for ( ; nbW > 0; ++nE, --nbW )
4690 std::advance( eEnd, *nE );
4691 for ( ; e != eEnd; ++e )
4692 for ( int i = 0; i < 2; ++i )
4695 _grid->ShapeID( *e ) :
4696 _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4698 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4700 edges.erase( eEnd, edges.end() ); // remove rest wires
4701 e = eEnd = edges.end();
4708 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4711 // rotate edges to have the first one at least partially out of the hexa
4712 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4713 for ( ; e != edges.end(); ++e )
4715 if ( !_grid->ShapeID( *e ))
4720 for ( int i = 0; i < 2 && !isOut; ++i )
4724 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4725 p = BRep_Tool::Pnt( v );
4727 else if ( eMidOut == edges.end() )
4729 TopLoc_Location loc;
4730 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4731 if ( c.IsNull() ) break;
4732 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4739 _grid->ComputeUVW( p.XYZ(), uvw );
4740 if ( isOutParam( uvw ))
4751 if ( e != edges.end() )
4752 edges.splice( edges.end(), edges, edges.begin(), e );
4753 else if ( eMidOut != edges.end() )
4754 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4756 // sort nodes according to the order of edges
4757 _Node* orderNodes [20];
4758 //TGeomID orderShapeIDs[20];
4760 TGeomID id, *pID = 0;
4761 for ( e = edges.begin(); e != edges.end(); ++e )
4763 if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4764 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4766 //orderShapeIDs[ nbN ] = id;
4767 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4770 if (( id = _grid->ShapeID( *e )) &&
4771 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4773 //orderShapeIDs[ nbN ] = id;
4774 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4778 if ( nbN != nodes.size() )
4781 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
4782 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4784 for ( size_t i = 0; i < nodes.size(); ++i )
4785 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4788 //================================================================================
4790 * \brief Adds computed elements to the mesh
4792 int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4794 F_IntersectPoint noIntPnt;
4795 const bool toCheckNodePos = _grid->IsToCheckNodePos();
4798 // add elements resulted from hexahedron intersection
4799 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4801 vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4802 for ( size_t iN = 0; iN < nodes.size(); ++iN )
4804 if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4806 if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4808 nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4809 helper.AddNode( eip->_point.X(),
4812 if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4813 helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4815 helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4818 throw SALOME_Exception("Bug: no node at intersection point");
4820 else if ( volDef->_nodes[iN]._intPoint &&
4821 volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4823 // Update position of node at EDGE intersection;
4824 // see comment to _Node::Add( E_IntersectPoint )
4825 SMESHDS_Mesh* mesh = helper.GetMeshDS();
4826 TGeomID shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4827 mesh->UnSetNodeOnShape( nodes[iN] );
4828 if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4829 mesh->SetNodeOnVertex( nodes[iN], shapeID );
4831 mesh->SetNodeOnEdge( nodes[iN], shapeID );
4833 else if ( toCheckNodePos &&
4834 !nodes[iN]->isMarked() &&
4835 _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4837 _grid->SetOnShape( nodes[iN], noIntPnt, /*v=*/nullptr,/*unset=*/true );
4838 nodes[iN]->setIsMarked( true );
4840 } // loop to get nodes
4842 const SMDS_MeshElement* v = 0;
4843 if ( !volDef->_quantities.empty() )
4845 v = helper.AddPolyhedralVolume( nodes, volDef->_quantities );
4846 volDef->_size = SMDS_VolumeTool( v ).GetSize();
4847 if ( volDef->_size < 0 ) // invalid polyhedron
4849 if ( ! SMESH_MeshEditor( helper.GetMesh() ).Reorient( v ) || // try to fix
4850 SMDS_VolumeTool( v ).GetSize() < 0 )
4852 helper.GetMeshDS()->RemoveFreeElement( v, /*sm=*/nullptr, /*fromGroups=*/false );
4854 //_hasTooSmall = true;
4856 if (SALOME::VerbosityActivated())
4858 std::cout << "Remove INVALID polyhedron, _cellID = " << _cellID
4859 << " ijk = ( " << _i << " " << _j << " " << _k << " ) "
4860 << " solid " << volDef->_solidID << std::endl;
4867 switch ( nodes.size() )
4869 case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4870 nodes[4],nodes[5],nodes[6],nodes[7] );
4872 case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4874 case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4876 case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4880 volDef->_volume = v;
4881 nbAdded += bool( v );
4883 } // loop on _volumeDefs chain
4885 // avoid creating overlapping volumes (bos #24052)
4888 double sumSize = 0, maxSize = 0;
4889 _volumeDef* maxSizeDef = nullptr;
4890 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4892 if ( !volDef->_volume )
4894 sumSize += volDef->_size;
4895 if ( volDef->_size > maxSize )
4897 maxSize = volDef->_size;
4898 maxSizeDef = volDef;
4901 if ( sumSize > _sideLength[0] * _sideLength[1] * _sideLength[2] * 1.05 )
4903 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4904 if ( volDef != maxSizeDef && volDef->_volume )
4906 helper.GetMeshDS()->RemoveFreeElement( volDef->_volume, /*sm=*/nullptr,
4907 /*fromGroups=*/false );
4908 volDef->_volume = nullptr;
4909 //volDef->_nodes.clear();
4915 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4917 if ( volDef->_volume )
4919 helper.GetMeshDS()->SetMeshElementOnShape( volDef->_volume, volDef->_solidID );
4925 //================================================================================
4927 * \brief Return true if the element is in a hole
4929 bool Hexahedron::isInHole() const
4931 if ( !_vIntNodes.empty() )
4934 const size_t ijk[3] = { _i, _j, _k };
4935 F_IntersectPoint curIntPnt;
4937 // consider a cell to be in a hole if all links in any direction
4938 // comes OUT of geometry
4939 for ( int iDir = 0; iDir < 3; ++iDir )
4941 const vector<double>& coords = _grid->_coords[ iDir ];
4942 LineIndexer li = _grid->GetLineIndexer( iDir );
4943 li.SetIJK( _i,_j,_k );
4944 size_t lineIndex[4] = { li.LineIndex (),
4948 bool allLinksOut = true, hasLinks = false;
4949 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4951 const _Link& link = _hexLinks[ iL + 4*iDir ];
4952 // check transition of the first node of a link
4953 const F_IntersectPoint* firstIntPnt = 0;
4954 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4956 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4957 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4958 if ( !line._intPoints.empty() )
4960 multiset< F_IntersectPoint >::const_iterator ip =
4961 line._intPoints.upper_bound( curIntPnt );
4963 firstIntPnt = &(*ip);
4966 else if ( !link._fIntPoints.empty() )
4968 firstIntPnt = link._fIntPoints[0];
4974 allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4975 !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4978 if ( hasLinks && allLinksOut )
4984 //================================================================================
4986 * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
4987 * that will be meshed by other algo
4989 bool Hexahedron::hasStrangeEdge() const
4991 if ( _eIntPoints.size() < 2 )
4994 TopTools_MapOfShape edges;
4995 for ( size_t i = 0; i < _eIntPoints.size(); ++i )
4997 if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
4999 const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
5000 if ( s.ShapeType() == TopAbs_EDGE )
5002 if ( ! edges.Add( s ))
5003 return true; // an EDGE encounters twice
5007 PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
5008 *_grid->_helper->GetMesh(),
5010 while ( const TopoDS_Shape* edge = edgeIt->next() )
5011 if ( ! edges.Add( *edge ))
5012 return true; // an EDGE encounters twice
5018 //================================================================================
5020 * \brief Return true if a polyhedron passes _sizeThreshold criterion
5022 bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace, double & volume) const
5026 if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
5028 // check if any polygon fully lies on shared/internal FACEs
5029 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5031 const _Face& polygon = _polygons[iP];
5032 if ( polygon._links.empty() )
5034 bool allNodesInternal = true;
5035 for ( size_t iL = 0; iL < polygon._links.size() && allNodesInternal; ++iL )
5037 _Node* n = polygon._links[ iL ].FirstNode();
5038 allNodesInternal = (( n->IsCutByInternal() ) ||
5039 ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
5041 if ( allNodesInternal )
5045 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5047 const _Face& polygon = _polygons[iP];
5048 if ( polygon._links.empty() )
5050 gp_XYZ area (0,0,0);
5051 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
5052 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
5054 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
5058 volume += p1 * area;
5062 if ( this->hasStrangeEdge() && volume > 1e-13 )
5065 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
5067 return volume > initVolume / _grid->_sizeThreshold;
5069 //================================================================================
5071 * \brief Tries to create a hexahedron
5073 bool Hexahedron::addHexa()
5075 int nbQuad = 0, iQuad = -1;
5076 for ( size_t i = 0; i < _polygons.size(); ++i )
5078 if ( _polygons[i]._links.empty() )
5080 if ( _polygons[i]._links.size() != 4 )
5091 for ( int iL = 0; iL < 4; ++iL )
5094 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
5097 // find a top node above the base node
5098 _Link* link = _polygons[iQuad]._links[iL]._link;
5099 if ( !link->_faces[0] || !link->_faces[1] )
5100 return debugDumpLink( link );
5101 // a quadrangle sharing <link> with _polygons[iQuad]
5102 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
5103 for ( int i = 0; i < 4; ++i )
5104 if ( quad->_links[i]._link == link )
5106 // 1st node of a link opposite to <link> in <quad>
5107 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
5113 _volumeDefs.Set( &nodes[0], 8 );
5117 //================================================================================
5119 * \brief Tries to create a tetrahedron
5121 bool Hexahedron::addTetra()
5124 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
5125 if ( _polygons[i]._links.size() == 3 )
5131 nodes[0] = _polygons[iTria]._links[0].FirstNode();
5132 nodes[1] = _polygons[iTria]._links[1].FirstNode();
5133 nodes[2] = _polygons[iTria]._links[2].FirstNode();
5135 _Link* link = _polygons[iTria]._links[0]._link;
5136 if ( !link->_faces[0] || !link->_faces[1] )
5137 return debugDumpLink( link );
5139 // a triangle sharing <link> with _polygons[0]
5140 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
5141 for ( int i = 0; i < 3; ++i )
5142 if ( tria->_links[i]._link == link )
5144 nodes[3] = tria->_links[(i+1)%3].LastNode();
5145 _volumeDefs.Set( &nodes[0], 4 );
5151 //================================================================================
5153 * \brief Tries to create a pentahedron
5155 bool Hexahedron::addPenta()
5157 // find a base triangular face
5159 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
5160 if ( _polygons[ iF ]._links.size() == 3 )
5162 if ( iTri < 0 ) return false;
5167 for ( int iL = 0; iL < 3; ++iL )
5170 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
5173 // find a top node above the base node
5174 _Link* link = _polygons[ iTri ]._links[iL]._link;
5175 if ( !link->_faces[0] || !link->_faces[1] )
5176 return debugDumpLink( link );
5177 // a quadrangle sharing <link> with a base triangle
5178 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
5179 if ( quad->_links.size() != 4 ) return false;
5180 for ( int i = 0; i < 4; ++i )
5181 if ( quad->_links[i]._link == link )
5183 // 1st node of a link opposite to <link> in <quad>
5184 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
5190 _volumeDefs.Set( &nodes[0], 6 );
5192 return ( nbN == 6 );
5194 //================================================================================
5196 * \brief Tries to create a pyramid
5198 bool Hexahedron::addPyra()
5200 // find a base quadrangle
5202 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
5203 if ( _polygons[ iF ]._links.size() == 4 )
5205 if ( iQuad < 0 ) return false;
5209 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
5210 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
5211 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
5212 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
5214 _Link* link = _polygons[iQuad]._links[0]._link;
5215 if ( !link->_faces[0] || !link->_faces[1] )
5216 return debugDumpLink( link );
5218 // a triangle sharing <link> with a base quadrangle
5219 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
5220 if ( tria->_links.size() != 3 ) return false;
5221 for ( int i = 0; i < 3; ++i )
5222 if ( tria->_links[i]._link == link )
5224 nodes[4] = tria->_links[(i+1)%3].LastNode();
5225 _volumeDefs.Set( &nodes[0], 5 );
5231 //================================================================================
5233 * \brief Return true if there are _eIntPoints at EDGEs forming a concave corner
5235 bool Hexahedron::hasEdgesAround( const ConcaveFace* cf ) const
5238 ConcaveFace foundGeomHolder;
5239 for ( const E_IntersectPoint* ip : _eIntPoints )
5241 if ( cf->HasEdge( ip->_shapeID ))
5243 if ( ++nbEdges == 2 )
5245 foundGeomHolder.SetEdge( ip->_shapeID );
5247 else if ( ip->_faceIDs.size() >= 3 )
5249 const TGeomID & vID = ip->_shapeID;
5250 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5252 if ( ++nbEdges == 2 )
5254 foundGeomHolder.SetVertex( vID );
5259 for ( const _Node& hexNode: _hexNodes )
5261 if ( !hexNode._node || !hexNode._intPoint )
5263 const B_IntersectPoint* ip = hexNode._intPoint;
5264 if ( ip->_faceIDs.size() == 2 ) // EDGE
5266 TGeomID edgeID = hexNode._node->GetShapeID();
5267 if ( cf->HasEdge( edgeID ) && !foundGeomHolder.HasEdge( edgeID ))
5269 foundGeomHolder.SetEdge( edgeID );
5270 if ( ++nbEdges == 2 )
5274 else if ( ip->_faceIDs.size() >= 3 ) // VERTEX
5276 TGeomID vID = hexNode._node->GetShapeID();
5277 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5279 if ( ++nbEdges == 2 )
5281 foundGeomHolder.SetVertex( vID );
5288 //================================================================================
5290 * \brief Dump a link and return \c false
5292 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
5294 if (SALOME::VerbosityActivated())
5296 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
5297 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
5298 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
5299 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
5304 //================================================================================
5306 * \brief Classify a point by grid parameters
5308 bool Hexahedron::isOutParam(const double uvw[3]) const
5310 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
5311 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
5312 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
5313 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
5314 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
5315 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
5317 //================================================================================
5319 * \brief Find existing triangulation of a polygon
5321 int findExistingTriangulation( const SMDS_MeshElement* polygon,
5322 //const SMDS_Mesh* mesh,
5323 std::vector< const SMDS_MeshNode* >& nodes )
5327 std::vector<const SMDS_MeshNode *> twoNodes(2);
5328 std::vector<const SMDS_MeshElement *> foundFaces; foundFaces.reserve(10);
5329 std::set< const SMDS_MeshElement * > avoidFaces; avoidFaces.insert( polygon );
5331 const int nbPolyNodes = polygon->NbCornerNodes();
5332 twoNodes[1] = polygon->GetNode( nbPolyNodes - 1 );
5333 for ( int iN = 0; iN < nbPolyNodes; ++iN ) // loop on border links of polygon
5335 twoNodes[0] = polygon->GetNode( iN );
5337 int nbFaces = SMDS_Mesh::GetElementsByNodes( twoNodes, foundFaces, SMDSAbs_Face );
5339 for ( int iF = 0; iF < nbFaces; ++iF ) // keep faces lying over polygon
5341 if ( avoidFaces.count( foundFaces[ iF ]))
5343 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5344 for ( i = 0; i < nbFaceNodes; ++i )
5346 const SMDS_MeshNode* n = foundFaces[ iF ]->GetNode( i );
5347 bool isCommonNode = ( n == twoNodes[0] ||
5349 polygon->GetNodeIndex( n ) >= 0 );
5350 if ( !isCommonNode )
5353 if ( i == nbFaceNodes ) // all nodes of foundFaces[iF] are shared with polygon
5354 if ( nbOkFaces++ != iF )
5355 foundFaces[ nbOkFaces-1 ] = foundFaces[ iF ];
5357 if ( nbOkFaces > 0 )
5359 int iFaceSelected = 0;
5360 if ( nbOkFaces > 1 ) // select a face with minimal distance from polygon
5362 double minDist = Precision::Infinite();
5363 for ( int iF = 0; iF < nbOkFaces; ++iF )
5365 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5366 gp_XYZ gc = SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( 0 ));
5367 for ( i = 1; i < nbFaceNodes; ++i )
5368 gc += SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( i ));
5371 double dist = SMESH_MeshAlgos::GetDistance( polygon, gc );
5372 if ( dist < minDist )
5379 if ( foundFaces[ iFaceSelected ]->NbCornerNodes() != 3 )
5381 nodes.insert( nodes.end(),
5382 foundFaces[ iFaceSelected ]->begin_nodes(),
5383 foundFaces[ iFaceSelected ]->end_nodes());
5384 if ( !SMESH_MeshAlgos::IsRightOrder( foundFaces[ iFaceSelected ],
5385 twoNodes[0], twoNodes[1] ))
5387 // reverse just added nodes
5388 std::reverse( nodes.end() - 3, nodes.end() );
5390 avoidFaces.insert( foundFaces[ iFaceSelected ]);
5394 twoNodes[1] = twoNodes[0];
5396 } // loop on polygon nodes
5400 //================================================================================
5402 * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
5404 void splitPolygon( const SMDS_MeshElement* polygon,
5405 SMDS_VolumeTool & volume,
5406 const int facetIndex,
5407 const TGeomID faceID,
5408 const TGeomID solidID,
5409 SMESH_MeshEditor::ElemFeatures& face,
5410 SMESH_MeshEditor& editor,
5411 const bool reinitVolume)
5413 SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
5414 bool triangulationExist = false;
5415 int nbTrias = findExistingTriangulation( polygon, face.myNodes );
5417 triangulationExist = true;
5419 nbTrias = divider.GetTriangles( polygon, face.myNodes );
5420 face.myNodes.resize( nbTrias * 3 );
5422 SMESH_MeshEditor::ElemFeatures newVolumeDef;
5423 newVolumeDef.Init( volume.Element() );
5424 newVolumeDef.SetID( volume.Element()->GetID() );
5426 newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
5427 newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
5429 SMESHDS_Mesh* meshDS = editor.GetMeshDS();
5430 SMDS_MeshElement* newTriangle;
5431 for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
5433 if ( iF == facetIndex )
5435 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5436 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5437 face.myNodes.begin(),
5438 face.myNodes.begin() + 3 );
5439 meshDS->RemoveFreeElement( polygon, 0, false );
5440 if ( !triangulationExist )
5442 newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
5443 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5448 const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
5449 const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
5450 newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
5451 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
5455 for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
5457 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5458 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5459 face.myNodes.begin() + iN,
5460 face.myNodes.begin() + iN + 3 );
5461 if ( !triangulationExist )
5463 newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
5464 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5468 meshDS->RemoveFreeElement( volume.Element(), 0, false );
5469 SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
5470 meshDS->SetMeshElementOnShape( newVolume, solidID );
5475 volume.Set( newVolume );
5479 //================================================================================
5481 * \brief Look for a FACE supporting all given nodes made on EDGEs and VERTEXes
5483 TGeomID findCommonFace( const std::vector< const SMDS_MeshNode* > & nn,
5484 const SMESH_Mesh* mesh )
5487 TGeomID shapeIDs[20];
5488 for ( size_t iN = 0; iN < nn.size(); ++iN )
5489 shapeIDs[ iN ] = nn[ iN ]->GetShapeID();
5491 SMESH_subMesh* sm = mesh->GetSubMeshContaining( shapeIDs[ 0 ]);
5492 for ( const SMESH_subMesh * smFace : sm->GetAncestors() )
5494 if ( smFace->GetSubShape().ShapeType() != TopAbs_FACE )
5497 faceID = smFace->GetId();
5499 for ( size_t iN = 1; iN < nn.size() && faceID; ++iN )
5501 if ( !smFace->DependsOn( shapeIDs[ iN ]))
5509 //================================================================================
5511 * \brief Create mesh faces at free facets
5513 void Hexahedron::addFaces( SMESH_MesherHelper& helper,
5514 const vector< const SMDS_MeshElement* > & boundaryVolumes )
5516 if ( !_grid->_toCreateFaces )
5519 SMDS_VolumeTool vTool;
5520 vector<int> bndFacets;
5521 SMESH_MeshEditor editor( helper.GetMesh() );
5522 SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
5523 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
5525 // check if there are internal or shared FACEs
5526 bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
5527 _grid->_geometry._soleSolid.HasInternalFaces() );
5529 for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
5531 if ( !vTool.Set( boundaryVolumes[ iV ]))
5534 TGeomID solidID = vTool.Element()->GetShapeID();
5535 Solid * solid = _grid->GetOneOfSolids( solidID );
5537 // find boundary facets
5540 for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
5542 const SMDS_MeshElement* otherVol;
5543 bool isBoundary = vTool.IsFreeFace( iF, &otherVol );
5546 bndFacets.push_back( iF );
5548 else if (( hasInternal ) ||
5549 ( !_grid->IsSolid( otherVol->GetShapeID() )))
5551 // check if all nodes are on internal/shared FACEs
5553 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
5554 const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
5555 for ( size_t iN = 0; iN < nbFaceNodes && isBoundary; ++iN )
5556 isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
5558 bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
5561 if ( bndFacets.empty() )
5566 if ( !vTool.IsPoly() )
5567 vTool.SetExternalNormal();
5568 for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
5570 const bool isBoundary = ( bndFacets[i] >= 0 );
5571 const int iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
5572 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
5573 const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
5574 face.myNodes.assign( nn, nn + nbFaceNodes );
5577 const SMDS_MeshElement* existFace = 0, *newFace = 0;
5579 if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
5581 if ( existFace->isMarked() )
5582 continue; // created by this method
5583 faceID = existFace->GetShapeID();
5587 // look for a supporting FACE
5588 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN ) // look for a node on FACE
5590 if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
5591 faceID = nn[ iN ]->GetShapeID();
5594 faceID = findCommonFace( face.myNodes, helper.GetMesh() );
5596 bool toCheckFace = faceID && (( !isBoundary ) ||
5597 ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
5598 if ( toCheckFace ) // check if all nodes are on the found FACE
5600 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
5601 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5603 TGeomID subID = nn[ iN ]->GetShapeID();
5604 if ( subID != faceID && !faceSM->DependsOn( subID ))
5607 // if ( !faceID && !isBoundary )
5610 if ( !faceID && !isBoundary )
5614 // orient a new face according to supporting FACE orientation in shape_to_mesh
5615 if ( !isBoundary && !solid->IsOutsideOriented( faceID ))
5618 editor.Reorient( existFace );
5620 std::reverse( face.myNodes.begin(), face.myNodes.end() );
5623 if ( ! ( newFace = existFace ))
5625 face.SetPoly( nbFaceNodes > 4 );
5626 newFace = editor.AddElement( face.myNodes, face );
5629 newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
5632 if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
5634 // set newFace to the found FACE provided that it fully lies on the FACE
5635 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5636 if ( nn[iN]->GetShapeID() == solidID )
5639 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
5644 if ( faceID && nbFaceNodes > 4 &&
5645 !_grid->IsInternal( faceID ) &&
5646 !_grid->IsShared( faceID ) &&
5647 !_grid->IsBoundaryFace( faceID ))
5649 // split a polygon that will be used by other 3D algorithm
5651 splitPolygon( newFace, vTool, iFacet, faceID, solidID,
5652 face, editor, i+1 < bndFacets.size() );
5657 meshDS->SetMeshElementOnShape( newFace, faceID );
5659 meshDS->SetMeshElementOnShape( newFace, solidID );
5661 } // loop on bndFacets
5662 } // loop on boundaryVolumes
5665 // Orient coherently mesh faces on INTERNAL FACEs
5669 TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5670 for ( ; faceExp.More(); faceExp.Next() )
5672 if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5675 SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5676 if ( !sm ) continue;
5678 TIDSortedElemSet facesToOrient;
5679 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5680 facesToOrient.insert( facesToOrient.end(), fIt->next() );
5681 if ( facesToOrient.size() < 2 )
5684 gp_Dir direction(1,0,0);
5685 TIDSortedElemSet refFaces;
5686 editor.Reorient2D( facesToOrient, direction, refFaces, /*allowNonManifold=*/true );
5692 //================================================================================
5694 * \brief Create mesh segments.
5696 void Hexahedron::addSegments( SMESH_MesherHelper& helper,
5697 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5699 SMESHDS_Mesh* mesh = helper.GetMeshDS();
5701 std::vector<const SMDS_MeshNode*> nodes;
5702 std::vector<const SMDS_MeshElement *> elems;
5703 map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5704 for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5706 const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5707 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5708 StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5709 nodes = side.GetOrderedNodes();
5712 if ( nodes.size() == 2 )
5713 // check that there is an element connecting two nodes
5714 if ( !mesh->GetElementsByNodes( nodes, elems ))
5717 for ( size_t i = 1; i < nodes.size(); i++ )
5719 if ( mesh->FindEdge( nodes[i-1], nodes[i] ))
5721 SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5722 mesh->SetMeshElementOnShape( segment, e2ff->first );
5728 //================================================================================
5730 * \brief Return created volumes and volumes that can have free facet because of
5731 * skipped small volume. Also create mesh faces on free facets
5732 * of adjacent not-cut volumes if the result volume is too small.
5734 void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5736 if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5738 // create faces around a missing small volume
5740 SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5741 SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5742 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5743 std::vector<const SMDS_MeshElement *> adjVolumes(2);
5744 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5746 const size_t nbLinks = _polygons[ iF ]._links.size();
5747 if ( nbLinks != 4 ) continue;
5748 polygon.myNodes.resize( nbLinks );
5749 polygon.myNodes.back() = 0;
5750 for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5751 if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5753 if ( !polygon.myNodes.back() )
5756 meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5757 if ( adjVolumes.size() != 1 )
5759 if ( !adjVolumes[0]->isMarked() )
5761 boundaryElems.push_back( adjVolumes[0] );
5762 adjVolumes[0]->setIsMarked( true );
5765 bool sameShape = true;
5766 TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5767 for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5768 sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5770 if ( !sameShape || !_grid->IsSolid( shapeID ))
5771 continue; // some of shapes must be FACE
5775 faceID = getAnyFace();
5778 if ( _grid->IsInternal( faceID ) ||
5779 _grid->IsShared( faceID ) //||
5780 //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5782 break; // create only if a new face will be used by other 3D algo
5785 Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5786 if ( !solid->IsOutsideOriented( faceID ))
5787 std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5789 //polygon.SetPoly( polygon.myNodes.size() > 4 );
5790 const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5791 meshDS->SetMeshElementOnShape( newFace, faceID );
5795 // return created volumes
5796 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5798 if ( volDef ->_volume &&
5799 !volDef->_volume->IsNull() &&
5800 !volDef->_volume->isMarked() )
5802 volDef->_volume->setIsMarked( true );
5803 boundaryElems.push_back( volDef->_volume );
5805 if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5806 for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5807 volDef->_nodes[iN].Node()->setIsMarked( false );
5812 //================================================================================
5814 * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5815 * volume also sharing the dividing edge is missing due to its small side.
5818 //================================================================================
5820 void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
5822 if ( ! _volumeDefs.IsPolyhedron() )
5823 return; // not a polyhedron
5825 // look for a divided side adjacent to a small hexahedron
5827 int di[6] = { 0, 0, 0, 0,-1, 1 };
5828 int dj[6] = { 0, 0,-1, 1, 0, 0 };
5829 int dk[6] = {-1, 1, 0, 0, 0, 0 };
5831 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
5833 size_t neighborIndex = _grid->CellIndex( _i + di[iF],
5836 if ( neighborIndex >= allHexa.size() ||
5837 !allHexa[ neighborIndex ] ||
5838 !allHexa[ neighborIndex ]->_hasTooSmall )
5841 // check if a side is divided into several polygons
5842 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5844 int nbPolygons = 0, nbNodes = 0;
5845 for ( size_t i = 0; i < volDef->_names.size(); ++i )
5846 if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
5849 nbNodes += volDef->_quantities[ i ];
5851 if ( nbPolygons < 2 )
5854 // construct loops from polygons
5855 typedef _volumeDef::_linkDef TLinkDef;
5856 std::vector< TLinkDef* > loops;
5857 std::vector< TLinkDef > links( nbNodes );
5858 for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5860 size_t nbLinks = volDef->_quantities[ iLoop ];
5861 if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
5866 loops.push_back( & links[i] );
5867 for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
5869 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
5870 links[i].setNext( &links[i+1] );
5872 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
5873 links[i].setNext( &links[i-nbLinks+1] );
5877 // look for equal links in different loops and join such loops
5878 bool loopsJoined = false;
5879 std::set< TLinkDef > linkSet;
5880 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5883 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
5885 std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
5886 if ( !it2new.second ) // equal found, join loops
5888 const TLinkDef* equal = &(*it2new.first);
5889 if ( equal->_loopIndex == l->_loopIndex )
5894 for ( size_t i = iLoop - 1; i < loops.size(); --i )
5895 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
5898 // exclude l and equal and join two loops
5899 if ( l->_prev != equal )
5900 l->_prev->setNext( equal->_next );
5901 if ( equal->_prev != l )
5902 equal->_prev->setNext( l->_next );
5904 if ( volDef->_quantities[ l->_loopIndex ] > 0 )
5905 volDef->_quantities[ l->_loopIndex ] *= -1;
5906 if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
5907 volDef->_quantities[ equal->_loopIndex ] *= -1;
5909 if ( loops[ iLoop ] == l )
5910 loops[ iLoop ] = l->_prev->_next;
5912 beg = loops[ iLoop ];
5918 // set unchanged polygons
5919 std::vector< int > newQuantities;
5920 std::vector< _volumeDef::_nodeDef > newNodes;
5921 vector< SMESH_Block::TShapeID > newNames;
5922 newQuantities.reserve( volDef->_quantities.size() );
5923 newNodes.reserve ( volDef->_nodes.size() );
5924 newNames.reserve ( volDef->_names.size() );
5925 for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5927 if ( volDef->_quantities[ iLoop ] < 0 )
5929 i -= volDef->_quantities[ iLoop ];
5932 newQuantities.push_back( volDef->_quantities[ iLoop ]);
5933 newNodes.insert( newNodes.end(),
5934 volDef->_nodes.begin() + i,
5935 volDef->_nodes.begin() + i + newQuantities.back() );
5936 newNames.push_back( volDef->_names[ iLoop ]);
5937 i += volDef->_quantities[ iLoop ];
5941 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5943 if ( !loops[ iLoop ] )
5945 newQuantities.push_back( 0 );
5947 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
5949 newNodes.push_back( l->_node1 );
5950 beg = loops[ iLoop ];
5952 newNames.push_back( _hexQuads[ iF ]._name );
5954 volDef->_quantities.swap( newQuantities );
5955 volDef->_nodes.swap( newNodes );
5956 volDef->_names.swap( newNames );
5958 } // loop on volDef's
5959 } // loop on hex sides
5962 } // removeExcessSideDivision()
5965 //================================================================================
5967 * \brief Remove nodes splitting Cartesian cell edges in the case if a node
5968 * is used in every cells only by two polygons sharing the edge
5971 //================================================================================
5973 void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
5975 if ( ! _volumeDefs.IsPolyhedron() )
5976 return; // not a polyhedron
5978 typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
5979 vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
5980 vector< int > volDefInd [ 4 ]; // index of a _volumeDefs
5981 Hexahedron* hexa [ 4 ];
5982 int i,j,k, cellIndex, iLink = 0, iCellLink;
5983 for ( int iDir = 0; iDir < 3; ++iDir )
5985 CellsAroundLink fourCells( _grid, iDir );
5986 for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
5988 _Link& link = _hexLinks[ iLink ];
5989 fourCells.Init( _i, _j, _k, iLink );
5991 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
5993 bool nodeRemoved = true;
5994 _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
5996 for ( size_t i = 0, nb = _volumeDefs.size(); i < nb && nodeRemoved; ++i )
5997 if ( _volumeDef* vol = _volumeDefs.at( i ))
5999 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
6001 continue; // node already removed
6003 // check if a node encounters zero or two times in 4 cells sharing iLink
6004 // if so, the node can be removed from the cells
6005 bool nodeIsOnEdge = true;
6006 int nbPolyhedraWithNode = 0;
6007 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
6009 nodesInPoly[ iC ].clear();
6010 volDefInd [ iC ].clear();
6012 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
6014 hexa[ iC ] = allHexa[ cellIndex ];
6017 for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
6018 if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
6020 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
6022 nIt = std::find( nIt, vol->_nodes.end(), node );
6023 if ( nIt != vol->_nodes.end() )
6025 nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
6026 volDefInd [ iC ].push_back( i );
6031 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
6033 if ( nodesInPoly[ iC ].size() != 0 &&
6034 nodesInPoly[ iC ].size() != 2 )
6036 nodeIsOnEdge = false;
6039 } // loop on 4 cells
6041 // remove nodes from polyhedra
6042 if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
6044 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
6046 if ( nodesInPoly[ iC ].empty() )
6048 for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
6050 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
6051 int nIndex = nodesInPoly[ iC ][ i ];
6052 // decrement _quantities
6053 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
6054 if ( nIndex < vol->_quantities[ iQ ])
6056 vol->_quantities[ iQ ]--;
6061 nIndex -= vol->_quantities[ iQ ];
6063 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
6066 vol->_nodes.size() == 6 * 4 &&
6067 vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
6069 bool allQuads = true;
6070 for ( size_t iQ = 0; iQ < vol->_quantities.size() && allQuads; ++iQ )
6071 allQuads = ( vol->_quantities[ iQ ] == 4 );
6074 // set side nodes as this: bottom, top, top, ...
6075 int iTop = 0, iBot = 0; // side indices
6076 for ( int iS = 0; iS < 6; ++iS )
6078 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
6080 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
6087 std::copy( vol->_nodes.begin(),
6088 vol->_nodes.begin() + 4,
6089 vol->_nodes.begin() + 4 );
6092 std::copy( vol->_nodes.begin() + 4 * iBot,
6093 vol->_nodes.begin() + 4 * ( iBot + 1),
6094 vol->_nodes.begin() );
6097 std::copy( vol->_nodes.begin() + 4 * iTop,
6098 vol->_nodes.begin() + 4 * ( iTop + 1),
6099 vol->_nodes.begin() + 4 );
6101 std::copy( vol->_nodes.begin() + 4,
6102 vol->_nodes.begin() + 8,
6103 vol->_nodes.begin() + 8 );
6104 // set up top facet nodes by comparing their uvw with bottom nodes
6105 E_IntersectPoint ip[8];
6106 for ( int iN = 0; iN < 8; ++iN )
6108 SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
6109 _grid->ComputeUVW( p, ip[ iN ]._uvw );
6111 const double tol2 = _grid->_tol * _grid->_tol;
6112 for ( int iN = 0; iN < 4; ++iN )
6114 gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
6115 for ( int iT = 4; iT < 8; ++iT )
6117 gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
6118 if ( pBot.SquareDistance( pTop ) < tol2 )
6120 // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
6121 // vol->_nodes[ iN + 4 ]._intPoint = 0;
6122 vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
6127 vol->_nodes.resize( 8 );
6128 vol->_quantities.clear();
6129 //vol->_names.clear();
6132 } // loop on _volumeDefs
6133 } // loop on 4 cell abound a link
6134 } // if ( nodeIsOnEdge )
6135 } // loop on intersection points of a link
6136 } // loop on 4 links of a direction
6137 } // loop on 3 directions
6141 } // removeExcessNodes()
6143 //================================================================================
6145 * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
6147 //================================================================================
6149 void Hexahedron::preventVolumesOverlapping()
6151 // Cut off a quadrangle corner if two links sharing the corner
6152 // are shared by same two solids, in this case each of solids gets
6153 // a triangle for it-self.
6154 std::vector< TGeomID > soIDs[4];
6155 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6157 _Face& quad = _hexQuads[ iF ] ;
6159 int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
6160 _Face& quadOpp = _hexQuads[ iFOpposite ] ;
6162 int nbSides = 0, nbSidesOpp = 0;
6163 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
6165 nbSides += ( quad._links [ iE ].NbResultLinks() > 0 );
6166 nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
6168 if ( nbSides < 4 || nbSidesOpp != 2 )
6171 for ( int iE = 0; iE < 4; ++iE )
6173 soIDs[ iE ].clear();
6174 _Node* n = quad._links[ iE ].FirstNode();
6175 if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
6176 soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
6178 if ((( soIDs[0].size() >= 2 ) +
6179 ( soIDs[1].size() >= 2 ) +
6180 ( soIDs[2].size() >= 2 ) +
6181 ( soIDs[3].size() >= 2 ) ) < 3 )
6185 for ( int i = 0; i < 4; ++i )
6187 int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
6188 int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
6189 int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
6190 if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
6191 soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
6192 soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
6194 quad._links[ i1 ]._link->_splits.clear();
6195 quad._links[ i2 ]._link->_splits.clear();
6204 } // preventVolumesOverlapping()
6206 //================================================================================
6208 * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
6210 bool Hexahedron::_SplitIterator::Next()
6212 if ( _iterationNb > 0 )
6213 // count used splits
6214 for ( size_t i = 0; i < _splits.size(); ++i )
6216 if ( _splits[i]._iCheckIteration == _iterationNb )
6218 _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
6219 _nbUsed += _splits[i]._isUsed;
6227 bool toTestUsed = ( _nbChecked >= _splits.size() );
6230 // all splits are checked; find all not used splits
6231 for ( size_t i = 0; i < _splits.size(); ++i )
6232 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6233 _splits[i]._iCheckIteration = _iterationNb;
6235 _nbUsed = _splits.size(); // to stop iteration
6239 // get any not used/checked split to start from
6241 for ( size_t i = 0; i < _splits.size(); ++i )
6243 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6245 _freeNodes.push_back( _splits[i]._nodes[0] );
6246 _freeNodes.push_back( _splits[i]._nodes[1] );
6247 _splits[i]._iCheckIteration = _iterationNb;
6251 // find splits connected to the start one via _freeNodes
6252 for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
6254 for ( size_t iS = 0; iS < _splits.size(); ++iS )
6256 if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
6259 if ( _freeNodes[iN] == _splits[iS]._nodes[0] )
6261 else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
6265 if ( _freeNodes[iN]->_isInternalFlags > 0 )
6267 if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
6269 if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
6272 _splits[iS]._iCheckIteration = _iterationNb;
6273 _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
6277 // set splits to hex links
6279 for ( int iL = 0; iL < 12; ++iL )
6280 _hexLinks[ iL ]._splits.clear();
6283 for ( size_t i = 0; i < _splits.size(); ++i )
6285 if ( _splits[i]._iCheckIteration == _iterationNb )
6287 split._nodes[0] = _splits[i]._nodes[0];
6288 split._nodes[1] = _splits[i]._nodes[1];
6289 _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
6290 hexLink._splits.push_back( split );
6291 _splits[i]._checkedSplit = & hexLink._splits.back();
6298 //================================================================================
6300 * \brief computes exact bounding box with axes parallel to given ones
6302 //================================================================================
6304 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
6305 const double* axesDirs,
6309 TopoDS_Compound allFacesComp;
6310 b.MakeCompound( allFacesComp );
6311 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
6312 b.Add( allFacesComp, faceVec[ iF ] );
6314 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
6315 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
6317 for ( int i = 0; i < 6; ++i )
6318 farDist = Max( farDist, 10 * sP[i] );
6320 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
6321 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
6322 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
6323 axis[0].Normalize();
6324 axis[1].Normalize();
6325 axis[2].Normalize();
6327 gp_Mat basis( axis[0], axis[1], axis[2] );
6328 gp_Mat bi = basis.Inverted();
6331 for ( int iDir = 0; iDir < 3; ++iDir )
6333 gp_XYZ axis0 = axis[ iDir ];
6334 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
6335 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
6336 for ( int isMax = 0; isMax < 2; ++isMax )
6338 double shift = isMax ? farDist : -farDist;
6339 gp_XYZ orig = shift * axis0;
6340 gp_XYZ norm = axis1 ^ axis2;
6341 gp_Pln pln( orig, norm );
6342 norm = pln.Axis().Direction().XYZ();
6343 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
6345 gp_Pnt& pAxis = isMax ? pMax : pMin;
6346 gp_Pnt pPlane, pFaces;
6347 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
6352 for ( int i = 0; i < 2; ++i ) {
6353 corner.SetCoord( 1, sP[ i*3 ]);
6354 for ( int j = 0; j < 2; ++j ) {
6355 corner.SetCoord( 2, sP[ i*3 + 1 ]);
6356 for ( int k = 0; k < 2; ++k )
6358 corner.SetCoord( 3, sP[ i*3 + 2 ]);
6364 corner = isMax ? bb.CornerMax() : bb.CornerMin();
6365 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
6369 gp_XYZ pf = pFaces.XYZ() * bi;
6370 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
6376 shapeBox.Add( pMin );
6377 shapeBox.Add( pMax );
6384 //=============================================================================
6386 * \brief Generates 3D structured Cartesian mesh in the internal part of
6387 * solid shapes and polyhedral volumes near the shape boundary.
6388 * \param theMesh - mesh to fill in
6389 * \param theShape - a compound of all SOLIDs to mesh
6390 * \retval bool - true in case of success
6392 //=============================================================================
6394 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
6395 const TopoDS_Shape & theShape)
6397 if ( _hypViscousLayers )
6399 const StdMeshers_ViscousLayers* hypViscousLayers = _hypViscousLayers;
6400 _hypViscousLayers = nullptr;
6402 StdMeshers_Cartesian_VL::ViscousBuilder builder( hypViscousLayers, theMesh, theShape );
6405 TopoDS_Shape offsetShape = builder.MakeOffsetShape( theShape, theMesh, error );
6406 if ( offsetShape.IsNull() )
6407 throw SALOME_Exception( error );
6409 SMESH_Mesh* offsetMesh = builder.MakeOffsetMesh();
6411 this->_isComputeOffset = true;
6412 if ( ! this->Compute( *offsetMesh, offsetShape ))
6415 return builder.MakeViscousLayers( theMesh, theShape );
6418 // The algorithm generates the mesh in following steps:
6420 // 1) Intersection of grid lines with the geometry boundary.
6421 // This step allows to find out if a given node of the initial grid is
6422 // inside or outside the geometry.
6424 // 2) For each cell of the grid, check how many of it's nodes are outside
6425 // of the geometry boundary. Depending on a result of this check
6426 // - skip a cell, if all it's nodes are outside
6427 // - skip a cell, if it is too small according to the size threshold
6428 // - add a hexahedron in the mesh, if all nodes are inside
6429 // - add a polyhedron in the mesh, if some nodes are inside and some outside
6431 _computeCanceled = false;
6433 SMESH_MesherHelper helper( theMesh );
6434 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
6439 grid._helper = &helper;
6440 grid._toAddEdges = _hyp->GetToAddEdges();
6441 grid._toCreateFaces = _hyp->GetToCreateFaces();
6442 grid._toConsiderInternalFaces = _hyp->GetToConsiderInternalFaces();
6443 grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
6444 grid._sizeThreshold = _hyp->GetSizeThreshold();
6445 if ( _isComputeOffset )
6447 grid._toAddEdges = true;
6448 grid._toCreateFaces = true;
6450 grid.InitGeometry( theShape );
6452 vector< TopoDS_Shape > faceVec;
6454 TopTools_MapOfShape faceMap;
6455 TopExp_Explorer fExp;
6456 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
6458 bool isNewFace = faceMap.Add( fExp.Current() );
6459 if ( !grid._toConsiderInternalFaces )
6460 if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
6461 // remove an internal face
6462 faceMap.Remove( fExp.Current() );
6464 faceVec.reserve( faceMap.Extent() );
6465 faceVec.assign( faceMap.cbegin(), faceMap.cend() );
6467 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
6469 for ( size_t i = 0; i < faceVec.size(); ++i )
6471 facesItersectors[i]._face = TopoDS::Face( faceVec[i] );
6472 facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
6473 facesItersectors[i]._grid = &grid;
6474 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
6476 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
6479 vector<double> xCoords, yCoords, zCoords;
6480 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
6482 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
6484 if ( _computeCanceled ) return false;
6487 { // copy partner faces and curves of not thread-safe types
6488 set< const Standard_Transient* > tshapes;
6489 BRepBuilderAPI_Copy copier;
6490 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6492 if ( !facesItersectors[i].IsThreadSafe( tshapes ))
6494 copier.Perform( facesItersectors[i]._face );
6495 facesItersectors[i]._face = TopoDS::Face( copier );
6499 // Intersection of grid lines with the geometry boundary.
6500 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
6501 ParallelIntersector( facesItersectors ),
6502 tbb::simple_partitioner());
6504 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6505 facesItersectors[i].Intersect();
6508 // put intersection points onto the GridLine's; this is done after intersection
6509 // to avoid contention of facesItersectors for writing into the same GridLine
6510 // in case of parallel work of facesItersectors
6511 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6512 facesItersectors[i].StoreIntersections();
6514 if ( _computeCanceled ) return false;
6516 // create nodes on the geometry
6517 grid.ComputeNodes( helper );
6519 if ( _computeCanceled ) return false;
6521 // get EDGEs to take into account
6522 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
6523 grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
6525 // create volume elements
6526 Hexahedron hex( &grid );
6527 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
6531 if ( !grid._toConsiderInternalFaces )
6533 // make all SOLIDs computed
6534 TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
6535 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
6537 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
6538 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
6540 const SMDS_MeshElement* vol = volIt->next();
6541 sm1->RemoveElement( vol );
6542 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
6546 // make other sub-shapes computed
6547 setSubmeshesComputed( theMesh, theShape );
6550 // remove free nodes
6551 //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
6553 std::vector< const SMDS_MeshNode* > nodesToRemove;
6554 // get intersection nodes
6555 for ( int iDir = 0; iDir < 3; ++iDir )
6557 vector< GridLine >& lines = grid._lines[ iDir ];
6558 for ( size_t i = 0; i < lines.size(); ++i )
6560 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
6561 for ( ; ip != lines[i]._intPoints.end(); ++ip )
6563 !ip->_node->IsNull() &&
6564 ip->_node->NbInverseElements() == 0 &&
6565 !ip->_node->isMarked() )
6567 nodesToRemove.push_back( ip->_node );
6568 ip->_node->setIsMarked( true );
6573 for ( size_t i = 0; i < grid._nodes.size(); ++i )
6574 if ( grid._nodes[i] &&
6575 !grid._nodes[i]->IsNull() &&
6576 grid._nodes[i]->NbInverseElements() == 0 &&
6577 !grid._nodes[i]->isMarked() )
6579 nodesToRemove.push_back( grid._nodes[i] );
6580 grid._nodes[i]->setIsMarked( true );
6584 for ( size_t i = 0; i < nodesToRemove.size(); ++i )
6585 meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
6591 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
6592 catch ( SMESH_ComputeError& e)
6594 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
6599 //=============================================================================
6603 //=============================================================================
6605 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & /*theMesh*/,
6606 const TopoDS_Shape & /*theShape*/,
6607 MapShapeNbElems& /*theResMap*/)
6610 // std::vector<int> aResVec(SMDSEntity_Last);
6611 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
6612 // if(IsQuadratic) {
6613 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6614 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
6615 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
6618 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
6619 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6621 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
6622 // aResMap.insert(std::make_pair(sm,aResVec));
6627 //=============================================================================
6631 * \brief Event listener setting/unsetting _alwaysComputed flag to
6632 * submeshes of inferior levels to prevent their computing
6634 struct _EventListener : public SMESH_subMeshEventListener
6638 _EventListener(const string& algoName):
6639 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
6642 // --------------------------------------------------------------------------------
6643 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
6645 static void setAlwaysComputed( const bool isComputed,
6646 SMESH_subMesh* subMeshOfSolid)
6648 SMESH_subMeshIteratorPtr smIt =
6649 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
6650 while ( smIt->more() )
6652 SMESH_subMesh* sm = smIt->next();
6653 sm->SetIsAlwaysComputed( isComputed );
6655 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
6658 // --------------------------------------------------------------------------------
6659 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
6661 virtual void ProcessEvent(const int /*event*/,
6662 const int eventType,
6663 SMESH_subMesh* subMeshOfSolid,
6664 SMESH_subMeshEventListenerData* /*data*/,
6665 const SMESH_Hypothesis* /*hyp*/ = 0)
6667 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
6669 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
6674 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
6675 if ( !algo3D || _algoName != algo3D->GetName() )
6676 setAlwaysComputed( false, subMeshOfSolid );
6680 // --------------------------------------------------------------------------------
6681 // set the event listener
6683 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
6685 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6690 }; // struct _EventListener
6694 //================================================================================
6696 * \brief Sets event listener to submeshes if necessary
6697 * \param subMesh - submesh where algo is set
6698 * This method is called when a submesh gets HYP_OK algo_state.
6699 * After being set, event listener is notified on each event of a submesh.
6701 //================================================================================
6703 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6705 _EventListener::SetOn( subMesh, GetName() );
6708 //================================================================================
6710 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6712 //================================================================================
6714 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
6715 const TopoDS_Shape& theShape)
6717 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6718 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));