Salome HOME
7a172ddd66d651e9c8397a419bd202e51628a4b2
[modules/smesh.git] / src / StdMeshers / StdMeshers_Cartesian_3D.cxx
1 // Copyright (C) 2007-2024  CEA, EDF, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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.
10 //
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.
15 //
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
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  File   : StdMeshers_Cartesian_3D.cxx
23 //  Module : SMESH
24 //
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"
30
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>
46
47 #include <utilities.h>
48 #include <Utils_ExceptHandlers.hxx>
49
50 #include <GEOMUtils.hxx>
51
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>
63 #include <ElSLib.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>
83 #include <TopExp.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>
89 #include <TopoDS.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>
95 #include <gp_Lin.hxx>
96 #include <gp_Pln.hxx>
97 #include <gp_Pnt2d.hxx>
98 #include <gp_Sphere.hxx>
99 #include <gp_Torus.hxx>
100
101 #include <limits>
102
103 #include <boost/container/flat_map.hpp>
104
105 #ifdef _DEBUG_
106 //  #define _MY_DEBUG_
107 //  #undef WITH_TBB
108 #endif
109
110 #ifdef WITH_TBB
111
112 #ifdef WIN32
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
117 #endif
118
119 #include <tbb/parallel_for.h>
120 //#include <tbb/enumerable_thread_specific.h>
121 #endif
122
123 using namespace std;
124 using namespace SMESH;
125
126 //=============================================================================
127 /*!
128  * Constructor
129  */
130 //=============================================================================
131
132 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
133   :SMESH_3D_Algo(hypId, gen)
134 {
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() );
139
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
143 }
144
145 //=============================================================================
146 /*!
147  * Check presence of a hypothesis
148  */
149 //=============================================================================
150
151 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh&          aMesh,
152                                                const TopoDS_Shape&  aShape,
153                                                Hypothesis_Status&   aStatus)
154 {
155   aStatus = SMESH_Hypothesis::HYP_MISSING;
156
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())
160   {
161     return false;
162   }
163
164   _hyp = nullptr;
165   _hypViscousLayers = nullptr;
166   _isComputeOffset = false;
167
168   for ( ; h != hyps.end(); ++h )
169   {
170     if ( !_hyp && ( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
171     {
172       aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
173     }
174     else
175     {
176       _hypViscousLayers = dynamic_cast<const StdMeshers_ViscousLayers*>( *h );
177     }
178   }
179
180   return aStatus == HYP_OK;
181 }
182
183 namespace
184 {
185   /*!
186    * \brief Temporary mesh to hold 
187    */
188   struct TmpMesh: public SMESH_Mesh
189   {
190     TmpMesh() {
191       _isShapeToMesh = (_id = 0);
192       _meshDS  = new SMESHDS_Mesh( _id, true );
193     }
194   };
195
196   typedef int                     TGeomID; // IDs of sub-shapes
197   typedef TopTools_ShapeMapHasher TShapeHasher; // non-oriented shape hasher
198   typedef std::array< int, 3 >    TIJK;
199
200   const TGeomID theUndefID = 1e+9;
201
202   //=============================================================================
203   // Definitions of internal utils
204   // --------------------------------------------------------------------------
205   enum Transition {
206     Trans_TANGENT = IntCurveSurface_Tangent,
207     Trans_IN      = IntCurveSurface_In,
208     Trans_OUT     = IntCurveSurface_Out,
209     Trans_APEX,
210     Trans_INTERNAL // for INTERNAL FACE
211   };
212   // --------------------------------------------------------------------------
213   /*!
214    * \brief Sub-entities of a FACE neighboring its concave VERTEX.
215    *        Help to avoid linking nodes on EDGEs that seem connected
216    *        by the concave FACE but the link actually lies outside the FACE
217    */
218   struct ConcaveFace
219   {
220     TGeomID _concaveFace;
221     TGeomID _edge1, _edge2;
222     TGeomID _v1,    _v2;
223     ConcaveFace( int f=0, int e1=0, int e2=0, int v1=0, int v2=0 )
224       : _concaveFace(f), _edge1(e1), _edge2(e2), _v1(v1), _v2(v2) {}
225     bool HasEdge( TGeomID edge ) const { return edge == _edge1 || edge == _edge2; }
226     bool HasVertex( TGeomID v  ) const { return v == _v1 || v == _v2; }
227     void SetEdge( TGeomID edge ) { ( _edge1 ? _edge2 : _edge1 ) = edge; }
228     void SetVertex( TGeomID v  ) { ( _v1 ? _v2 : _v1 ) = v; }
229   };
230   typedef NCollection_DataMap< TGeomID, ConcaveFace > TConcaveVertex2Face;
231   // --------------------------------------------------------------------------
232   /*!
233    * \brief Container of IDs of SOLID sub-shapes
234    */
235   class Solid // sole SOLID contains all sub-shapes
236   {
237     TGeomID             _id; // SOLID id
238     bool                _hasInternalFaces;
239     TConcaveVertex2Face _concaveVertex; // concave VERTEX -> ConcaveFace
240   public:
241     virtual ~Solid() {}
242     virtual bool Contains( TGeomID /*subID*/ ) const { return true; }
243     virtual bool ContainsAny( const vector< TGeomID>& /*subIDs*/ ) const { return true; }
244     virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
245     virtual bool IsOutsideOriented( TGeomID /*faceID*/ ) const { return true; }
246     void SetID( TGeomID id ) { _id = id; }
247     TGeomID ID() const { return _id; }
248     void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
249     bool HasInternalFaces() const { return _hasInternalFaces; }
250     void SetConcave( TGeomID V, TGeomID F, TGeomID E1, TGeomID E2, TGeomID V1, TGeomID V2  )
251     { _concaveVertex.Bind( V, ConcaveFace{ F, E1, E2, V1, V2 }); }
252     bool HasConcaveVertex() const { return !_concaveVertex.IsEmpty(); }
253     const ConcaveFace* GetConcave( TGeomID V ) const { return _concaveVertex.Seek( V ); }
254   };
255   // --------------------------------------------------------------------------
256   class OneOfSolids : public Solid
257   {
258     TColStd_MapOfInteger _subIDs;
259     TopTools_MapOfShape  _faces; // keep FACE orientation
260     TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
261   public:
262     void Init( const TopoDS_Shape& solid,
263                TopAbs_ShapeEnum    subType,
264                const SMESHDS_Mesh* mesh );
265     virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
266     virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
267     {
268       for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
269       return false;
270     }
271     virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
272     {
273       const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
274       return sInMap.Orientation();
275     }
276     virtual bool IsOutsideOriented( TGeomID faceID ) const
277     {
278       return faceID == 0 || _outFaceIDs.Contains( faceID );
279     }
280   };
281   // --------------------------------------------------------------------------
282   /*!
283    * \brief Hold a vector of TGeomID and clear it at destruction
284    */
285   class GeomIDVecHelder
286   {
287     typedef std::vector< TGeomID > TVector;
288     const TVector& myVec;
289     bool           myOwn;
290
291   public:
292     GeomIDVecHelder( const TVector& idVec, bool isOwner ): myVec( idVec ), myOwn( isOwner ) {}
293     GeomIDVecHelder( const GeomIDVecHelder& holder ): myVec( holder.myVec ), myOwn( holder.myOwn )
294     {
295       const_cast< bool& >( holder.myOwn ) = false;
296     }
297     ~GeomIDVecHelder() { if ( myOwn ) const_cast<TVector&>( myVec ).clear(); }
298     size_t size() const { return myVec.size(); }
299     TGeomID operator[]( size_t i ) const { return i < size() ? myVec[i] : theUndefID; }
300     bool operator==( const GeomIDVecHelder& other ) const { return myVec == other.myVec; }
301     bool contain( const TGeomID& id ) const {
302       return std::find( myVec.begin(), myVec.end(), id ) != myVec.end();
303     }
304     TGeomID otherThan( const TGeomID& id ) const {
305       for ( const TGeomID& id2 : myVec )
306         if ( id != id2 )
307           return id2;
308       return theUndefID;
309     }
310     TGeomID oneCommon( const GeomIDVecHelder& other ) const {
311       TGeomID common = theUndefID;
312       for ( const TGeomID& id : myVec )
313         if ( other.contain( id ))
314         {
315           if ( common != theUndefID )
316             return theUndefID;
317           common = id;
318         }
319       return common;
320     }
321   };
322   // --------------------------------------------------------------------------
323   /*!
324    * \brief Geom data
325    */
326   struct Geometry
327   {
328     TopoDS_Shape                _mainShape;
329     vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
330     Solid                       _soleSolid;
331     map< TGeomID, OneOfSolids > _solidByID;
332     TColStd_MapOfInteger        _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
333     TColStd_MapOfInteger        _strangeEdges; // EDGEs shared by strange FACEs
334     TGeomID                     _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
335
336     TopTools_DataMapOfShapeInteger _shape2NbNodes; // nb of pre-existing nodes on shapes
337
338     Controls::ElementsOnShape _edgeClassifier;
339     Controls::ElementsOnShape _vertexClassifier;
340
341     bool IsOneSolid() const { return _solidByID.size() < 2; }
342     GeomIDVecHelder GetSolidIDsByShapeID( const vector< TGeomID >& shapeIDs ) const;
343   };
344   // --------------------------------------------------------------------------
345   /*!
346    * \brief Common data of any intersection between a Grid and a shape
347    */
348   struct B_IntersectPoint
349   {
350     mutable const SMDS_MeshNode* _node;
351     mutable vector< TGeomID >    _faceIDs;
352
353     B_IntersectPoint(): _node(NULL) {}
354     bool Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
355     TGeomID HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace=-1 ) const;
356     size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID * commonFaces ) const;
357     bool IsOnFace( TGeomID faceID ) const;
358     virtual ~B_IntersectPoint() {}
359   };
360   // --------------------------------------------------------------------------
361   /*!
362    * \brief Data of intersection between a GridLine and a TopoDS_Face
363    */
364   struct F_IntersectPoint : public B_IntersectPoint
365   {
366     double             _paramOnLine;
367     double             _u, _v;
368     mutable Transition _transition;
369     mutable size_t     _indexOnLine;
370
371     bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
372   };
373   // --------------------------------------------------------------------------
374   /*!
375    * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
376    */
377   struct E_IntersectPoint : public B_IntersectPoint
378   {
379     gp_Pnt  _point;
380     double  _uvw[3];
381     TGeomID _shapeID; // ID of EDGE or VERTEX
382   };
383   // --------------------------------------------------------------------------
384   /*!
385    * \brief A line of the grid and its intersections with 2D geometry
386    */
387   struct GridLine
388   {
389     gp_Lin _line;
390     double _length; // line length
391     multiset< F_IntersectPoint > _intPoints;
392
393     void RemoveExcessIntPoints( const double tol );
394     TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
395                               const TGeomID                          prevID,
396                               const Geometry&                        geom);
397   };
398   // --------------------------------------------------------------------------
399   /*!
400    * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
401    */
402   struct GridPlanes
403   {
404     gp_XYZ           _zNorm;
405     vector< gp_XYZ > _origins; // origin points of all planes in one direction
406     vector< double > _zProjs;  // projections of origins to _zNorm
407   };
408   // --------------------------------------------------------------------------
409   /*!
410    * \brief Iterator on the parallel grid lines of one direction
411    */
412   struct LineIndexer
413   {
414     size_t _size  [3];
415     size_t _curInd[3];
416     size_t _iVar1, _iVar2, _iConst;
417     string _name1, _name2, _nameConst;
418     LineIndexer() {}
419     LineIndexer( size_t sz1, size_t sz2, size_t sz3,
420                  size_t iv1, size_t iv2, size_t iConst,
421                  const string& nv1, const string& nv2, const string& nConst )
422     {
423       _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
424       _curInd[0] = _curInd[1] = _curInd[2] = 0;
425       _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
426       _name1 = nv1; _name2 = nv2; _nameConst = nConst;
427     }
428
429     size_t I() const { return _curInd[0]; }
430     size_t J() const { return _curInd[1]; }
431     size_t K() const { return _curInd[2]; }
432     void SetIJK( size_t i, size_t j, size_t k )
433     {
434       _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
435     }
436     void SetLineIndex(size_t i)
437     {
438       _curInd[_iVar2] = i / _size[_iVar1];
439       _curInd[_iVar1] = i % _size[_iVar1];
440     }
441     void operator++()
442     {
443       if ( ++_curInd[_iVar1] == _size[_iVar1] )
444         _curInd[_iVar1] = 0, ++_curInd[_iVar2];
445     }
446     bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
447     size_t LineIndex   () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
448     size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
449     size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
450     size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
451     void SetIndexOnLine (size_t i)  { _curInd[ _iConst ] = i; }
452     bool IsValidIndexOnLine (size_t i) const { return  i < _size[ _iConst ]; }
453     size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
454   };
455   struct FaceGridIntersector;
456   // --------------------------------------------------------------------------
457   /*!
458    * \brief Container of GridLine's
459    */
460   struct Grid
461   {
462     vector< double >   _coords[3]; // coordinates of grid nodes
463     gp_XYZ             _axes  [3]; // axis directions
464     vector< GridLine > _lines [3]; //    in 3 directions
465     double             _tol, _minCellSize;
466     gp_XYZ             _origin;
467     gp_Mat             _invB; // inverted basis of _axes
468
469     // index shift within _nodes of nodes of a cell from the 1st node
470     int                _nodeShift[8];
471
472     vector< const SMDS_MeshNode* >    _nodes; // mesh nodes at grid nodes
473     vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
474     ObjectPool< E_IntersectPoint >    _edgeIntPool; // intersections with EDGEs
475     ObjectPool< F_IntersectPoint >    _extIntPool; // intersections with extended INTERNAL FACEs
476     //list< E_IntersectPoint >          _edgeIntP; // intersections with EDGEs
477
478     Geometry                          _geometry;
479     bool                              _toAddEdges;
480     bool                              _toCreateFaces;
481     bool                              _toConsiderInternalFaces;
482     bool                              _toUseThresholdForInternalFaces;
483     double                            _sizeThreshold;
484
485     SMESH_MesherHelper*               _helper;
486
487     size_t CellIndex( size_t i, size_t j, size_t k ) const
488     {
489       return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
490     }
491     size_t NodeIndex( size_t i, size_t j, size_t k ) const
492     {
493       return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
494     }
495     size_t NodeIndex( const TIJK& ijk ) const
496     {
497       return NodeIndex( ijk[0], ijk[1], ijk[2] );
498     }
499     size_t NodeIndexDX() const { return 1; }
500     size_t NodeIndexDY() const { return _coords[0].size(); }
501     size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
502
503     LineIndexer GetLineIndexer(size_t iDir) const;
504     size_t GetLineDir( const GridLine* line, size_t & index ) const;
505
506     E_IntersectPoint* Add( const E_IntersectPoint& ip )
507     {
508       E_IntersectPoint* eip = _edgeIntPool.getNew();
509       *eip = ip;
510       return eip;
511     }
512     void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
513
514     TGeomID ShapeID( const TopoDS_Shape& s ) const;
515     const TopoDS_Shape& Shape( TGeomID id ) const;
516     TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
517     void InitGeometry( const TopoDS_Shape& theShape );
518     void InitClassifier( const TopoDS_Shape&        mainShape,
519                          TopAbs_ShapeEnum           shapeType,
520                          Controls::ElementsOnShape& classifier );
521     void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
522                               const TopoDS_Shape&                 shape,
523                               const vector< TopoDS_Shape >&       faces );
524     void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
525     bool IsShared( TGeomID faceID ) const;
526     bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
527     bool IsInternal( TGeomID faceID ) const {
528       return ( faceID == PseudoIntExtFaceID() ||
529                Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
530     bool IsSolid( TGeomID shapeID ) const {
531       if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
532       else                          return _geometry._solidByID.count( shapeID ); }
533     bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
534     TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
535     Solid* GetSolid( TGeomID solidID = 0 );
536     Solid* GetOneOfSolids( TGeomID solidID );
537     const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
538     bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
539     bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
540     void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
541                      TopoDS_Vertex* vertex = nullptr, bool unset = false );
542     void UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex );
543     bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
544     bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
545
546     void SetCoordinates(const vector<double>& xCoords,
547                         const vector<double>& yCoords,
548                         const vector<double>& zCoords,
549                         const double*         axesDirs,
550                         const Bnd_Box&        bndBox );
551     void ComputeUVW(const gp_XYZ& p, double uvw[3]);
552     void ComputeNodes(SMESH_MesherHelper& helper);
553   };
554   // --------------------------------------------------------------------------
555   /*!
556    * \brief Return cells sharing a link
557    */
558   struct CellsAroundLink
559   {
560     int    _iDir;
561     int    _dInd[4][3];
562     size_t _nbCells[3];
563     int    _i,_j,_k;
564     Grid*  _grid;
565
566     CellsAroundLink( Grid* grid, int iDir ):
567       _iDir( iDir ),
568       _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
569       _nbCells{ grid->_coords[0].size() - 1,
570           grid->_coords[1].size() - 1,
571           grid->_coords[2].size() - 1 },
572       _grid( grid )
573     {
574       const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
575       _dInd[1][ iDirOther[iDir][0] ] = -1;
576       _dInd[2][ iDirOther[iDir][1] ] = -1;
577       _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
578     }
579     void Init( int i, int j, int k, int link12 = 0 )
580     {
581       int iL = link12 % 4;
582       _i = i - _dInd[iL][0];
583       _j = j - _dInd[iL][1];
584       _k = k - _dInd[iL][2];
585     }
586     bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
587     {
588       i =  _i + _dInd[iL][0];
589       j =  _j + _dInd[iL][1];
590       k =  _k + _dInd[iL][2];
591       if ( i < 0 || i >= (int)_nbCells[0] ||
592            j < 0 || j >= (int)_nbCells[1] ||
593            k < 0 || k >= (int)_nbCells[2] )
594         return false;
595       cellIndex = _grid->CellIndex( i,j,k );
596       linkIndex = iL + _iDir * 4;
597       return true;
598     }
599   };
600   // --------------------------------------------------------------------------
601   /*!
602    * \brief Intersector of TopoDS_Face with all GridLine's
603    */
604   struct FaceGridIntersector
605   {
606     TopoDS_Face _face;
607     TGeomID     _faceID;
608     Grid*       _grid;
609     Bnd_Box     _bndBox;
610     IntCurvesFace_Intersector* _surfaceInt;
611     vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
612
613     FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
614     void Intersect();
615
616     void StoreIntersections()
617     {
618       for ( size_t i = 0; i < _intersections.size(); ++i )
619       {
620         multiset< F_IntersectPoint >::iterator ip =
621           _intersections[i].first->_intPoints.insert( _intersections[i].second );
622         ip->_faceIDs.reserve( 1 );
623         ip->_faceIDs.push_back( _faceID );
624       }
625     }
626     const Bnd_Box& GetFaceBndBox()
627     {
628       GetCurveFaceIntersector();
629       return _bndBox;
630     }
631     IntCurvesFace_Intersector* GetCurveFaceIntersector()
632     {
633       if ( !_surfaceInt )
634       {
635         _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
636         _bndBox     = _surfaceInt->Bounding();
637         if ( _bndBox.IsVoid() )
638           BRepBndLib::Add (_face, _bndBox);
639       }
640       return _surfaceInt;
641     }
642     bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
643   };
644   // --------------------------------------------------------------------------
645   /*!
646    * \brief Intersector of a surface with a GridLine
647    */
648   struct FaceLineIntersector
649   {
650     double      _tol;
651     double      _u, _v, _w; // params on the face and the line
652     Transition  _transition; // transition at intersection (see IntCurveSurface.cdl)
653     Transition  _transIn, _transOut; // IN and OUT transitions depending of face orientation
654
655     gp_Pln      _plane;
656     gp_Cylinder _cylinder;
657     gp_Cone     _cone;
658     gp_Sphere   _sphere;
659     gp_Torus    _torus;
660     IntCurvesFace_Intersector* _surfaceInt;
661
662     vector< F_IntersectPoint > _intPoints;
663
664     void IntersectWithPlane   (const GridLine& gridLine);
665     void IntersectWithCylinder(const GridLine& gridLine);
666     void IntersectWithCone    (const GridLine& gridLine);
667     void IntersectWithSphere  (const GridLine& gridLine);
668     void IntersectWithTorus   (const GridLine& gridLine);
669     void IntersectWithSurface (const GridLine& gridLine);
670
671     bool UVIsOnFace() const;
672     void addIntPoint(const bool toClassify=true);
673     bool isParamOnLineOK( const double linLength )
674     {
675       return -_tol < _w && _w < linLength + _tol;
676     }
677     FaceLineIntersector():_surfaceInt(0) {}
678     ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
679   };
680   // --------------------------------------------------------------------------
681   /*!
682    * \brief Class representing topology of the hexahedron and creating a mesh
683    *        volume basing on analysis of hexahedron intersection with geometry
684    */
685   class Hexahedron
686   {
687     // --------------------------------------------------------------------------------
688     struct _Face;
689     struct _Link;
690     enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
691     // --------------------------------------------------------------------------------
692     struct _Node //!< node either at a hexahedron corner or at intersection
693     {
694       const SMDS_MeshNode*    _node; // mesh node at hexahedron corner
695       const B_IntersectPoint* _intPoint;
696       const _Face*            _usedInFace;
697       char                    _isInternalFlags;
698
699       _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
700         :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {} 
701       const SMDS_MeshNode*    Node() const
702       { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
703       const E_IntersectPoint* EdgeIntPnt() const
704       { return static_cast< const E_IntersectPoint* >( _intPoint ); }
705       const F_IntersectPoint* FaceIntPnt() const
706       { return static_cast< const F_IntersectPoint* >( _intPoint ); }
707       const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
708       TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
709       void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
710       bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
711       bool IsUsedInFace( const _Face* polygon = 0 )
712       {
713         return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
714       }
715       TGeomID IsLinked( const B_IntersectPoint* other,
716                         TGeomID                 avoidFace=-1 ) const // returns id of a common face
717       {
718         return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
719       }
720       bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
721       {
722         return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
723       }
724       size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
725       {
726         return _intPoint && other ? _intPoint->GetCommonFaces( other, common ) : 0;
727       }
728       gp_Pnt Point() const
729       {
730         if ( const SMDS_MeshNode* n = Node() )
731           return SMESH_NodeXYZ( n );
732         if ( const E_IntersectPoint* eip =
733              dynamic_cast< const E_IntersectPoint* >( _intPoint ))
734           return eip->_point;
735         return gp_Pnt( 1e100, 0, 0 );
736       }
737       TGeomID ShapeID() const
738       {
739         if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
740           return eip->_shapeID;
741         return 0;
742       }
743       void Add( const E_IntersectPoint* ip )
744       {
745         // Possible cases before Add(ip):
746         ///  1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
747         ///  2) _node == 0 && _intPoint._node != 0  -->  link intersected by FACE
748         ///  3) _node == 0 && _intPoint._node == 0  -->  _Node at EDGE intersection
749         //
750         // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
751         //   at creation of elements
752         // To recognize this case, set _intPoint._node = Node()
753         const SMDS_MeshNode* node = Node();
754         if ( !_intPoint ) {
755           _intPoint = ip;
756         }
757         else {
758           ip->Add( _intPoint->_faceIDs );
759           _intPoint = ip;
760         }
761         if ( node )
762           _node = _intPoint->_node = node;
763       }
764     };
765     // --------------------------------------------------------------------------------
766     struct _Link // link connecting two _Node's
767     {
768       _Node* _nodes[2];
769       _Face* _faces[2]; // polygons sharing a link
770       vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
771       vector< _Node* >                  _fIntNodes;   // _Node's at _fIntPoints
772       vector< _Link >                   _splits;
773       _Link(): _faces{ 0, 0 } {}
774     };
775     // --------------------------------------------------------------------------------
776     struct _OrientedLink
777     {
778       _Link* _link;
779       bool   _reverse;
780       _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
781       void Reverse() { _reverse = !_reverse; }
782       size_t NbResultLinks() const { return _link->_splits.size(); }
783       _OrientedLink ResultLink(int i) const
784       {
785         return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
786       }
787       _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
788       _Node* LastNode()  const { return _link->_nodes[ !_reverse ]; }
789       operator bool() const { return _link; }
790       vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
791       {
792         vector< TGeomID > faces;
793         const B_IntersectPoint *ip0, *ip1;
794         if (( ip0 = _link->_nodes[0]->_intPoint ) &&
795             ( ip1 = _link->_nodes[1]->_intPoint ))
796         {
797           for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
798             if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
799                  !usedIDs.count( ip0->_faceIDs[i] ) )
800               faces.push_back( ip0->_faceIDs[i] );
801         }
802         return faces;
803       }
804       bool HasEdgeNodes() const
805       {
806         return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
807                  dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
808       }
809       int NbFaces() const
810       {
811         return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
812       }
813       void AddFace( _Face* f )
814       {
815         if ( _link->_faces[0] )
816         {
817           _link->_faces[1] = f;
818         }
819         else
820         {
821           _link->_faces[0] = f;
822           _link->_faces[1] = 0;
823         }
824       }
825       void RemoveFace( _Face* f )
826       {
827         if ( !_link->_faces[0] ) return;
828
829         if ( _link->_faces[1] == f )
830         {
831           _link->_faces[1] = 0;
832         }
833         else if ( _link->_faces[0] == f )
834         {
835           _link->_faces[0] = 0;
836           if ( _link->_faces[1] )
837           {
838             _link->_faces[0] = _link->_faces[1];
839             _link->_faces[1] = 0;
840           }
841         }
842       }
843     };
844     // --------------------------------------------------------------------------------
845     struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
846     {
847       struct _Split // data of a link split
848       {
849         int    _linkID;          // hex link ID
850         _Node* _nodes[2];
851         int    _iCheckIteration; // iteration where split is tried as Hexahedron split
852         _Link* _checkedSplit;    // split set to hex links
853         bool   _isUsed;          // used in a volume
854
855         _Split( _Link & split, int iLink ):
856           _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
857           _iCheckIteration( 0 ), _isUsed( false )
858         {}
859         bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
860       };
861       _Link*                _hexLinks;
862       std::vector< _Split > _splits;
863       int                   _iterationNb;
864       size_t                _nbChecked;
865       size_t                _nbUsed;
866       std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
867
868       _SplitIterator( _Link* hexLinks ):
869         _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
870       {
871         _freeNodes.reserve( 12 );
872         _splits.reserve( 24 );
873         for ( int iL = 0; iL < 12; ++iL )
874           for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
875             _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
876         Next();
877       }
878       bool More() const { return _nbUsed < _splits.size(); }
879       bool Next();
880     };
881     // --------------------------------------------------------------------------------
882     struct _Face
883     {
884       SMESH_Block::TShapeID   _name;
885       vector< _OrientedLink > _links;       // links on GridLine's
886       vector< _Link >         _polyLinks;   // links added to close a polygonal face
887       vector< _Node* >        _eIntNodes;   // nodes at intersection with EDGEs
888
889       _Face():_name( SMESH_Block::ID_NONE )
890       {}
891       bool IsPolyLink( const _OrientedLink& ol )
892       {
893         return _polyLinks.empty() ? false :
894           ( &_polyLinks[0] <= ol._link &&  ol._link <= &_polyLinks.back() );
895       }
896       void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
897       {
898         if ( faceToFindEqual && faceToFindEqual != this ) {
899           for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
900             if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
901                  faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
902             {
903               _links.push_back
904                 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
905               return;
906             }
907         }
908         _Link l;
909         l._nodes[0] = n0;
910         l._nodes[1] = n1;
911         _polyLinks.push_back( l );
912         _links.push_back( _OrientedLink( &_polyLinks.back() ));
913       }
914     };
915     // --------------------------------------------------------------------------------
916     struct _volumeDef // holder of nodes of a volume mesh element
917     {
918       typedef void* _ptr;
919
920       struct _nodeDef
921       {
922         const SMDS_MeshNode*    _node; // mesh node at hexahedron corner
923         const B_IntersectPoint* _intPoint;
924
925         _nodeDef(): _node(0), _intPoint(0) {}
926         _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
927         const SMDS_MeshNode*    Node() const
928         { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
929         const E_IntersectPoint* EdgeIntPnt() const
930         { return static_cast< const E_IntersectPoint* >( _intPoint ); }
931         _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
932         bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
933       };
934
935       vector< _nodeDef >      _nodes;
936       vector< int >           _quantities;
937       _volumeDef*             _next; // to store several _volumeDefs in a chain
938       TGeomID                 _solidID;
939       double                  _size;
940       const SMDS_MeshElement* _volume; // new volume
941       std::vector<const SMDS_MeshElement*> _brotherVolume; // produced due to poly split 
942
943       vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
944
945       _volumeDef(): _next(0), _solidID(0), _size(0), _volume(0) {}
946       ~_volumeDef() { delete _next; }
947       _volumeDef( _volumeDef& other ):
948         _next(0), _solidID( other._solidID ), _size( other._size ), _volume( other._volume )
949       { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
950         _names.swap( other._names ); }
951
952       size_t size() const { return 1 + ( _next ? _next->size() : 0 ); } // nb _volumeDef in a chain
953       _volumeDef* at(int index)
954       { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
955
956       void Set( _Node** nodes, int nb )
957       { _nodes.assign( nodes, nodes + nb ); }
958
959       void SetNext( _volumeDef* vd )
960       { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
961
962       bool IsEmpty() const { return (( _nodes.empty() ) &&
963                                      ( !_next || _next->IsEmpty() )); }
964       bool IsPolyhedron() const { return ( !_quantities.empty() ||
965                                            ( _next && !_next->_quantities.empty() )); }
966
967
968       struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
969       {
970         _nodeDef _node1;//, _node2;
971         mutable /*const */_linkDef *_prev, *_next;
972         size_t _loopIndex;
973
974         _linkDef():_prev(0), _next(0) {}
975
976         void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
977         {
978           _node1     = n1; //_node2 = n2;
979           _loopIndex = iLoop;
980           first      = n1.Ptr();
981           second     = n2.Ptr();
982           if ( first > second ) std::swap( first, second );
983         }
984         void setNext( _linkDef* next )
985         {
986           _next = next;
987           next->_prev = this;
988         }
989       };
990     };
991
992     // topology of a hexahedron
993     _Node _hexNodes [8];
994     _Link _hexLinks [12];
995     _Face _hexQuads [6];
996
997     // faces resulted from hexahedron intersection
998     vector< _Face > _polygons;
999
1000     // intresections with EDGEs
1001     vector< const E_IntersectPoint* > _eIntPoints;
1002
1003     // additional nodes created at intersection points
1004     vector< _Node > _intNodes;
1005
1006     // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
1007     vector< _Node* > _vIntNodes;
1008
1009     // computed volume elements
1010     _volumeDef _volumeDefs;
1011
1012     Grid*       _grid;
1013     double      _sideLength[3];
1014     int         _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
1015     int         _origNodeInd; // index of _hexNodes[0] node within the _grid
1016     size_t      _i,_j,_k;
1017     bool        _hasTooSmall;
1018     int         _cellID;
1019
1020   public:
1021     Hexahedron(Grid* grid);
1022     int MakeElements(SMESH_MesherHelper&                      helper,
1023                      const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1024     void computeElements( const Solid* solid = 0, int solidIndex = -1 );
1025
1026   private:
1027     Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
1028     void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
1029     void init( size_t i );
1030     void setIJK( size_t i );
1031     bool compute( const Solid* solid, const IsInternalFlag intFlag );
1032     size_t getSolids( TGeomID ids[] );
1033     bool isCutByInternalFace( IsInternalFlag & maxFlag );
1034     void addEdges(SMESH_MesherHelper&                      helper,
1035                   vector< Hexahedron* >&                   intersectedHex,
1036                   const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1037     gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
1038                          double proj, BRepAdaptor_Curve& curve,
1039                          const gp_XYZ& axis, const gp_XYZ& origin );
1040     int  getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
1041     bool addIntersection( const E_IntersectPoint* ip,
1042                           vector< Hexahedron* >&  hexes,
1043                           int ijk[], int dIJK[] );
1044     bool isQuadOnFace( const size_t iQuad );
1045     bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
1046     bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
1047     bool findChainOnEdge( const vector< _OrientedLink >& splits,
1048                           const _OrientedLink&           prevSplit,
1049                           const _OrientedLink&           avoidSplit,
1050                           const std::set< TGeomID > &    concaveFaces,
1051                           size_t &                       iS,
1052                           _Face&                         quad,
1053                           vector<_Node*>&                chn);
1054     int  addVolumes(SMESH_MesherHelper& helper );
1055     void addFaces( SMESH_MesherHelper&                       helper,
1056                    const vector< const SMDS_MeshElement* > & boundaryVolumes );
1057     void addSegments( SMESH_MesherHelper&                      helper,
1058                       const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
1059     void getVolumes( vector< const SMDS_MeshElement* > & volumes );
1060     void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
1061     void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
1062     void removeExcessNodes(vector< Hexahedron* >& allHexa);
1063     void preventVolumesOverlapping();
1064     TGeomID getAnyFace() const;
1065     void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
1066                                 const TColStd_MapOfInteger& intEdgeIDs );
1067     gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
1068     bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
1069     void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
1070     bool isInHole() const;
1071     bool hasStrangeEdge() const;
1072     bool checkPolyhedronSize( bool isCutByInternalFace, double & volSize ) const;
1073     int checkPolyhedronValidity( _volumeDef* volDef, std::vector<std::vector<int>>& splitQuantities, 
1074                                   std::vector<std::vector<const SMDS_MeshNode*>>& splitNodes );
1075     const SMDS_MeshElement* addPolyhedronToMesh( _volumeDef* volDef,  SMESH_MesherHelper& helper, const std::vector<const SMDS_MeshNode*>& nodes, 
1076                                                 const std::vector<int>& quantities );
1077     bool addHexa ();
1078     bool addTetra();
1079     bool addPenta();
1080     bool addPyra ();
1081     bool debugDumpLink( _Link* link );
1082     _Node* findEqualNode( vector< _Node* >&       nodes,
1083                           const E_IntersectPoint* ip,
1084                           const double            tol2 )
1085     {
1086       for ( size_t i = 0; i < nodes.size(); ++i )
1087         if ( nodes[i]->EdgeIntPnt() == ip ||
1088              nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
1089           return nodes[i];
1090       return 0;
1091     }
1092     bool isCorner( const _Node* node ) const { return ( node >= &_hexNodes[0] &&
1093                                                         node -  &_hexNodes[0] < 8 ); }
1094     bool hasEdgesAround( const ConcaveFace* cf ) const;
1095     bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
1096     bool isOutParam(const double uvw[3]) const;
1097
1098     typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
1099     static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
1100     {
1101       TID2Nb::value_type s0( id, 0 );
1102       TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
1103       id2nb->second++;
1104     }
1105   }; // class Hexahedron
1106
1107 #ifdef WITH_TBB
1108   // --------------------------------------------------------------------------
1109   /*!
1110    * \brief Hexahedron computing volumes in one thread
1111    */
1112   struct ParallelHexahedron
1113   {
1114     vector< Hexahedron* >& _hexVec;
1115     ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
1116     void operator() ( const tbb::blocked_range<size_t>& r ) const
1117     {
1118       for ( size_t i = r.begin(); i != r.end(); ++i )
1119         if ( Hexahedron* hex = _hexVec[ i ] )
1120           hex->computeElements();
1121     }
1122   };
1123   // --------------------------------------------------------------------------
1124   /*!
1125    * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1126    */
1127   struct ParallelIntersector
1128   {
1129     vector< FaceGridIntersector >& _faceVec;
1130     ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1131     void operator() ( const tbb::blocked_range<size_t>& r ) const
1132     {
1133       for ( size_t i = r.begin(); i != r.end(); ++i )
1134         _faceVec[i].Intersect();
1135     }
1136   };
1137 #endif
1138
1139   //=============================================================================
1140   // Implementation of internal utils
1141   //=============================================================================
1142   /*!
1143    * \brief adjust \a i to have \a val between values[i] and values[i+1]
1144    */
1145   inline void locateValue( int & i, double val, const vector<double>& values,
1146                            int& di, double tol )
1147   {
1148     //val += values[0]; // input \a val is measured from 0.
1149     if ( i > (int) values.size()-2 )
1150       i = values.size()-2;
1151     else
1152       while ( i+2 < (int) values.size() && val > values[ i+1 ])
1153         ++i;
1154     while ( i > 0 && val < values[ i ])
1155       --i;
1156
1157     if ( i > 0 && val - values[ i ] < tol )
1158       di = -1;
1159     else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1160       di = 1;
1161     else
1162       di = 0;
1163   }
1164   //=============================================================================
1165   /*
1166    * Return a vector of SOLIDS sharing given shapes
1167    */
1168   GeomIDVecHelder Geometry::GetSolidIDsByShapeID( const vector< TGeomID >& theShapeIDs ) const
1169   {
1170     if ( theShapeIDs.size() == 1 )
1171       return GeomIDVecHelder( _solidIDsByShapeID[ theShapeIDs[ 0 ]], /*owner=*/false );
1172
1173     // look for an empty slot in _solidIDsByShapeID
1174     vector< TGeomID > * resultIDs = 0;
1175     for ( const vector< TGeomID >& vec : _solidIDsByShapeID )
1176       if ( vec.empty() )
1177       {
1178         resultIDs = const_cast< vector< TGeomID > * >( & vec );
1179         break;
1180       }
1181     // fill in resultIDs
1182     for ( const TGeomID& id : theShapeIDs )
1183       for ( const TGeomID& solid : _solidIDsByShapeID[ id ])
1184       {
1185         if ( std::find( resultIDs->begin(), resultIDs->end(), solid ) == resultIDs->end() )
1186           resultIDs->push_back( solid );
1187       }
1188     return GeomIDVecHelder( *resultIDs, /*owner=*/true );
1189   }
1190   //=============================================================================
1191   /*
1192    * Remove coincident intersection points
1193    */
1194   void GridLine::RemoveExcessIntPoints( const double tol )
1195   {
1196     if ( _intPoints.size() < 2 ) return;
1197
1198     set< Transition > tranSet;
1199     multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1200     while ( ip2 != _intPoints.end() )
1201     {
1202       tranSet.clear();
1203       ip1 = ip2++;
1204       while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1205       {
1206         tranSet.insert( ip1->_transition );
1207         tranSet.insert( ip2->_transition );
1208         ip2->Add( ip1->_faceIDs );
1209         _intPoints.erase( ip1 );
1210         ip1 = ip2++;
1211       }
1212       if ( tranSet.size() > 1 ) // points with different transition coincide
1213       {
1214         bool isIN  = tranSet.count( Trans_IN );
1215         bool isOUT = tranSet.count( Trans_OUT );
1216         if ( isIN && isOUT )
1217           (*ip1)._transition = Trans_TANGENT;
1218         else
1219           (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1220       }
1221     }
1222   }
1223   //================================================================================
1224   /*
1225    * Return ID of SOLID for nodes before the given intersection point
1226    */
1227   TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1228                                       const TGeomID                          prevID,
1229                                       const Geometry&                        geom )
1230   {
1231     if ( ip == _intPoints.begin() )
1232       return 0;
1233
1234     if ( geom.IsOneSolid() )
1235     {
1236       bool isOut = true;
1237       switch ( ip->_transition ) {
1238       case Trans_IN:      isOut = true;            break;
1239       case Trans_OUT:     isOut = false;           break;
1240       case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1241       case Trans_APEX:
1242       {
1243         // singularity point (apex of a cone)
1244         multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1245         if ( ipAft == _intPoints.end() )
1246           isOut = false;
1247         else
1248         {
1249           --ipBef;
1250           if ( ipBef->_transition != ipAft->_transition )
1251             isOut = ( ipBef->_transition == Trans_OUT );
1252           else
1253             isOut = ( ipBef->_transition != Trans_OUT );
1254         }
1255         break;
1256       }
1257       case Trans_INTERNAL: isOut = false;
1258       default:;
1259       }
1260       return isOut ? 0 : geom._soleSolid.ID();
1261     }
1262
1263     GeomIDVecHelder solids = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1264
1265     --ip;
1266     if ( ip->_transition == Trans_INTERNAL )
1267       return prevID;
1268
1269     GeomIDVecHelder solidsBef = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1270
1271     if ( ip->_transition == Trans_IN ||
1272          ip->_transition == Trans_OUT )
1273     {
1274       if ( solidsBef.size() == 1 )
1275       {
1276         if ( solidsBef[0] == prevID )
1277           return ip->_transition == Trans_OUT ? 0 : solidsBef[0];
1278         else
1279           return solidsBef[0];
1280       }
1281
1282       if ( solids.size() == 2 )
1283       {
1284         if ( solids == solidsBef )
1285           return solids.contain( prevID ) ? solids.otherThan( prevID ) : theUndefID; // bos #29212
1286       }
1287       return solids.oneCommon( solidsBef );
1288     }
1289
1290     if ( solidsBef.size() == 1 )
1291       return solidsBef[0];
1292
1293     return solids.oneCommon( solidsBef );
1294   }
1295   //================================================================================
1296   /*
1297    * Adds face IDs
1298    */
1299   bool B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1300                               const SMDS_MeshNode*     n) const
1301   {
1302     size_t prevNbF = _faceIDs.size();
1303
1304     if ( _faceIDs.empty() )
1305       _faceIDs = fIDs;
1306     else
1307       for ( size_t i = 0; i < fIDs.size(); ++i )
1308       {
1309         vector< TGeomID >::iterator it =
1310           std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1311         if ( it == _faceIDs.end() )
1312           _faceIDs.push_back( fIDs[i] );
1313       }
1314     if ( !_node )
1315       _node = n;
1316
1317     return prevNbF < _faceIDs.size();
1318   }
1319   //================================================================================
1320   /*
1321    * Return ID of a common face if any, else zero
1322    */
1323   TGeomID B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace ) const
1324   {
1325     if ( other )
1326       for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1327         if ( avoidFace != other->_faceIDs[i] &&
1328              IsOnFace   ( other->_faceIDs[i] ))
1329           return other->_faceIDs[i];
1330     return 0;
1331   }
1332   //================================================================================
1333   /*
1334    * Return faces common with other point
1335    */
1336   size_t B_IntersectPoint::GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
1337   {
1338     size_t nbComm = 0;
1339     if ( !other )
1340       return nbComm;
1341     if ( _faceIDs.size() > other->_faceIDs.size() )
1342       return other->GetCommonFaces( this, common );
1343     for ( const TGeomID& face : _faceIDs )
1344       if ( other->IsOnFace( face ))
1345         common[ nbComm++ ] = face;
1346     return nbComm;
1347   }
1348   //================================================================================
1349   /*
1350    * Return \c true if \a faceID in in this->_faceIDs
1351    */
1352   bool B_IntersectPoint::IsOnFace( TGeomID faceID ) const // returns true if faceID is found
1353   {
1354     vector< TGeomID >::const_iterator it =
1355       std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1356     return ( it != _faceIDs.end() );
1357   }
1358   //================================================================================
1359   /*
1360    * OneOfSolids initialization
1361    */
1362   void OneOfSolids::Init( const TopoDS_Shape& solid,
1363                           TopAbs_ShapeEnum    subType,
1364                           const SMESHDS_Mesh* mesh )
1365   {
1366     SetID( mesh->ShapeToIndex( solid ));
1367
1368     if ( subType == TopAbs_FACE )
1369       SetHasInternalFaces( false );
1370
1371     for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1372     {
1373       _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1374       if ( subType == TopAbs_FACE )
1375       {
1376         _faces.Add( sub.Current() );
1377         if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1378           SetHasInternalFaces( true );
1379
1380         TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1381         if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1382              sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1383           _outFaceIDs.Add( faceID );
1384       }
1385     }
1386   }
1387   //================================================================================
1388   /*
1389    * Return an iterator on GridLine's in a given direction
1390    */
1391   LineIndexer Grid::GetLineIndexer(size_t iDir) const
1392   {
1393     const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1394     const string s      [] = { "X", "Y", "Z" };
1395     LineIndexer li( _coords[0].size(),  _coords[1].size(),    _coords[2].size(),
1396                     indices[iDir*3],    indices[iDir*3+1],    indices[iDir*3+2],
1397                     s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1398     return li;
1399   }
1400   //================================================================================
1401   /*
1402    * Return direction [0,1,2] of a GridLine
1403    */
1404   size_t Grid::GetLineDir( const GridLine* line, size_t & index ) const
1405   {
1406     for ( size_t iDir = 0; iDir < 3; ++iDir )
1407       if ( &_lines[ iDir ][0] <= line && line <= &_lines[ iDir ].back() )
1408       {
1409         index = line - &_lines[ iDir ][0];
1410         return iDir;
1411       }
1412     return -1;
1413   }
1414   //=============================================================================
1415   /*
1416    * Creates GridLine's of the grid
1417    */
1418   void Grid::SetCoordinates(const vector<double>& xCoords,
1419                             const vector<double>& yCoords,
1420                             const vector<double>& zCoords,
1421                             const double*         axesDirs,
1422                             const Bnd_Box&        shapeBox)
1423   {
1424     _coords[0] = xCoords;
1425     _coords[1] = yCoords;
1426     _coords[2] = zCoords;
1427
1428     _axes[0].SetCoord( axesDirs[0],
1429                        axesDirs[1],
1430                        axesDirs[2]);
1431     _axes[1].SetCoord( axesDirs[3],
1432                        axesDirs[4],
1433                        axesDirs[5]);
1434     _axes[2].SetCoord( axesDirs[6],
1435                        axesDirs[7],
1436                        axesDirs[8]);
1437     _axes[0].Normalize();
1438     _axes[1].Normalize();
1439     _axes[2].Normalize();
1440
1441     _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1442     _invB.Invert();
1443
1444     // compute tolerance
1445     _minCellSize = Precision::Infinite();
1446     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1447     {
1448       for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1449       {
1450         double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1451         if ( cellLen < _minCellSize )
1452           _minCellSize = cellLen;
1453       }
1454     }
1455     if ( _minCellSize < Precision::Confusion() )
1456       throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1457                                 SMESH_Comment("Too small cell size: ") << _minCellSize );
1458     _tol = _minCellSize / 1000.;
1459
1460     // attune grid extremities to shape bounding box
1461
1462     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1463     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1464     double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1465                       &_coords[0].back(),  &_coords[1].back(),  &_coords[2].back() };
1466     for ( int i = 0; i < 6; ++i )
1467       if ( fabs( sP[i] - *cP[i] ) < _tol )
1468         *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1469
1470     for ( int iDir = 0; iDir < 3; ++iDir )
1471     {
1472       if ( _coords[iDir][0] - sP[iDir] > _tol )
1473       {
1474         _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1475         _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1476       }
1477       if ( sP[iDir+3] - _coords[iDir].back() > _tol  )
1478       {
1479         _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1480         _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1481       }
1482     }
1483     _tol = _minCellSize / 1000.;
1484
1485     _origin = ( _coords[0][0] * _axes[0] +
1486                 _coords[1][0] * _axes[1] +
1487                 _coords[2][0] * _axes[2] );
1488
1489     // create lines
1490     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1491     {
1492       LineIndexer li = GetLineIndexer( iDir );
1493       _lines[iDir].resize( li.NbLines() );
1494       double len = _coords[ iDir ].back() - _coords[iDir].front();
1495       for ( ; li.More(); ++li )
1496       {
1497         GridLine& gl = _lines[iDir][ li.LineIndex() ];
1498         gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1499                               _coords[1][li.J()] * _axes[1] +
1500                               _coords[2][li.K()] * _axes[2] );
1501         gl._line.SetDirection( _axes[ iDir ]);
1502         gl._length = len;
1503       }
1504     }
1505   }
1506   //================================================================================
1507   /*
1508    * Return local ID of shape
1509    */
1510   TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1511   {
1512     return _helper->GetMeshDS()->ShapeToIndex( s );
1513   }
1514   //================================================================================
1515   /*
1516    * Return a shape by its local ID
1517    */
1518   const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1519   {
1520     return _helper->GetMeshDS()->IndexToShape( id );
1521   }
1522   //================================================================================
1523   /*
1524    * Initialize _geometry
1525    */
1526   void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1527   {
1528     SMESH_Mesh* mesh = _helper->GetMesh();
1529
1530     _geometry._mainShape = theShapeToMesh;
1531     _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1532     _geometry._soleSolid.SetID( 0 );
1533     _geometry._soleSolid.SetHasInternalFaces( false );
1534
1535     InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1536     InitClassifier( theShapeToMesh, TopAbs_EDGE  , _geometry._edgeClassifier );
1537
1538     TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1539
1540     bool isSeveralSolids = false;
1541     if ( _toConsiderInternalFaces ) // check nb SOLIDs
1542     {
1543       solidExp.Next();
1544       isSeveralSolids = solidExp.More();
1545       _toConsiderInternalFaces = isSeveralSolids;
1546       solidExp.ReInit();
1547
1548       if ( !isSeveralSolids ) // look for an internal FACE
1549       {
1550         TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1551         for ( ; fExp.More() &&  !_toConsiderInternalFaces; fExp.Next() )
1552           _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1553
1554         _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1555         _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1556       }
1557       else // fill Geometry::_solidByID
1558       {
1559         for ( ; solidExp.More(); solidExp.Next() )
1560         {
1561           OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1562           solid.Init( solidExp.Current(), TopAbs_FACE,   mesh->GetMeshDS() );
1563           solid.Init( solidExp.Current(), TopAbs_EDGE,   mesh->GetMeshDS() );
1564           solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1565         }
1566       }
1567     }
1568     else
1569     {
1570       _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1571     }
1572
1573     if ( !_toCreateFaces )
1574     {
1575       int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1576       int nbSolidsLocal  = _helper->Count( theShapeToMesh,         TopAbs_SOLID, false );
1577       _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1578     }
1579
1580     TopTools_IndexedMapOfShape faces;
1581     TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1582
1583     // find boundary FACEs on boundary of mesh->ShapeToMesh()
1584     if ( _toCreateFaces )
1585       for ( int i = 1; i <= faces.Size(); ++i )
1586         if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1587              _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1588         {
1589           _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1590         }
1591
1592     if ( isSeveralSolids )
1593       for ( int i = 1; i <= faces.Size(); ++i )
1594       {
1595         SetSolidFather( faces(i), theShapeToMesh );
1596         for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1597         {
1598           const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1599           SetSolidFather( edge, theShapeToMesh );
1600           SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1601           SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1602         }
1603       }
1604
1605     // fill in _geometry._shape2NbNodes == find already meshed sub-shapes
1606     _geometry._shape2NbNodes.Clear();
1607     if ( mesh->NbNodes() > 0 )
1608     {
1609       for ( TopAbs_ShapeEnum type : { TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX })
1610         for ( TopExp_Explorer exp( theShapeToMesh, type ); exp.More(); exp.Next() )
1611         {
1612           if ( _geometry._shape2NbNodes.IsBound( exp.Current() ))
1613             continue;
1614           if ( SMESHDS_SubMesh* sm = mesh->GetMeshDS()->MeshElements( exp.Current() ))
1615             if ( sm->NbNodes() > 0 )
1616               _geometry._shape2NbNodes.Bind( exp.Current(), sm->NbNodes() );
1617         }
1618     }
1619
1620     // fill in Solid::_concaveVertex
1621     vector< TGeomID > soleSolidID( 1, _geometry._soleSolid.ID() );
1622     for ( int i = 1; i <= faces.Size(); ++i )
1623     {
1624       const TopoDS_Face& F = TopoDS::Face( faces( i ));
1625       TError error;
1626       TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *mesh, 0, error,
1627                                                              nullptr, nullptr, false );
1628       for ( StdMeshers_FaceSidePtr& wire : wires )
1629       {
1630         const int nbEdges = wire->NbEdges();
1631         if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wire->Edge(0)))
1632           continue;
1633         for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1634         {
1635           if ( SMESH_Algo::isDegenerated( wire->Edge( iE1 ))) continue;
1636           int iE2 = ( iE1 + 1 ) % nbEdges;
1637           while ( SMESH_Algo::isDegenerated( wire->Edge( iE2 )))
1638             iE2 = ( iE2 + 1 ) % nbEdges;
1639           TopoDS_Vertex V = wire->FirstVertex( iE2 );
1640           double angle = _helper->GetAngle( wire->Edge( iE1 ),
1641                                             wire->Edge( iE2 ), F, V );
1642           if ( angle < -5. * M_PI / 180. )
1643           {
1644             TGeomID faceID = ShapeID( F );
1645             const vector< TGeomID > & solids =
1646               _geometry.IsOneSolid() ? soleSolidID : GetSolidIDs( faceID );
1647             for ( const TGeomID & solidID : solids )
1648             {
1649               Solid* solid = GetSolid( solidID );
1650               TGeomID   V1 = ShapeID( wire->FirstVertex( iE1 ));
1651               TGeomID   V2 = ShapeID( wire->LastVertex ( iE2 ));
1652               solid->SetConcave( ShapeID( V ), faceID,
1653                                  wire->EdgeID( iE1 ), wire->EdgeID( iE2 ), V1, V2 );
1654             }
1655           }
1656         }
1657       }
1658     }
1659
1660     return;
1661   }
1662   //================================================================================
1663   /*
1664    * Store ID of SOLID as father of its child shape ID
1665    */
1666   void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1667   {
1668     if ( _geometry._solidIDsByShapeID.empty() )
1669       _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1670
1671     vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1672     if ( !solidIDs.empty() )
1673       return;
1674     solidIDs.reserve(2);
1675     PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1676                                                        *_helper->GetMesh(),
1677                                                        TopAbs_SOLID,
1678                                                        & theShapeToMesh );
1679     while ( const TopoDS_Shape* solid = solidIt->next() )
1680       solidIDs.push_back( ShapeID( *solid ));
1681   }
1682   //================================================================================
1683   /*
1684    * Return IDs of solids given sub-shape belongs to
1685    */
1686   const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1687   {
1688     return _geometry._solidIDsByShapeID[ subShapeID ];
1689   }
1690   //================================================================================
1691   /*
1692    * Check if a sub-shape belongs to several SOLIDs
1693    */
1694   bool Grid::IsShared( TGeomID shapeID ) const
1695   {
1696     return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1697   }
1698   //================================================================================
1699   /*
1700    * Check if any of FACEs belongs to several SOLIDs
1701    */
1702   bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1703   {
1704     for ( size_t i = 0; i < faceIDs.size(); ++i )
1705       if ( IsShared( faceIDs[ i ]))
1706         return true;
1707     return false;
1708   }
1709   //================================================================================
1710   /*
1711    * Return Solid by ID
1712    */
1713   Solid* Grid::GetSolid( TGeomID solidID )
1714   {
1715     if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1716       return & _geometry._soleSolid;
1717
1718     return & _geometry._solidByID[ solidID ];
1719   }
1720   //================================================================================
1721   /*
1722    * Return OneOfSolids by ID
1723    */
1724   Solid* Grid::GetOneOfSolids( TGeomID solidID )
1725   {
1726     map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1727     if ( is2s != _geometry._solidByID.end() )
1728       return & is2s->second;
1729
1730     return & _geometry._soleSolid;
1731   }
1732   //================================================================================
1733   /*
1734    * Check if transition on given FACE is correct for a given SOLID
1735    */
1736   bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1737   {
1738     if ( _geometry.IsOneSolid() )
1739       return true;
1740
1741     const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1742     return solidIDs[0] == solid->ID();
1743   }
1744
1745   //================================================================================
1746   /*
1747    * Assign to geometry a node at FACE intersection
1748    * Return a found supporting VERTEX
1749    */
1750   void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
1751                          TopoDS_Vertex* vertex, bool unset )
1752   {
1753     TopoDS_Shape s;
1754     SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1755     if ( ip._faceIDs.size() == 1 )
1756     {
1757       mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1758     }
1759     else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1760     {
1761       if ( unset ) mesh->UnSetNodeOnShape( n );
1762       mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1763       if ( vertex )
1764         *vertex = TopoDS::Vertex( s );
1765     }
1766     else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1767     {
1768       if ( unset ) mesh->UnSetNodeOnShape( n );
1769       mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1770     }
1771     else if ( ip._faceIDs.size() > 0 )
1772     {
1773       mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1774     }
1775     else if ( !unset && _geometry.IsOneSolid() )
1776     {
1777       mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1778     }
1779   }
1780   //================================================================================
1781   /*
1782    * Fill in B_IntersectPoint::_faceIDs with all FACEs sharing a VERTEX
1783    */
1784   void Grid::UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex )
1785   {
1786     if ( vertex.IsNull() )
1787       return;
1788     std::vector< int > faceID(1);
1789     PShapeIteratorPtr fIt = _helper->GetAncestors( vertex, *_helper->GetMesh(),
1790                                                    TopAbs_FACE, & _geometry._mainShape );
1791     while ( const TopoDS_Shape* face = fIt->next() )
1792     {
1793       faceID[ 0 ] = ShapeID( *face );
1794       ip.Add( faceID );
1795     }
1796   }
1797   //================================================================================
1798   /*
1799    * Initialize a classifier
1800    */
1801   void Grid::InitClassifier( const TopoDS_Shape&        mainShape,
1802                              TopAbs_ShapeEnum           shapeType,
1803                              Controls::ElementsOnShape& classifier )
1804   {
1805     TopTools_IndexedMapOfShape shapes;
1806     TopExp::MapShapes( mainShape, shapeType, shapes );
1807
1808     TopoDS_Compound compound; BRep_Builder builder;
1809     builder.MakeCompound( compound );
1810     for ( int i = 1; i <= shapes.Size(); ++i )
1811       builder.Add( compound, shapes(i) );
1812
1813     classifier.SetMesh( _helper->GetMeshDS() );
1814     //classifier.SetTolerance( _tol ); // _tol is not initialised
1815     classifier.SetShape( compound, SMDSAbs_Node );
1816   }
1817
1818   //================================================================================
1819   /*
1820    * Return EDGEs with FACEs to implement into the mesh
1821    */
1822   void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1823                                   const TopoDS_Shape&                 shape,
1824                                   const vector< TopoDS_Shape >&       faces )
1825   {
1826     // check if there are strange EDGEs
1827     TopTools_IndexedMapOfShape faceMap;
1828     TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1829     int nbFacesGlobal = faceMap.Size();
1830     faceMap.Clear( false );
1831     TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1832     int nbFacesLocal  = faceMap.Size();
1833     bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1834     if ( !_toAddEdges && !hasStrangeEdges )
1835       return; // no FACEs in contact with those meshed by other algo
1836
1837     for ( size_t i = 0; i < faces.size(); ++i )
1838     {
1839       _helper->SetSubShape( faces[i] );
1840       for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1841       {
1842         const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1843         if ( hasStrangeEdges )
1844         {
1845           bool hasStrangeFace = false;
1846           PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1847           while ( const TopoDS_Shape* face = faceIt->next() )
1848             if (( hasStrangeFace = !faceMap.Contains( *face )))
1849               break;
1850           if ( !hasStrangeFace && !_toAddEdges )
1851             continue;
1852           _geometry._strangeEdges.Add( ShapeID( edge ));
1853           _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1854           _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1855         }
1856         if ( !SMESH_Algo::isDegenerated( edge ) &&
1857              !_helper->IsRealSeam( edge ))
1858         {
1859           edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1860         }
1861       }
1862     }
1863     return;
1864   }
1865
1866   //================================================================================
1867   /*
1868    * Computes coordinates of a point in the grid CS
1869    */
1870   void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1871   {
1872     gp_XYZ p = P * _invB;
1873     p.Coord( UVW[0], UVW[1], UVW[2] );
1874   }
1875   //================================================================================
1876   /*
1877    * Creates all nodes
1878    */
1879   void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1880   {
1881     // state of each node of the grid relative to the geometry
1882     const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1883     vector< TGeomID > shapeIDVec( nbGridNodes, theUndefID );
1884     _nodes.resize( nbGridNodes, 0 );
1885     _gridIntP.resize( nbGridNodes, NULL );
1886
1887     SMESHDS_Mesh* mesh = helper.GetMeshDS();
1888
1889     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1890     {
1891       LineIndexer li = GetLineIndexer( iDir );
1892
1893       // find out a shift of node index while walking along a GridLine in this direction
1894       li.SetIndexOnLine( 0 );
1895       size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1896       li.SetIndexOnLine( 1 );
1897       const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1898       
1899       const vector<double> & coords = _coords[ iDir ];
1900       for ( ; li.More(); ++li ) // loop on lines in iDir
1901       {
1902         li.SetIndexOnLine( 0 );
1903         nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1904
1905         GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1906         const gp_XYZ lineLoc = line._line.Location().XYZ();
1907         const gp_XYZ lineDir = line._line.Direction().XYZ();
1908
1909         line.RemoveExcessIntPoints( _tol );
1910         multiset< F_IntersectPoint >&     intPnts = line._intPoints;
1911         multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1912
1913         // Create mesh nodes at intersections with geometry
1914         // and set OUT state of nodes between intersections
1915
1916         TGeomID solidID = 0;
1917         const double* nodeCoord = & coords[0];
1918         const double* coord0    = nodeCoord;
1919         const double* coordEnd  = coord0 + coords.size();
1920         double nodeParam = 0;
1921         for ( ; ip != intPnts.end(); ++ip )
1922         {
1923           solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1924
1925           // set OUT state or just skip IN nodes before ip
1926           if ( nodeParam < ip->_paramOnLine - _tol )
1927           {
1928             while ( nodeParam < ip->_paramOnLine - _tol )
1929             {
1930               TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1931               nodeShapeID = Min( solidID, nodeShapeID );
1932               if ( ++nodeCoord <  coordEnd )
1933                 nodeParam = *nodeCoord - *coord0;
1934               else
1935                 break;
1936             }
1937             if ( nodeCoord == coordEnd ) break;
1938           }
1939           // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1940           if ( nodeParam > ip->_paramOnLine + _tol )
1941           {
1942             gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1943             ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1944             ip->_indexOnLine = nodeCoord-coord0-1;
1945             TopoDS_Vertex v;
1946             SetOnShape( ip->_node, *ip, & v );
1947             UpdateFacesOfVertex( *ip, v );
1948           }
1949           // create a mesh node at ip coincident with a grid node
1950           else
1951           {
1952             int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1953             if ( !_nodes[ nodeIndex ] )
1954             {
1955               gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1956               _nodes   [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1957               //_gridIntP[ nodeIndex ] = & * ip;
1958               //SetOnShape( _nodes[ nodeIndex ], *ip );
1959             }
1960             if ( _gridIntP[ nodeIndex ] )
1961               _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1962             else
1963               _gridIntP[ nodeIndex ] = & * ip;
1964             // ip->_node        = _nodes[ nodeIndex ]; -- to differ from ip on links
1965             ip->_indexOnLine = nodeCoord-coord0;
1966             if ( ++nodeCoord < coordEnd )
1967               nodeParam = *nodeCoord - *coord0;
1968           }
1969         }
1970         // set OUT state to nodes after the last ip
1971         for ( ; nodeCoord < coordEnd; ++nodeCoord )
1972           shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1973       }
1974     }
1975
1976     // Create mesh nodes at !OUT nodes of the grid
1977
1978     for ( size_t z = 0; z < _coords[2].size(); ++z )
1979       for ( size_t y = 0; y < _coords[1].size(); ++y )
1980         for ( size_t x = 0; x < _coords[0].size(); ++x )
1981         {
1982           size_t nodeIndex = NodeIndex( x, y, z );
1983           if ( !_nodes[ nodeIndex ] &&
1984                0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < theUndefID )
1985           {
1986             gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1987                            _coords[1][y] * _axes[1] +
1988                            _coords[2][z] * _axes[2] );
1989             _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1990             mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1991           }
1992           else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1993                     !_nodes[ nodeIndex]->GetShapeID()*/ )
1994           {
1995             TopoDS_Vertex v;
1996             SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ], & v );
1997             UpdateFacesOfVertex( *_gridIntP[ nodeIndex ], v );
1998           }
1999         }
2000
2001 #ifdef _MY_DEBUG_
2002     // check validity of transitions
2003     const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
2004     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2005     {
2006       LineIndexer li = GetLineIndexer( iDir );
2007       for ( ; li.More(); ++li )
2008       {
2009         multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
2010         if ( intPnts.empty() ) continue;
2011         if ( intPnts.size() == 1 )
2012         {
2013           if ( intPnts.begin()->_transition != Trans_TANGENT &&
2014                intPnts.begin()->_transition != Trans_APEX )
2015             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2016                                       SMESH_Comment("Wrong SOLE transition of GridLine (")
2017                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2018                                       << ") along " << li._nameConst
2019                                       << ": " << trName[ intPnts.begin()->_transition] );
2020         }
2021         else
2022         {
2023           if ( intPnts.begin()->_transition == Trans_OUT )
2024             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2025                                       SMESH_Comment("Wrong START transition of GridLine (")
2026                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2027                                       << ") along " << li._nameConst
2028                                       << ": " << trName[ intPnts.begin()->_transition ]);
2029           if ( intPnts.rbegin()->_transition == Trans_IN )
2030             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2031                                       SMESH_Comment("Wrong END transition of GridLine (")
2032                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2033                                       << ") along " << li._nameConst
2034                                       << ": " << trName[ intPnts.rbegin()->_transition ]);
2035         }
2036       }
2037     }
2038 #endif
2039
2040     return;
2041   }
2042
2043   //=============================================================================
2044   /*
2045    * Intersects TopoDS_Face with all GridLine's
2046    */
2047   void FaceGridIntersector::Intersect()
2048   {
2049     FaceLineIntersector intersector;
2050     intersector._surfaceInt = GetCurveFaceIntersector();
2051     intersector._tol        = _grid->_tol;
2052     intersector._transOut   = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
2053     intersector._transIn    = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
2054
2055     typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
2056     PIntFun interFunction;
2057
2058     bool isDirect = true;
2059     BRepAdaptor_Surface surf( _face );
2060     switch ( surf.GetType() ) {
2061     case GeomAbs_Plane:
2062       intersector._plane = surf.Plane();
2063       interFunction = &FaceLineIntersector::IntersectWithPlane;
2064       isDirect = intersector._plane.Direct();
2065       break;
2066     case GeomAbs_Cylinder:
2067       intersector._cylinder = surf.Cylinder();
2068       interFunction = &FaceLineIntersector::IntersectWithCylinder;
2069       isDirect = intersector._cylinder.Direct();
2070       break;
2071     case GeomAbs_Cone:
2072       intersector._cone = surf.Cone();
2073       interFunction = &FaceLineIntersector::IntersectWithCone;
2074       //isDirect = intersector._cone.Direct();
2075       break;
2076     case GeomAbs_Sphere:
2077       intersector._sphere = surf.Sphere();
2078       interFunction = &FaceLineIntersector::IntersectWithSphere;
2079       isDirect = intersector._sphere.Direct();
2080       break;
2081     case GeomAbs_Torus:
2082       intersector._torus = surf.Torus();
2083       interFunction = &FaceLineIntersector::IntersectWithTorus;
2084       //isDirect = intersector._torus.Direct();
2085       break;
2086     default:
2087       interFunction = &FaceLineIntersector::IntersectWithSurface;
2088     }
2089     if ( !isDirect )
2090       std::swap( intersector._transOut, intersector._transIn );
2091
2092     _intersections.clear();
2093     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2094     {
2095       if ( surf.GetType() == GeomAbs_Plane )
2096       {
2097         // check if all lines in this direction are parallel to a plane
2098         if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
2099                                                  Precision::Angular()))
2100           continue;
2101         // find out a transition, that is the same for all lines of a direction
2102         gp_Dir plnNorm = intersector._plane.Axis().Direction();
2103         gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
2104         intersector._transition =
2105           ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
2106       }
2107       if ( surf.GetType() == GeomAbs_Cylinder )
2108       {
2109         // check if all lines in this direction are parallel to a cylinder
2110         if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
2111                                                       Precision::Angular()))
2112           continue;
2113       }
2114
2115       // intersect the grid lines with the face
2116       for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
2117       {
2118         GridLine& gridLine = _grid->_lines[iDir][iL];
2119         if ( _bndBox.IsOut( gridLine._line )) continue;
2120
2121         intersector._intPoints.clear();
2122         (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
2123         for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
2124           _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
2125       }
2126     }
2127
2128     if ( _face.Orientation() == TopAbs_INTERNAL )
2129     {
2130       for ( size_t i = 0; i < _intersections.size(); ++i )
2131         if ( _intersections[i].second._transition == Trans_IN ||
2132              _intersections[i].second._transition == Trans_OUT )
2133         {
2134           _intersections[i].second._transition = Trans_INTERNAL;
2135         }
2136     }
2137     return;
2138   }
2139   //================================================================================
2140   /*
2141    * Return true if (_u,_v) is on the face
2142    */
2143   bool FaceLineIntersector::UVIsOnFace() const
2144   {
2145     TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
2146     return ( state == TopAbs_IN || state == TopAbs_ON );
2147   }
2148   //================================================================================
2149   /*
2150    * Store an intersection if it is IN or ON the face
2151    */
2152   void FaceLineIntersector::addIntPoint(const bool toClassify)
2153   {
2154     if ( !toClassify || UVIsOnFace() )
2155     {
2156       F_IntersectPoint p;
2157       p._paramOnLine = _w;
2158       p._u           = _u;
2159       p._v           = _v;
2160       p._transition  = _transition;
2161       _intPoints.push_back( p );
2162     }
2163   }
2164   //================================================================================
2165   /*
2166    * Intersect a line with a plane
2167    */
2168   void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
2169   {
2170     IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
2171     _w = linPlane.ParamOnConic(1);
2172     if ( isParamOnLineOK( gridLine._length ))
2173     {
2174       ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
2175       addIntPoint();
2176     }
2177   }
2178   //================================================================================
2179   /*
2180    * Intersect a line with a cylinder
2181    */
2182   void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
2183   {
2184     IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
2185     if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
2186     {
2187       _w = linCylinder.ParamOnConic(1);
2188       if ( linCylinder.NbPoints() == 1 )
2189         _transition = Trans_TANGENT;
2190       else
2191         _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
2192       if ( isParamOnLineOK( gridLine._length ))
2193       {
2194         ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
2195         addIntPoint();
2196       }
2197       if ( linCylinder.NbPoints() > 1 )
2198       {
2199         _w = linCylinder.ParamOnConic(2);
2200         if ( isParamOnLineOK( gridLine._length ))
2201         {
2202           ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
2203           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2204           addIntPoint();
2205         }
2206       }
2207     }
2208   }
2209   //================================================================================
2210   /*
2211    * Intersect a line with a cone
2212    */
2213   void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
2214   {
2215     IntAna_IntConicQuad linCone(gridLine._line,_cone);
2216     if ( !linCone.IsDone() ) return;
2217     gp_Pnt P;
2218     gp_Vec du, dv, norm;
2219     for ( int i = 1; i <= linCone.NbPoints(); ++i )
2220     {
2221       _w = linCone.ParamOnConic( i );
2222       if ( !isParamOnLineOK( gridLine._length )) continue;
2223       ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
2224       if ( UVIsOnFace() )
2225       {
2226         ElSLib::D1( _u, _v, _cone, P, du, dv );
2227         norm = du ^ dv;
2228         double normSize2 = norm.SquareMagnitude();
2229         if ( normSize2 > Precision::Angular() * Precision::Angular() )
2230         {
2231           double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2232           cos /= sqrt( normSize2 );
2233           if ( cos < -Precision::Angular() )
2234             _transition = _transIn;
2235           else if ( cos > Precision::Angular() )
2236             _transition = _transOut;
2237           else
2238             _transition = Trans_TANGENT;
2239         }
2240         else
2241         {
2242           _transition = Trans_APEX;
2243         }
2244         addIntPoint( /*toClassify=*/false);
2245       }
2246     }
2247   }
2248   //================================================================================
2249   /*
2250    * Intersect a line with a sphere
2251    */
2252   void FaceLineIntersector::IntersectWithSphere  (const GridLine& gridLine)
2253   {
2254     IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
2255     if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
2256     {
2257       _w = linSphere.ParamOnConic(1);
2258       if ( linSphere.NbPoints() == 1 )
2259         _transition = Trans_TANGENT;
2260       else
2261         _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
2262       if ( isParamOnLineOK( gridLine._length ))
2263       {
2264         ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2265         addIntPoint();
2266       }
2267       if ( linSphere.NbPoints() > 1 )
2268       {
2269         _w = linSphere.ParamOnConic(2);
2270         if ( isParamOnLineOK( gridLine._length ))
2271         {
2272           ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2273           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2274           addIntPoint();
2275         }
2276       }
2277     }
2278   }
2279   //================================================================================
2280   /*
2281    * Intersect a line with a torus
2282    */
2283   void FaceLineIntersector::IntersectWithTorus   (const GridLine& gridLine)
2284   {
2285     IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2286     if ( !linTorus.IsDone()) return;
2287     gp_Pnt P;
2288     gp_Vec du, dv, norm;
2289     for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2290     {
2291       _w = linTorus.ParamOnLine( i );
2292       if ( !isParamOnLineOK( gridLine._length )) continue;
2293       linTorus.ParamOnTorus( i, _u,_v );
2294       if ( UVIsOnFace() )
2295       {
2296         ElSLib::D1( _u, _v, _torus, P, du, dv );
2297         norm = du ^ dv;
2298         double normSize = norm.Magnitude();
2299         double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2300         cos /= normSize;
2301         if ( cos < -Precision::Angular() )
2302           _transition = _transIn;
2303         else if ( cos > Precision::Angular() )
2304           _transition = _transOut;
2305         else
2306           _transition = Trans_TANGENT;
2307         addIntPoint( /*toClassify=*/false);
2308       }
2309     }
2310   }
2311   //================================================================================
2312   /*
2313    * Intersect a line with a non-analytical surface
2314    */
2315   void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2316   {
2317     _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2318     if ( !_surfaceInt->IsDone() ) return;
2319     for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2320     {
2321       _transition = Transition( _surfaceInt->Transition( i ) );
2322       _w = _surfaceInt->WParameter( i );
2323       addIntPoint(/*toClassify=*/false);
2324     }
2325   }
2326   //================================================================================
2327   /*
2328    * check if its face can be safely intersected in a thread
2329    */
2330   bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2331   {
2332     bool isSafe = true;
2333
2334     // check surface
2335     TopLoc_Location loc;
2336     Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2337     Handle(Geom_RectangularTrimmedSurface) ts =
2338       Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2339     while( !ts.IsNull() ) {
2340       surf = ts->BasisSurface();
2341       ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2342     }
2343     if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2344          surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2345       if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2346         isSafe = false;
2347
2348     double f, l;
2349     TopExp_Explorer exp( _face, TopAbs_EDGE );
2350     for ( ; exp.More(); exp.Next() )
2351     {
2352       bool edgeIsSafe = true;
2353       const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2354       // check 3d curve
2355       {
2356         Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2357         if ( !c.IsNull() )
2358         {
2359           Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2360           while( !tc.IsNull() ) {
2361             c = tc->BasisCurve();
2362             tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2363           }
2364           if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2365                c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2366             edgeIsSafe = false;
2367         }
2368       }
2369       // check 2d curve
2370       if ( edgeIsSafe )
2371       {
2372         Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2373         if ( !c2.IsNull() )
2374         {
2375           Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2376           while( !tc.IsNull() ) {
2377             c2 = tc->BasisCurve();
2378             tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2379           }
2380           if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2381                c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2382             edgeIsSafe = false;
2383         }
2384       }
2385       if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2386         isSafe = false;
2387     }
2388     return isSafe;
2389   }
2390   //================================================================================
2391   /*!
2392    * \brief Creates topology of the hexahedron
2393    */
2394   Hexahedron::Hexahedron(Grid* grid)
2395     : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2396   {
2397     _polygons.reserve(100); // to avoid reallocation;
2398
2399     //set nodes shift within grid->_nodes from the node 000 
2400     size_t dx = _grid->NodeIndexDX();
2401     size_t dy = _grid->NodeIndexDY();
2402     size_t dz = _grid->NodeIndexDZ();
2403     size_t i000 = 0;
2404     size_t i100 = i000 + dx;
2405     size_t i010 = i000 + dy;
2406     size_t i110 = i010 + dx;
2407     size_t i001 = i000 + dz;
2408     size_t i101 = i100 + dz;
2409     size_t i011 = i010 + dz;
2410     size_t i111 = i110 + dz;
2411     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2412     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2413     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2414     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2415     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2416     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2417     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2418     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2419
2420     vector< int > idVec;
2421     // set nodes to links
2422     for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2423     {
2424       SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2425       _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2426       link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2427       link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2428     }
2429
2430     // set links to faces
2431     int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2432     for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2433     {
2434       _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2435       quad._name = (SMESH_Block::TShapeID) faceID;
2436
2437       SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2438       bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2439                        faceID == SMESH_Block::ID_Fx1z ||
2440                        faceID == SMESH_Block::ID_F0yz );
2441       quad._links.resize(4);
2442       vector<_OrientedLink>::iterator         frwLinkIt = quad._links.begin();
2443       vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2444       for ( int i = 0; i < 4; ++i )
2445       {
2446         bool revLink = revFace;
2447         if ( i > 1 ) // reverse links u1 and v0
2448           revLink = !revLink;
2449         _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2450         link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2451                               revLink );
2452       }
2453     }
2454   }
2455   //================================================================================
2456   /*!
2457    * \brief Copy constructor
2458    */
2459   Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2460     :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2461   {
2462     _polygons.reserve(100); // to avoid reallocation;
2463
2464     // copy topology
2465     for ( int i = 0; i < 12; ++i )
2466     {
2467       const _Link& srcLink = other._hexLinks[ i ];
2468       _Link&       tgtLink = this->_hexLinks[ i ];
2469       tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2470       tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2471     }
2472
2473     for ( int i = 0; i < 6; ++i )
2474     {
2475       const _Face& srcQuad = other._hexQuads[ i ];
2476       _Face&       tgtQuad = this->_hexQuads[ i ];
2477       tgtQuad._name = srcQuad._name;
2478       tgtQuad._links.resize(4);
2479       for ( int j = 0; j < 4; ++j )
2480       {
2481         const _OrientedLink& srcLink = srcQuad._links[ j ];
2482         _OrientedLink&       tgtLink = tgtQuad._links[ j ];
2483         tgtLink._reverse = srcLink._reverse;
2484         tgtLink._link    = _hexLinks + ( srcLink._link - other._hexLinks );
2485       }
2486     }
2487     
2488     if (SALOME::VerbosityActivated())
2489       _cellID = cellID;
2490   }
2491
2492   //================================================================================
2493   /*!
2494    * \brief Return IDs of SOLIDs interfering with this Hexahedron
2495    */
2496   size_t Hexahedron::getSolids( TGeomID ids[] )
2497   {
2498     if ( _grid->_geometry.IsOneSolid() )
2499     {
2500       ids[0] = _grid->GetSolid()->ID();
2501       return 1;
2502     }
2503     // count intersection points belonging to each SOLID
2504     TID2Nb id2NbPoints;
2505     id2NbPoints.reserve( 3 );
2506
2507     _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2508     for ( int iN = 0; iN < 8; ++iN )
2509     {
2510       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _grid->_nodeShift[iN] ];
2511       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2512
2513       if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2514       {
2515         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2516         {
2517           const vector< TGeomID > & solidIDs =
2518             _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2519           for ( size_t i = 0; i < solidIDs.size(); ++i )
2520             insertAndIncrement( solidIDs[i], id2NbPoints );
2521         }
2522       }
2523       else if ( _hexNodes[iN]._node ) // node inside a SOLID
2524       {
2525         insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2526       }
2527     }
2528
2529     for ( int iL = 0; iL < 12; ++iL )
2530     {
2531       const _Link& link = _hexLinks[ iL ];
2532       for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2533       {
2534         for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2535         {
2536           const vector< TGeomID > & solidIDs =
2537             _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2538           for ( size_t i = 0; i < solidIDs.size(); ++i )
2539             insertAndIncrement( solidIDs[i], id2NbPoints );
2540         }
2541       }
2542     }
2543
2544     for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2545     {
2546       const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2547       for ( size_t i = 0; i < solidIDs.size(); ++i )
2548         insertAndIncrement( solidIDs[i], id2NbPoints );
2549     }
2550
2551     size_t nbSolids = 0;
2552     for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2553       if ( id2nb->second >= 3 )
2554         ids[ nbSolids++ ] = id2nb->first;
2555
2556     return nbSolids;
2557   }
2558
2559   //================================================================================
2560   /*!
2561    * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2562    */
2563   bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2564   {
2565     TID2Nb id2NbPoints;
2566     id2NbPoints.reserve( 3 );
2567
2568     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2569       for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2570       {
2571         if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2572           insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2573       }
2574     for ( size_t iN = 0; iN < 8; ++iN )
2575       if ( _hexNodes[iN]._intPoint )
2576         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2577         {
2578           if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2579             insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2580         }
2581
2582     maxFlag = IS_NOT_INTERNAL;
2583     for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2584     {
2585       TGeomID        intFace = id2nb->first;
2586       IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2587       if ( intFlag > maxFlag )
2588         maxFlag = intFlag;
2589
2590       for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2591         if ( _intNodes[iN].IsOnFace( intFace ))
2592           _intNodes[iN].SetInternal( intFlag );
2593
2594       for ( size_t iN = 0; iN < 8; ++iN )
2595         if ( _hexNodes[iN].IsOnFace( intFace ))
2596           _hexNodes[iN].SetInternal( intFlag );
2597     }
2598
2599     return maxFlag;
2600   }
2601
2602   //================================================================================
2603   /*!
2604    * \brief Return any FACE interfering with this Hexahedron
2605    */
2606   TGeomID Hexahedron::getAnyFace() const
2607   {
2608     TID2Nb id2NbPoints;
2609     id2NbPoints.reserve( 3 );
2610
2611     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2612       for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2613         insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2614
2615     for ( size_t iN = 0; iN < 8; ++iN )
2616       if ( _hexNodes[iN]._intPoint )
2617         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2618           insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2619
2620     for ( unsigned int minNb = 3; minNb > 0; --minNb )
2621       for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2622         if ( id2nb->second >= minNb )
2623           return id2nb->first;
2624
2625     return 0;
2626   }
2627
2628   //================================================================================
2629   /*!
2630    * \brief Initializes IJK by Hexahedron index
2631    */
2632   void Hexahedron::setIJK( size_t iCell )
2633   {
2634     size_t iNbCell = _grid->_coords[0].size() - 1;
2635     size_t jNbCell = _grid->_coords[1].size() - 1;
2636     _i = iCell % iNbCell;
2637     _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2638     _k = iCell / iNbCell / jNbCell;
2639   }
2640
2641   //================================================================================
2642   /*!
2643    * \brief Initializes its data by given grid cell (countered from zero)
2644    */
2645   void Hexahedron::init( size_t iCell )
2646   {
2647     setIJK( iCell );
2648     init( _i, _j, _k );
2649   }
2650
2651   //================================================================================
2652   /*!
2653    * \brief Initializes its data by given grid cell nodes and intersections
2654    */
2655   void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2656   {
2657     _i = i; _j = j; _k = k;
2658
2659     bool isCompute = solid;
2660     if ( !solid )
2661       solid = _grid->GetSolid();
2662
2663     // set nodes of grid to nodes of the hexahedron and
2664     // count nodes at hexahedron corners located IN and ON geometry
2665     _nbCornerNodes = _nbBndNodes = 0;
2666     _origNodeInd   = _grid->NodeIndex( i,j,k );
2667     for ( int iN = 0; iN < 8; ++iN )
2668     {
2669       _hexNodes[iN]._isInternalFlags = 0;
2670
2671       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _grid->_nodeShift[iN] ];
2672       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2673
2674       if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2675         _hexNodes[iN]._node = 0;
2676       if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2677         _hexNodes[iN]._intPoint = 0;
2678
2679       _nbCornerNodes += bool( _hexNodes[iN]._node );
2680       _nbBndNodes    += bool( _hexNodes[iN]._intPoint );
2681     }
2682     _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2683     _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2684     _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2685
2686     _intNodes.clear();
2687     _vIntNodes.clear();
2688
2689     if ( !isCompute )
2690       return;
2691
2692     if ( _nbFaceIntNodes + _eIntPoints.size()                  > 0 &&
2693          _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2694     {
2695       _intNodes.reserve( 3 * ( _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() ));
2696
2697       // this method can be called in parallel, so use own helper
2698       SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2699
2700       // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2701       // ---------------------------------------------------------------
2702       _Link split;
2703       for ( int iLink = 0; iLink < 12; ++iLink )
2704       {
2705         _Link& link = _hexLinks[ iLink ];
2706         link._fIntNodes.clear();
2707         link._fIntNodes.reserve( link._fIntPoints.size() );
2708         for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2709           if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2710           {
2711             _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2712             link._fIntNodes.push_back( & _intNodes.back() );
2713           }
2714
2715         link._splits.clear();
2716         split._nodes[ 0 ] = link._nodes[0];
2717         bool isOut = ( ! link._nodes[0]->Node() );
2718         bool checkTransition;
2719         for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2720         {
2721           const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2722           if ( !isGridNode ) // intersection non-coincident with a grid node
2723           {
2724             if ( split._nodes[ 0 ]->Node() && !isOut )
2725             {
2726               split._nodes[ 1 ] = link._fIntNodes[i];
2727               link._splits.push_back( split );
2728             }
2729             split._nodes[ 0 ] = link._fIntNodes[i];
2730             checkTransition = true;
2731           }
2732           else // FACE intersection coincident with a grid node (at link ends)
2733           {
2734             checkTransition = ( i == 0 && link._nodes[0]->Node() );
2735           }
2736           if ( checkTransition )
2737           {
2738             const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2739             if ( _grid->IsInternal( faceIDs.back() ))
2740               isOut = false;
2741             else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2742               isOut = isOutPoint( link, i, helper, solid );
2743             else
2744             {
2745               bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2746               switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2747               case Trans_OUT: isOut = okTransi;  break;
2748               case Trans_IN : isOut = !okTransi; break;
2749               default:
2750                 isOut = isOutPoint( link, i, helper, solid );
2751               }
2752             }
2753           }
2754         }
2755         if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2756         {
2757           split._nodes[ 1 ] = link._nodes[1];
2758           link._splits.push_back( split );
2759         }
2760       }
2761
2762       // Create _Node's at intersections with EDGEs.
2763       // --------------------------------------------
2764       // 1) add this->_eIntPoints to _Face::_eIntNodes
2765       // 2) fill _intNodes and _vIntNodes
2766       //
2767       const double tol2 = _grid->_tol * _grid->_tol * 4;
2768       int facets[3], nbFacets, subEntity;
2769
2770       for ( int iF = 0; iF < 6; ++iF )
2771         _hexQuads[ iF ]._eIntNodes.clear();
2772
2773       for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2774       {
2775         if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2776           continue;
2777         nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2778         _Node* equalNode = 0;
2779         switch( nbFacets ) {
2780         case 1: // in a _Face
2781         {
2782           _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2783           equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2784           if ( equalNode ) {
2785             equalNode->Add( _eIntPoints[ iP ] );
2786           }
2787           else {
2788             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2789             quad._eIntNodes.push_back( & _intNodes.back() );
2790           }
2791           break;
2792         }
2793         case 2: // on a _Link
2794         {
2795           _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2796           if ( link._splits.size() > 0 )
2797           {
2798             equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2799             if ( equalNode )
2800               equalNode->Add( _eIntPoints[ iP ] );
2801             else if ( link._splits.size() == 1 &&
2802                       link._splits[0]._nodes[0] &&
2803                       link._splits[0]._nodes[1] )
2804               link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2805           }
2806           //else
2807           if ( !equalNode )
2808           {
2809             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2810             bool newNodeUsed = false;
2811             for ( int iF = 0; iF < 2; ++iF )
2812             {
2813               _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2814               equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2815               if ( equalNode ) {
2816                 equalNode->Add( _eIntPoints[ iP ] );
2817               }
2818               else {
2819                 quad._eIntNodes.push_back( & _intNodes.back() );
2820                 newNodeUsed = true;
2821               }
2822             }
2823             if ( !newNodeUsed )
2824               _intNodes.pop_back();
2825           }
2826           break;
2827         }
2828         case 3: // at a corner
2829         {
2830           _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2831           if ( node.Node() )
2832           {
2833             if ( node._intPoint )
2834               node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2835           }
2836           else
2837           {
2838             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2839             for ( int iF = 0; iF < 3; ++iF )
2840             {
2841               _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2842               equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2843               if ( equalNode ) {
2844                 equalNode->Add( _eIntPoints[ iP ] );
2845               }
2846               else {
2847                 quad._eIntNodes.push_back( & _intNodes.back() );
2848               }
2849             }
2850           }
2851           break;
2852         }
2853         } // switch( nbFacets )
2854
2855         if ( nbFacets == 0 ||
2856              _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2857         {
2858           equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2859           if ( equalNode ) {
2860             equalNode->Add( _eIntPoints[ iP ] );
2861           }
2862           else if ( nbFacets == 0 ) {
2863             if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2864               _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2865             _vIntNodes.push_back( & _intNodes.back() );
2866           }
2867         }
2868       } // loop on _eIntPoints
2869     }
2870
2871     else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2872              ( !_grid->_geometry.IsOneSolid() ))
2873     {
2874       _Link split;
2875       // create sub-links (_splits) of whole links
2876       for ( int iLink = 0; iLink < 12; ++iLink )
2877       {
2878         _Link& link = _hexLinks[ iLink ];
2879         link._splits.clear();
2880         if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2881         {
2882           split._nodes[ 0 ] = link._nodes[0];
2883           split._nodes[ 1 ] = link._nodes[1];
2884           link._splits.push_back( split );
2885         }
2886       }
2887     }
2888     return;
2889
2890   } // init( _i, _j, _k )
2891
2892   //================================================================================
2893   /*!
2894    * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2895    */
2896   void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2897   {
2898     if ( !solid )
2899     {
2900       solid = _grid->GetSolid();
2901       if ( !_grid->_geometry.IsOneSolid() )
2902       {
2903         TGeomID solidIDs[20] = { 0 };
2904         size_t nbSolids = getSolids( solidIDs );
2905         if ( nbSolids > 1 )
2906         {
2907           for ( size_t i = 0; i < nbSolids; ++i )
2908           {
2909             solid = _grid->GetSolid( solidIDs[i] );
2910             computeElements( solid, i );
2911             if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2912               _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2913           }
2914           return;
2915         }
2916         solid = _grid->GetSolid( solidIDs[0] );
2917       }
2918     }
2919
2920     init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2921
2922     int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2923     if ( _nbCornerNodes + nbIntersections < 4 )
2924       return;
2925
2926     if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2927       return; // cell is in a hole
2928
2929     IsInternalFlag intFlag = IS_NOT_INTERNAL;
2930     if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2931     {
2932       for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2933       {
2934         if ( compute( solid, intFlag ))
2935           _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2936       }
2937     }
2938     else
2939     {
2940       if ( solidIndex >= 0 )
2941         intFlag = IS_CUT_BY_INTERNAL_FACE;
2942
2943       compute( solid, intFlag );
2944     }
2945   }
2946
2947   //================================================================================
2948   /*!
2949    * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2950    */
2951   bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2952   {
2953     _polygons.clear();
2954     _polygons.reserve( 20 );
2955
2956     for ( int iN = 0; iN < 8; ++iN )
2957       _hexNodes[iN]._usedInFace = 0;
2958
2959     if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2960       preventVolumesOverlapping();
2961
2962     std::set< TGeomID > concaveFaces; // to avoid connecting nodes laying on them
2963
2964     if ( solid->HasConcaveVertex() )
2965     {
2966       for ( const E_IntersectPoint* ip : _eIntPoints )
2967       {
2968         if ( const ConcaveFace* cf = solid->GetConcave( ip->_shapeID ))
2969           if ( this->hasEdgesAround( cf ))
2970             concaveFaces.insert( cf->_concaveFace );
2971       }
2972       if ( concaveFaces.empty() || concaveFaces.size() * 3  < _eIntPoints.size() )
2973         for ( const _Node& hexNode: _hexNodes )
2974         {
2975           if ( hexNode._node && hexNode._intPoint && hexNode._intPoint->_faceIDs.size() >= 3 )
2976             if ( const ConcaveFace* cf = solid->GetConcave( hexNode._node->GetShapeID() ))
2977               if ( this->hasEdgesAround( cf ))
2978                 concaveFaces.insert( cf->_concaveFace );
2979         }
2980     }
2981
2982     // Create polygons from quadrangles
2983     // --------------------------------
2984
2985     vector< _OrientedLink > splits;
2986     vector<_Node*>          chainNodes;
2987     _Face*                  coplanarPolyg;
2988
2989     const bool hasEdgeIntersections = !_eIntPoints.empty();
2990     const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
2991
2992     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2993     {
2994       _Face& quad = _hexQuads[ iF ] ;
2995
2996       _polygons.resize( _polygons.size() + 1 );
2997       _Face* polygon = &_polygons.back();
2998       polygon->_polyLinks.reserve( 20 );
2999       polygon->_name = quad._name;
3000
3001       splits.clear();
3002       for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
3003         for ( size_t iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
3004           splits.push_back( quad._links[ iE ].ResultLink( iS ));
3005
3006       if ( splits.size() == 4 &&
3007            isQuadOnFace( iF )) // check if a quad on FACE is not split
3008       {
3009         polygon->_links.swap( splits );
3010         continue; // goto the next quad
3011       }
3012
3013       // add splits of links to a polygon and add _polyLinks to make
3014       // polygon's boundary closed
3015
3016       int nbSplits = splits.size();
3017       if (( nbSplits == 1 ) &&
3018           ( quad._eIntNodes.empty() ||
3019             splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
3020         //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
3021         nbSplits = 0;
3022
3023       for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3024         if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
3025           quad._eIntNodes[ iP ]->_usedInFace = 0;
3026
3027       size_t nbUsedEdgeNodes = 0;
3028       _Face* prevPolyg = 0; // polygon previously created from this quad
3029
3030       while ( nbSplits > 0 )
3031       {
3032         size_t iS = 0;
3033         while ( !splits[ iS ] )
3034           ++iS;
3035
3036         if ( !polygon->_links.empty() )
3037         {
3038           _polygons.resize( _polygons.size() + 1 );
3039           polygon = &_polygons.back();
3040           polygon->_polyLinks.reserve( 20 );
3041           polygon->_name = quad._name;
3042         }
3043         polygon->_links.push_back( splits[ iS ] );
3044         splits[ iS++ ]._link = 0;
3045         --nbSplits;
3046
3047         _Node* nFirst = polygon->_links.back().FirstNode();
3048         _Node *n1,*n2 = polygon->_links.back().LastNode();
3049         for ( ; nFirst != n2 && iS < splits.size(); ++iS )
3050         {
3051           _OrientedLink& split = splits[ iS ];
3052           if ( !split ) continue;
3053
3054           n1 = split.FirstNode();
3055           if ( n1 == n2 &&
3056                n1->_intPoint &&
3057                (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
3058                 ( n1->_isInternalFlags )))
3059           {
3060             // n1 is at intersection with EDGE
3061             if ( findChainOnEdge( splits, polygon->_links.back(), split, concaveFaces,
3062                                   iS, quad, chainNodes ))
3063             {
3064               for ( size_t i = 1; i < chainNodes.size(); ++i )
3065                 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3066               if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
3067               {
3068                 prevPolyg = polygon;
3069                 n2 = chainNodes.back();
3070                 continue;
3071               }
3072             }
3073           }
3074           else if ( n1 != n2 )
3075           {
3076             // try to connect to intersections with EDGEs
3077             if ( quad._eIntNodes.size() > nbUsedEdgeNodes  &&
3078                  findChain( n2, n1, quad, chainNodes ))
3079             {
3080               for ( size_t i = 1; i < chainNodes.size(); ++i )
3081               {
3082                 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
3083                 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
3084               }
3085               if ( chainNodes.back() != n1 )
3086               {
3087                 n2 = chainNodes.back();
3088                 --iS;
3089                 continue;
3090               }
3091             }
3092             // try to connect to a split ending on the same FACE
3093             else
3094             {
3095               _OrientedLink foundSplit;
3096               for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
3097                 if (( foundSplit = splits[ i ]) &&
3098                     ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
3099                 {
3100                   iS = i - 1;
3101                 }
3102                 else
3103                 {
3104                   foundSplit._link = 0;
3105                 }
3106               if ( foundSplit )
3107               {
3108                 if ( n2 != foundSplit.FirstNode() )
3109                 {
3110                   polygon->AddPolyLink( n2, foundSplit.FirstNode() );
3111                   n2 = foundSplit.FirstNode();
3112                 }
3113                 continue;
3114               }
3115               else
3116               {
3117                 if ( n2->IsLinked( nFirst->_intPoint ))
3118                   break;
3119                 polygon->AddPolyLink( n2, n1, prevPolyg );
3120               }
3121             }
3122           } // if ( n1 != n2 )
3123
3124           polygon->_links.push_back( split );
3125           split._link = 0;
3126           --nbSplits;
3127           n2 = polygon->_links.back().LastNode();
3128
3129         } // loop on splits
3130
3131         if ( nFirst != n2 ) // close a polygon
3132         {
3133           if ( !findChain( n2, nFirst, quad, chainNodes ))
3134           {
3135             if ( !closePolygon( polygon, chainNodes ))
3136               if ( !isImplementEdges() )
3137                 chainNodes.push_back( nFirst );
3138           }
3139           for ( size_t i = 1; i < chainNodes.size(); ++i )
3140           {
3141             polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3142             nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
3143           }
3144         }
3145
3146         if ( polygon->_links.size() < 3 && nbSplits > 0 )
3147         {
3148           polygon->_polyLinks.clear();
3149           polygon->_links.clear();
3150         }
3151       } // while ( nbSplits > 0 )
3152
3153       if ( polygon->_links.size() < 3 )
3154       {
3155         _polygons.pop_back();
3156       }
3157     }  // loop on 6 hexahedron sides
3158
3159     // Create polygons closing holes in a polyhedron
3160     // ----------------------------------------------
3161
3162     // clear _usedInFace
3163     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
3164       _intNodes[ iN ]._usedInFace = 0;
3165
3166     // add polygons to their links and mark used nodes
3167     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3168     {
3169       _Face& polygon = _polygons[ iP ];
3170       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3171       {
3172         polygon._links[ iL ].AddFace( &polygon );
3173         polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
3174       }
3175     }
3176     // find free links
3177     vector< _OrientedLink* > freeLinks;
3178     freeLinks.reserve(20);
3179     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3180     {
3181       _Face& polygon = _polygons[ iP ];
3182       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3183         if ( polygon._links[ iL ].NbFaces() < 2 )
3184           freeLinks.push_back( & polygon._links[ iL ]);
3185     }
3186     int nbFreeLinks = freeLinks.size();
3187     if ( nbFreeLinks == 1 ) return false;
3188
3189     // put not used intersection nodes to _vIntNodes
3190     int nbVertexNodes = 0; // nb not used vertex nodes
3191     {
3192       for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3193         nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
3194
3195       const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
3196       for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
3197       {
3198         if ( _intNodes[ iN ].IsUsedInFace() ) continue;
3199         if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
3200         _Node* equalNode =
3201           findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
3202         if ( !equalNode )
3203         {
3204           _vIntNodes.push_back( &_intNodes[ iN ]);
3205           ++nbVertexNodes;
3206         }
3207       }
3208     }
3209
3210     std::set<TGeomID> usedFaceIDs;
3211     std::vector< TGeomID > faces;
3212     TGeomID curFace = 0;
3213     const size_t nbQuadPolygons = _polygons.size();
3214     E_IntersectPoint ipTmp;
3215     std::map< TGeomID, std::vector< const B_IntersectPoint* > > tmpAddedFace; // face added to _intPoint
3216
3217     // create polygons by making closed chains of free links
3218     size_t iPolygon = _polygons.size();
3219     while ( nbFreeLinks > 0 )
3220     {
3221       if ( iPolygon == _polygons.size() )
3222       {
3223         _polygons.resize( _polygons.size() + 1 );
3224         _polygons[ iPolygon ]._polyLinks.reserve( 20 );
3225         _polygons[ iPolygon ]._links.reserve( 20 );
3226       }
3227       _Face& polygon = _polygons[ iPolygon ];
3228
3229       _OrientedLink* curLink = 0;
3230       _Node*         curNode;
3231       if (( !hasEdgeIntersections ) ||
3232           ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
3233       {
3234         // get a remaining link to start from
3235         for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3236           if (( curLink = freeLinks[ iL ] ))
3237             freeLinks[ iL ] = 0;
3238         polygon._links.push_back( *curLink );
3239         --nbFreeLinks;
3240         do
3241         {
3242           // find all links connected to curLink
3243           curNode = curLink->FirstNode();
3244           curLink = 0;
3245           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3246             if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
3247             {
3248               curLink = freeLinks[ iL ];
3249               freeLinks[ iL ] = 0;
3250               --nbFreeLinks;
3251               polygon._links.push_back( *curLink );
3252             }
3253         } while ( curLink );
3254       }
3255       else // there are intersections with EDGEs
3256       {
3257         // get a remaining link to start from, one lying on minimal nb of FACEs
3258         {
3259           typedef pair< TGeomID, int > TFaceOfLink;
3260           TFaceOfLink faceOfLink( -1, -1 );
3261           TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
3262           for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
3263             if ( freeLinks[ iL ] )
3264             {
3265               faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
3266               if ( faces.size() == 1 )
3267               {
3268                 faceOfLink = TFaceOfLink( faces[0], iL );
3269                 if ( !freeLinks[ iL ]->HasEdgeNodes() )
3270                   break;
3271                 facesOfLink[0] = faceOfLink;
3272               }
3273               else if ( facesOfLink[0].first < 0 )
3274               {
3275                 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
3276                 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
3277               }
3278             }
3279           for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
3280             faceOfLink = facesOfLink[i];
3281
3282           if ( faceOfLink.first < 0 ) // all faces used
3283           {
3284             for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
3285               if (( curLink = freeLinks[ iL ]))
3286               {
3287                 faceOfLink.first = 
3288                   curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
3289                 faceOfLink.second = iL;
3290               }
3291             usedFaceIDs.clear();
3292           }
3293           curFace = faceOfLink.first;
3294           curLink = freeLinks[ faceOfLink.second ];
3295           freeLinks[ faceOfLink.second ] = 0;
3296         }
3297         usedFaceIDs.insert( curFace );
3298         polygon._links.push_back( *curLink );
3299         --nbFreeLinks;
3300
3301         // find all links lying on a curFace
3302         do
3303         {
3304           // go forward from curLink
3305           curNode = curLink->LastNode();
3306           curLink = 0;
3307           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3308             if ( freeLinks[ iL ] &&
3309                  freeLinks[ iL ]->FirstNode() == curNode &&
3310                  freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3311             {
3312               curLink = freeLinks[ iL ];
3313               freeLinks[ iL ] = 0;
3314               polygon._links.push_back( *curLink );
3315               --nbFreeLinks;
3316             }
3317         } while ( curLink );
3318
3319         std::reverse( polygon._links.begin(), polygon._links.end() );
3320
3321         curLink = & polygon._links.back();
3322         do
3323         {
3324           // go backward from curLink
3325           curNode = curLink->FirstNode();
3326           curLink = 0;
3327           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3328             if ( freeLinks[ iL ] &&
3329                  freeLinks[ iL ]->LastNode() == curNode &&
3330                  freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3331             {
3332               curLink = freeLinks[ iL ];
3333               freeLinks[ iL ] = 0;
3334               polygon._links.push_back( *curLink );
3335               --nbFreeLinks;
3336             }
3337         } while ( curLink );
3338
3339         curNode = polygon._links.back().FirstNode();
3340
3341         if ( polygon._links[0].LastNode() != curNode )
3342         {
3343           if ( nbVertexNodes > 0 )
3344           {
3345             // add links with _vIntNodes if not already used
3346             chainNodes.clear();
3347             for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3348               if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3349                    _vIntNodes[ iN ]->IsOnFace( curFace ))
3350               {
3351                 _vIntNodes[ iN ]->_usedInFace = &polygon;
3352                 chainNodes.push_back( _vIntNodes[ iN ] );
3353               }
3354             if ( chainNodes.size() > 1 &&
3355                  curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3356             {
3357               sortVertexNodes( chainNodes, curNode, curFace );
3358             }
3359             for ( size_t i = 0; i < chainNodes.size(); ++i )
3360             {
3361               polygon.AddPolyLink( chainNodes[ i ], curNode );
3362               curNode = chainNodes[ i ];
3363               freeLinks.push_back( &polygon._links.back() );
3364               ++nbFreeLinks;
3365             }
3366             nbVertexNodes -= chainNodes.size();
3367           }
3368           // if ( polygon._links.size() > 1 )
3369           {
3370             polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3371             freeLinks.push_back( &polygon._links.back() );
3372             ++nbFreeLinks;
3373           }
3374         }
3375       } // if there are intersections with EDGEs
3376
3377       if ( polygon._links.size() < 2 ||
3378            polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3379       {
3380         _polygons.clear();
3381         break; // closed polygon not found -> invalid polyhedron
3382       }
3383
3384       if ( polygon._links.size() == 2 )
3385       {
3386         if ( freeLinks.back() == &polygon._links.back() )
3387         {
3388           freeLinks.pop_back();
3389           --nbFreeLinks;
3390         }
3391         if ( polygon._links.front().NbFaces() > 0 )
3392           polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3393         if ( polygon._links.back().NbFaces() > 0 )
3394           polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3395
3396         if ( iPolygon == _polygons.size()-1 )
3397           _polygons.pop_back();
3398       }
3399       else // polygon._links.size() >= 2
3400       {
3401         // add polygon to its links
3402         for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3403         {
3404           polygon._links[ iL ].AddFace( &polygon );
3405           polygon._links[ iL ].Reverse();
3406         }
3407         if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3408         {
3409           // check that a polygon does not lie on a hexa side
3410           coplanarPolyg = 0;
3411           for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3412           {
3413             if ( polygon._links[ iL ].NbFaces() < 2 )
3414               continue; // it's a just added free link
3415             // look for a polygon made on a hexa side and sharing
3416             // two or more haxa links
3417             size_t iL2;
3418             coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3419             for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3420               if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3421                    !coplanarPolyg->IsPolyLink( polygon._links[ iL  ]) &&
3422                    !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3423                    coplanarPolyg < & _polygons[ nbQuadPolygons ])
3424                 break;
3425             if ( iL2 == polygon._links.size() )
3426               coplanarPolyg = 0;
3427           }
3428           if ( coplanarPolyg ) // coplanar polygon found
3429           {
3430             freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3431             nbFreeLinks -= polygon._polyLinks.size();
3432
3433             // an E_IntersectPoint used to mark nodes of coplanarPolyg
3434             // as lying on curFace while they are not at intersection with geometry
3435             ipTmp._faceIDs.resize(1);
3436             ipTmp._faceIDs[0] = curFace;
3437
3438             // fill freeLinks with links not shared by coplanarPolyg and polygon
3439             for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3440               if ( polygon._links[ iL ]._link->_faces[1] &&
3441                    polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3442               {
3443                 _Face* p = polygon._links[ iL ]._link->_faces[0];
3444                 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3445                   if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3446                   {
3447                     freeLinks.push_back( & p->_links[ iL2 ] );
3448                     ++nbFreeLinks;
3449                     freeLinks.back()->RemoveFace( &polygon );
3450                     break;
3451                   }
3452               }
3453             for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3454               if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3455                    coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3456               {
3457                 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3458                 if ( p == coplanarPolyg )
3459                   p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3460                 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3461                   if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3462                   {
3463                     // set links of coplanarPolyg in place of used freeLinks
3464                     // to re-create coplanarPolyg next
3465                     size_t iL3 = 0;
3466                     for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3467                     if ( iL3 < freeLinks.size() )
3468                       freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3469                     else
3470                       freeLinks.push_back( & p->_links[ iL2 ] );
3471                     ++nbFreeLinks;
3472                     freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3473                     //  mark nodes of coplanarPolyg as lying on curFace
3474                     for ( int iN = 0; iN < 2; ++iN )
3475                     {
3476                       _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3477                       bool added = false;
3478                       if ( n->_intPoint ) added = n->_intPoint->Add( ipTmp._faceIDs );
3479                       else                        n->_intPoint = &ipTmp;
3480                       if ( added )
3481                         tmpAddedFace[ ipTmp._faceIDs[0] ].push_back( n->_intPoint );
3482                     }
3483                     break;
3484                   }
3485               }
3486             // set coplanarPolyg to be re-created next
3487             for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3488               if ( coplanarPolyg == & _polygons[ iP ] )
3489               {
3490                 iPolygon = iP;
3491                 _polygons[ iPolygon ]._links.clear();
3492                 _polygons[ iPolygon ]._polyLinks.clear();
3493                 break;
3494               }
3495             _polygons.pop_back();
3496             usedFaceIDs.erase( curFace );
3497             continue;
3498           } // if ( coplanarPolyg )
3499         } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3500
3501         iPolygon = _polygons.size();
3502
3503       } // end of case ( polygon._links.size() > 2 )
3504     } // while ( nbFreeLinks > 0 )
3505
3506     for ( auto & face_ip : tmpAddedFace )
3507     {
3508       curFace = face_ip.first;
3509       for ( const B_IntersectPoint* ip : face_ip.second )
3510       {
3511         auto it = std::find( ip->_faceIDs.begin(), ip->_faceIDs.end(), curFace );
3512         if ( it != ip->_faceIDs.end() )
3513           ip->_faceIDs.erase( it );
3514       }
3515     }
3516
3517     if ( _polygons.size() < 3 )
3518       return false;
3519
3520     // check volume size
3521     double volSize = 0;
3522     _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE, volSize );
3523
3524     for ( size_t i = 0; i < 8; ++i )
3525       if ( _hexNodes[ i ]._intPoint == &ipTmp )
3526         _hexNodes[ i ]._intPoint = 0;
3527
3528     if ( _hasTooSmall )
3529       return false; // too small volume
3530
3531
3532     // Try to find out names of no-name polygons (issue # 19887)
3533     if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3534     {
3535       gp_XYZ uvwCenter =
3536         0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3537         0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3538         0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3539       for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3540       {
3541         _Face& face = _polygons[ i ];
3542         Bnd_Box bb;
3543         gp_Pnt uvw;
3544         for ( size_t iL = 0; iL < face._links.size(); ++iL )
3545         {
3546           _Node* n = face._links[ iL ].FirstNode();
3547           gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3548           _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3549           bb.Add( uvw );
3550         }
3551         gp_Pnt pMin = bb.CornerMin();
3552         if ( bb.IsXThin( _grid->_tol ))
3553           face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3554         else if ( bb.IsYThin( _grid->_tol ))
3555           face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3556         else if ( bb.IsZThin( _grid->_tol ))
3557           face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3558       }
3559     }
3560
3561     _volumeDefs._nodes.clear();
3562     _volumeDefs._quantities.clear();
3563     _volumeDefs._names.clear();
3564     // create a classic cell if possible
3565
3566     int nbPolygons = 0;
3567     for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3568       nbPolygons += (_polygons[ iF ]._links.size() > 2 );
3569
3570     //const int nbNodes = _nbCornerNodes + nbIntersections;
3571     int nbNodes = 0;
3572     for ( size_t i = 0; i < 8; ++i )
3573       nbNodes += _hexNodes[ i ].IsUsedInFace();
3574     for ( size_t i = 0; i < _intNodes.size(); ++i )
3575       nbNodes += _intNodes[ i ].IsUsedInFace();
3576
3577     bool isClassicElem = false;
3578     if (      nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3579     else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3580     else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3581     else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3582     if ( !isClassicElem )
3583     {
3584       for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3585       {
3586         const size_t nbLinks = _polygons[ iF ]._links.size();
3587         if ( nbLinks < 3 ) continue;
3588         _volumeDefs._quantities.push_back( nbLinks );
3589         _volumeDefs._names.push_back( _polygons[ iF ]._name );
3590         for ( size_t iL = 0; iL < nbLinks; ++iL )
3591           _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3592       }
3593     }
3594     _volumeDefs._solidID = solid->ID();
3595     _volumeDefs._size    = volSize;
3596
3597     return !_volumeDefs._nodes.empty();
3598   }
3599   //================================================================================
3600   /*!
3601    * \brief Create elements in the mesh
3602    */
3603   int Hexahedron::MakeElements(SMESH_MesherHelper&                      helper,
3604                                const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3605   {
3606     SMESHDS_Mesh* mesh = helper.GetMeshDS();
3607
3608     CellsAroundLink c( _grid, 0 );
3609     const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3610     vector< Hexahedron* > allHexa( nbGridCells, 0 );
3611     int nbIntHex = 0;
3612
3613     // set intersection nodes from GridLine's to links of allHexa
3614     int i,j,k, cellIndex, iLink;
3615     for ( int iDir = 0; iDir < 3; ++iDir )
3616     {
3617       // loop on GridLine's parallel to iDir
3618       LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3619       CellsAroundLink fourCells( _grid, iDir );
3620       for ( ; lineInd.More(); ++lineInd )
3621       {
3622         GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3623         multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3624         for ( ; ip != line._intPoints.end(); ++ip )
3625         {
3626           // if ( !ip->_node ) continue; // intersection at a grid node
3627           lineInd.SetIndexOnLine( ip->_indexOnLine );
3628           fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3629           for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3630           {
3631             if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3632               continue;
3633             Hexahedron *& hex = allHexa[ cellIndex ];
3634             if ( !hex)
3635             {
3636               hex = new Hexahedron( *this, i, j, k, cellIndex );
3637               ++nbIntHex;
3638             }
3639             hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3640             hex->_nbFaceIntNodes += bool( ip->_node );
3641           }
3642         }
3643       }
3644     }
3645
3646     // implement geom edges into the mesh
3647     addEdges( helper, allHexa, edge2faceIDsMap );
3648
3649     // add not split hexahedra to the mesh
3650     int nbAdded = 0;
3651     TGeomID solidIDs[20];
3652     vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3653     vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3654     for ( size_t i = 0; i < allHexa.size(); ++i )
3655     {
3656       // initialize this by not cut allHexa[ i ]
3657       Hexahedron * & hex = allHexa[ i ];
3658       if ( hex ) // split hexahedron
3659       {
3660         intHexa.push_back( hex );
3661         if ( hex->_nbFaceIntNodes > 0 ||
3662              hex->_eIntPoints.size() > 0 ||
3663              hex->getSolids( solidIDs ) > 1 )
3664           continue; // treat intersected hex later in parallel
3665         this->init( hex->_i, hex->_j, hex->_k );
3666       }
3667       else
3668       {
3669         this->init( i ); // == init(i,j,k)
3670       }
3671       if (( _nbCornerNodes == 8 ) &&
3672           ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3673       {
3674         // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3675         SMDS_MeshElement* el =
3676           mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3677                            _hexNodes[3].Node(), _hexNodes[1].Node(),
3678                            _hexNodes[4].Node(), _hexNodes[6].Node(),
3679                            _hexNodes[7].Node(), _hexNodes[5].Node() );
3680         TGeomID solidID = 0;
3681         if ( _nbBndNodes < _nbCornerNodes )
3682         {
3683           for ( int iN = 0; iN < 8 &&  !solidID; ++iN )
3684             if ( !_hexNodes[iN]._intPoint ) // no intersection
3685               solidID = _hexNodes[iN].Node()->GetShapeID();
3686         }
3687         else
3688         {
3689           getSolids( solidIDs );
3690           solidID = solidIDs[0];
3691         }
3692         mesh->SetMeshElementOnShape( el, solidID );
3693         ++nbAdded;
3694         if ( hex )
3695           intHexa.pop_back();
3696         if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3697         {
3698           boundaryVolumes.push_back( el );
3699           el->setIsMarked( true );
3700         }
3701       }
3702       else if ( _nbCornerNodes > 3 && !hex )
3703       {
3704         // all intersections of hex with geometry are at grid nodes
3705         hex = new Hexahedron( *this, _i, _j, _k, i );
3706         intHexa.push_back( hex );
3707       }
3708     }
3709
3710     // compute definitions of volumes resulted from hexadron intersection
3711 #ifdef WITH_TBB
3712     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3713                         ParallelHexahedron( intHexa ),
3714                         tbb::simple_partitioner()); // computeElements() is called here
3715 #else
3716     for ( size_t i = 0; i < intHexa.size(); ++i )
3717       if ( Hexahedron * hex = intHexa[ i ] )
3718         hex->computeElements();
3719 #endif
3720
3721     // simplify polyhedrons
3722     if ( _grid->IsToRemoveExcessEntities() )
3723     {
3724       for ( size_t i = 0; i < intHexa.size(); ++i )
3725         if ( Hexahedron * hex = intHexa[ i ] )
3726           hex->removeExcessSideDivision( allHexa );
3727
3728       for ( size_t i = 0; i < intHexa.size(); ++i )
3729         if ( Hexahedron * hex = intHexa[ i ] )
3730           hex->removeExcessNodes( allHexa );
3731     }
3732
3733     // add volumes
3734     for ( size_t i = 0; i < intHexa.size(); ++i )
3735       if ( Hexahedron * hex = intHexa[ i ] )
3736         nbAdded += hex->addVolumes( helper );
3737
3738     // fill boundaryVolumes with volumes neighboring too small skipped volumes
3739     if ( _grid->_toCreateFaces )
3740     {
3741       for ( size_t i = 0; i < intHexa.size(); ++i )
3742         if ( Hexahedron * hex = intHexa[ i ] )
3743           hex->getBoundaryElems( boundaryVolumes );
3744     }
3745
3746     // merge nodes on outer sub-shapes with pre-existing ones
3747     TopTools_DataMapIteratorOfDataMapOfShapeInteger s2nIt( _grid->_geometry._shape2NbNodes );
3748     for ( ; s2nIt.More(); s2nIt.Next() )
3749       if ( s2nIt.Value() > 0 )
3750         if ( SMESHDS_SubMesh* sm = mesh->MeshElements( s2nIt.Key() ))
3751         {
3752           TIDSortedNodeSet smNodes( SMDS_MeshElement::iterator( sm->GetNodes() ),
3753                                     SMDS_MeshElement::iterator() );
3754           SMESH_MeshEditor::TListOfListOfNodes equalNodes;
3755           SMESH_MeshEditor editor( helper.GetMesh() );
3756           editor.FindCoincidentNodes( smNodes, 10 * _grid->_tol, equalNodes,
3757                                       /*SeparateCornersAndMedium =*/ false);
3758           if ((int) equalNodes.size() <= s2nIt.Value() )
3759             editor.MergeNodes( equalNodes );
3760         }
3761
3762     // create boundary mesh faces
3763     addFaces( helper, boundaryVolumes );
3764
3765     // create mesh edges
3766     addSegments( helper, edge2faceIDsMap );
3767
3768     for ( size_t i = 0; i < allHexa.size(); ++i )
3769       if ( allHexa[ i ] )
3770         delete allHexa[ i ];
3771
3772     return nbAdded;
3773   }
3774
3775   //================================================================================
3776   /*!
3777    * \brief Implements geom edges into the mesh
3778    */
3779   void Hexahedron::addEdges(SMESH_MesherHelper&                      helper,
3780                             vector< Hexahedron* >&                   hexes,
3781                             const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3782   {
3783     if ( edge2faceIDsMap.empty() ) return;
3784
3785     // Prepare planes for intersecting with EDGEs
3786     GridPlanes pln[3];
3787     {
3788       for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3789       {
3790         GridPlanes& planes = pln[ iDirZ ];
3791         int iDirX = ( iDirZ + 1 ) % 3;
3792         int iDirY = ( iDirZ + 2 ) % 3;
3793         planes._zNorm  = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3794         planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3795         planes._zProjs [0] = 0;
3796         const double       zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3797         const vector< double > & u = _grid->_coords[ iDirZ ];
3798         for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3799         {
3800           planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3801         }
3802       }
3803     }
3804     const double deflection = _grid->_minCellSize / 20.;
3805     const double tol        = _grid->_tol;
3806     E_IntersectPoint ip;
3807
3808     TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3809
3810     // Intersect EDGEs with the planes
3811     map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3812     for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3813     {
3814       const TGeomID  edgeID = e2fIt->first;
3815       const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3816       BRepAdaptor_Curve curve( E );
3817       TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3818       TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3819
3820       ip._faceIDs = e2fIt->second;
3821       ip._shapeID = edgeID;
3822
3823       bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3824       if ( isInternal )
3825       {
3826         intEdgeIDs.Add( edgeID );
3827         intEdgeIDs.Add( _grid->ShapeID( v1 ));
3828         intEdgeIDs.Add( _grid->ShapeID( v2 ));
3829       }
3830
3831       // discretize the EDGE
3832       GCPnts_UniformDeflection discret( curve, deflection, true );
3833       if ( !discret.IsDone() || discret.NbPoints() < 2 )
3834         continue;
3835
3836       // perform intersection
3837       E_IntersectPoint* eip, *vip = 0;
3838       for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3839       {
3840         GridPlanes& planes = pln[ iDirZ ];
3841         int      iDirX = ( iDirZ + 1 ) % 3;
3842         int      iDirY = ( iDirZ + 2 ) % 3;
3843         double    xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3844         double    yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3845         double    zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3846         int dIJK[3], d000[3] = { 0,0,0 };
3847         double o[3] = { _grid->_coords[0][0],
3848                         _grid->_coords[1][0],
3849                         _grid->_coords[2][0] };
3850
3851         // locate the 1st point of a segment within the grid
3852         gp_XYZ p1     = discret.Value( 1 ).XYZ();
3853         double u1     = discret.Parameter( 1 );
3854         double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3855
3856         _grid->ComputeUVW( p1, ip._uvw );
3857         int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3858         int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3859         int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3860         locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3861         locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3862         locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3863
3864         int ijk[3]; // grid index where a segment intersects a plane
3865         ijk[ iDirX ] = iX1;
3866         ijk[ iDirY ] = iY1;
3867         ijk[ iDirZ ] = iZ1;
3868
3869         // add the 1st vertex point to a hexahedron
3870         if ( iDirZ == 0 )
3871         {
3872           ip._point   = p1;
3873           ip._shapeID = _grid->ShapeID( v1 );
3874           vip = _grid->Add( ip );
3875           _grid->UpdateFacesOfVertex( *vip, v1 );
3876           if ( isInternal )
3877             vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3878           if ( !addIntersection( vip, hexes, ijk, d000 ))
3879             _grid->Remove( vip );
3880           ip._shapeID = edgeID;
3881         }
3882         for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3883         {
3884           // locate the 2nd point of a segment within the grid
3885           gp_XYZ p2     = discret.Value( iP ).XYZ();
3886           double u2     = discret.Parameter( iP );
3887           double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3888           int    iZ2    = iZ1;
3889           if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3890           {
3891             locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3892
3893             // treat intersections with planes between 2 end points of a segment
3894             int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3895             int iZ = iZ1 + ( iZ1 < iZ2 );
3896             for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3897             {
3898               ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3899                                         planes._zProjs[ iZ ],
3900                                         curve, planes._zNorm, _grid->_origin );
3901               _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3902               locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3903               locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3904               ijk[ iDirZ ] = iZ;
3905
3906               // add ip to hex "above" the plane
3907               eip = _grid->Add( ip );
3908               if ( isInternal )
3909                 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3910               dIJK[ iDirZ ] = 0;
3911               bool added = addIntersection( eip, hexes, ijk, dIJK);
3912
3913               // add ip to hex "below" the plane
3914               ijk[ iDirZ ] = iZ-1;
3915               if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3916                    !added )
3917                 _grid->Remove( eip );
3918             }
3919           }
3920           iZ1    = iZ2;
3921           p1     = p2;
3922           u1     = u2;
3923           zProj1 = zProj2;
3924         }
3925         // add the 2nd vertex point to a hexahedron
3926         if ( iDirZ == 0 )
3927         {
3928           ip._point   = p1;
3929           ip._shapeID = _grid->ShapeID( v2 );
3930           _grid->ComputeUVW( p1, ip._uvw );
3931           locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3932           locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3933           ijk[ iDirZ ] = iZ1;
3934           bool sameV = ( v1.IsSame( v2 ));
3935           if ( !sameV )
3936           {
3937             vip = _grid->Add( ip );
3938             _grid->UpdateFacesOfVertex( *vip, v2 );
3939             if ( isInternal )
3940               vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3941           }
3942           if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3943             _grid->Remove( vip );
3944           ip._shapeID = edgeID;
3945         }
3946       } // loop on 3 grid directions
3947     } // loop on EDGEs
3948
3949
3950     if ( intEdgeIDs.Size() > 0 )
3951       cutByExtendedInternal( hexes, intEdgeIDs );
3952
3953     return;
3954   }
3955
3956   //================================================================================
3957   /*!
3958    * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3959    *        Cut them by extended INTERNAL FACE.
3960    */
3961   void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3962                                           const TColStd_MapOfInteger& intEdgeIDs )
3963   {
3964     IntAna_IntConicQuad intersection;
3965     SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3966     const double tol2 = _grid->_tol * _grid->_tol;
3967
3968     for ( size_t iH = 0; iH < hexes.size(); ++iH )
3969     {
3970       Hexahedron* hex = hexes[ iH ];
3971       if ( !hex || hex->_eIntPoints.size() < 2 )
3972         continue;
3973       if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3974         continue;
3975
3976       // get 3 points on INTERNAL FACE to construct a cutting plane
3977       gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3978       gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3979       gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3980
3981       gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3982       gp_Pln pln;
3983       try {
3984         pln = gp_Pln( p1, norm );
3985       }
3986       catch(...)
3987       {
3988         continue;
3989       }
3990
3991       TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3992       TGeomID   solidID = _grid->GetSolid( intFaceID )->ID();
3993
3994       // cut links by the plane
3995       //bool isCut = false;
3996       for ( int iLink = 0; iLink < 12; ++iLink )
3997       {
3998         _Link& link = hex->_hexLinks[ iLink ];
3999         if ( !link._fIntPoints.empty() )
4000         {
4001           // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
4002           //   isCut = true;
4003           continue; // already cut link
4004         }
4005         if ( !link._nodes[0]->Node() ||
4006              !link._nodes[1]->Node() )
4007           continue; // outside link
4008
4009         if ( link._nodes[0]->IsOnFace( intFaceID ))
4010         {
4011           if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4012             if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2  ||
4013                  p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
4014               link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4015           continue; // link is cut by FACE being "extended"
4016         }
4017         if ( link._nodes[1]->IsOnFace( intFaceID ))
4018         {
4019           if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4020             if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2  ||
4021                  p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
4022               link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4023           continue; // link is cut by FACE being "extended"
4024         }
4025         gp_Pnt p4 = link._nodes[0]->Point();
4026         gp_Pnt p5 = link._nodes[1]->Point();
4027         gp_Lin line( p4, gp_Vec( p4, p5 ));
4028
4029         intersection.Perform( line, pln );
4030         if ( !intersection.IsDone() ||
4031              intersection.IsInQuadric() ||
4032              intersection.IsParallel() ||
4033              intersection.NbPoints() < 1 )
4034           continue;
4035
4036         double u = intersection.ParamOnConic(1);
4037         if ( u + _grid->_tol < 0 )
4038           continue;
4039         int       iDir = iLink / 4;
4040         int      index = (&hex->_i)[iDir];
4041         double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
4042         if ( u - _grid->_tol > linkLen )
4043           continue;
4044
4045         if ( u < _grid->_tol ||
4046              u > linkLen - _grid->_tol ) // intersection at grid node
4047         {
4048           int  i = ! ( u < _grid->_tol ); // [0,1]
4049           int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
4050
4051           const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
4052                                                             _grid->_nodeShift[iN] ];
4053           if ( !ip )
4054           {
4055             ip = _grid->_extIntPool.getNew();
4056             ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4057             //ip->_transition = Trans_INTERNAL;
4058           }
4059           else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4060           {
4061             ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4062           }
4063           hex->_nbFaceIntNodes++;
4064           //isCut = true;
4065         }
4066         else
4067         {
4068           const gp_Pnt&      p = intersection.Point( 1 );
4069           F_IntersectPoint* ip = _grid->_extIntPool.getNew();
4070           ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
4071           ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4072           ip->_transition = Trans_INTERNAL;
4073           meshDS->SetNodeInVolume( ip->_node, solidID );
4074
4075           CellsAroundLink fourCells( _grid, iDir );
4076           fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
4077           int i,j,k, cellIndex;
4078           for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
4079           {
4080             if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
4081               continue;
4082             Hexahedron * h = hexes[ cellIndex ];
4083             if ( !h )
4084               h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
4085             h->_hexLinks[iLink]._fIntPoints.push_back( ip );
4086             h->_nbFaceIntNodes++;
4087             //isCut = true;
4088           }
4089         }
4090       }
4091
4092       // if ( isCut )
4093       //   for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
4094       //   {
4095       //     if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
4096       //          ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
4097       //       hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4098       //   }
4099       continue;
4100
4101     } // loop on all hexes
4102     return;
4103   }
4104
4105   //================================================================================
4106   /*!
4107    * \brief Return intersection point on INTERNAL FACE most distant from given ones
4108    */
4109   gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
4110   {
4111     gp_Pnt resultPnt = p1;
4112
4113     double maxDist2 = 0;
4114     for ( int iLink = 0; iLink < 12; ++iLink ) // check links
4115     {
4116       _Link& link = _hexLinks[ iLink ];
4117       for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
4118         if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
4119              _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
4120              link._fIntPoints[i]->_node )
4121         {
4122           gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
4123           double d = p1.SquareDistance( p );
4124           if ( d > maxDist2 )
4125           {
4126             resultPnt = p;
4127             maxDist2  = d;
4128           }
4129           else
4130           {
4131             d = p2.SquareDistance( p );
4132             if ( d > maxDist2 )
4133             {
4134               resultPnt = p;
4135               maxDist2  = d;
4136             }
4137           }
4138         }
4139     }
4140     setIJK( hexIndex );
4141     _origNodeInd = _grid->NodeIndex( _i,_j,_k );
4142
4143     for ( size_t iN = 0; iN < 8; ++iN ) // check corners
4144     {
4145       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _grid->_nodeShift[iN] ];
4146       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
4147       if ( _hexNodes[iN]._intPoint )
4148         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
4149         {
4150           if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
4151           {
4152             gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
4153             double d = p1.SquareDistance( p );
4154             if ( d > maxDist2 )
4155             {
4156               resultPnt = p;
4157               maxDist2  = d;
4158             }
4159             else
4160             {
4161               d = p2.SquareDistance( p );
4162               if ( d > maxDist2 )
4163               {
4164                 resultPnt = p;
4165                 maxDist2  = d;
4166               }
4167             }
4168           }
4169         }
4170     }
4171     if ( maxDist2 < _grid->_tol * _grid->_tol )
4172       return p1;
4173
4174     return resultPnt;
4175   }
4176
4177   //================================================================================
4178   /*!
4179    * \brief Finds intersection of a curve with a plane
4180    *  \param [in] u1 - parameter of one curve point
4181    *  \param [in] proj1 - projection of the curve point to the plane normal
4182    *  \param [in] u2 - parameter of another curve point
4183    *  \param [in] proj2 - projection of the other curve point to the plane normal
4184    *  \param [in] proj - projection of a point where the curve intersects the plane
4185    *  \param [in] curve - the curve
4186    *  \param [in] axis - the plane normal
4187    *  \param [in] origin - the plane origin
4188    *  \return gp_Pnt - the found intersection point
4189    */
4190   gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
4191                                    double u2, double proj2,
4192                                    double proj,
4193                                    BRepAdaptor_Curve& curve,
4194                                    const gp_XYZ& axis,
4195                                    const gp_XYZ& origin)
4196   {
4197     double r = (( proj - proj1 ) / ( proj2 - proj1 ));
4198     double u = u1 * ( 1 - r ) + u2 * r;
4199     gp_Pnt p = curve.Value( u );
4200     double newProj =  axis * ( p.XYZ() - origin );
4201     if ( Abs( proj - newProj ) > _grid->_tol / 10. )
4202     {
4203       if ( r > 0.5 )
4204         return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
4205       else
4206         return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
4207     }
4208     return p;
4209   }
4210
4211   //================================================================================
4212   /*!
4213    * \brief Returns indices of a hexahedron sub-entities holding a point
4214    *  \param [in] ip - intersection point
4215    *  \param [out] facets - 0-3 facets holding a point
4216    *  \param [out] sub - index of a vertex or an edge holding a point
4217    *  \return int - number of facets holding a point
4218    */
4219   int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
4220   {
4221     enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
4222     int nbFacets = 0;
4223     int vertex = 0, edgeMask = 0;
4224
4225     if ( Abs( _grid->_coords[0][ _i   ] - ip->_uvw[0] ) < _grid->_tol ) {
4226       facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
4227       edgeMask |= X;
4228     }
4229     else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
4230       facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
4231       vertex   |= X;
4232       edgeMask |= X;
4233     }
4234     if ( Abs( _grid->_coords[1][ _j   ] - ip->_uvw[1] ) < _grid->_tol ) {
4235       facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
4236       edgeMask |= Y;
4237     }
4238     else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
4239       facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
4240       vertex   |= Y;
4241       edgeMask |= Y;
4242     }
4243     if ( Abs( _grid->_coords[2][ _k   ] - ip->_uvw[2] ) < _grid->_tol ) {
4244       facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
4245       edgeMask |= Z;
4246     }
4247     else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
4248       facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
4249       vertex   |= Z;
4250       edgeMask |= Z;
4251     }
4252
4253     switch ( nbFacets )
4254     {
4255     case 0: sub = 0;         break;
4256     case 1: sub = facets[0]; break;
4257     case 2: {
4258       const int edge [3][8] = {
4259         { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
4260           SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
4261         { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
4262           SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
4263         { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
4264           SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
4265       };
4266       switch ( edgeMask ) {
4267       case X | Y: sub = edge[ 0 ][ vertex ]; break;
4268       case X | Z: sub = edge[ 1 ][ vertex ]; break;
4269       default:    sub = edge[ 2 ][ vertex ];
4270       }
4271       break;
4272     }
4273     //case 3:
4274     default:
4275       sub = vertex + SMESH_Block::ID_FirstV;
4276     }
4277
4278     return nbFacets;
4279   }
4280   //================================================================================
4281   /*!
4282    * \brief Adds intersection with an EDGE
4283    */
4284   bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
4285                                     vector< Hexahedron* >&  hexes,
4286                                     int ijk[], int dIJK[] )
4287   {
4288     bool added = false;
4289
4290     size_t hexIndex[4] = {
4291       _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
4292       dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
4293       dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
4294       dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
4295     };
4296     for ( int i = 0; i < 4; ++i )
4297     {
4298       if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
4299       {
4300         Hexahedron* h = hexes[ hexIndex[i] ];
4301         h->_eIntPoints.reserve(2);
4302         h->_eIntPoints.push_back( ip );
4303         added = true;
4304
4305         // check if ip is really inside the hex
4306         if (SALOME::VerbosityActivated() && h->isOutParam( ip->_uvw ))
4307           throw SALOME_Exception("ip outside a hex");
4308       }
4309     }
4310     return added;
4311   }
4312   //================================================================================
4313   /*!
4314    * \brief Check if a hexahedron facet lies on a FACE
4315    *        Also return true if the facet does not interfere with any FACE
4316    */
4317   bool Hexahedron::isQuadOnFace( const size_t iQuad )
4318   {
4319     _Face& quad = _hexQuads[ iQuad ] ;
4320
4321     int nbGridNodesInt = 0; // nb FACE intersections at grid nodes
4322     int nbNoGeomNodes  = 0;
4323     for ( int iE = 0; iE < 4; ++iE )
4324     {
4325       nbNoGeomNodes = ( !quad._links[ iE ].FirstNode()->_intPoint &&
4326                         quad._links[ iE ].NbResultLinks() == 1      );
4327       nbGridNodesInt +=
4328         ( quad._links[ iE ].FirstNode()->_intPoint &&
4329           quad._links[ iE ].NbResultLinks() == 1   &&
4330           quad._links[ iE ].ResultLink( 0 ).FirstNode() == quad._links[ iE ].FirstNode() &&
4331           quad._links[ iE ].ResultLink( 0 ).LastNode()  == quad._links[ iE ].LastNode()   );
4332     }
4333     if ( nbNoGeomNodes == 4 )
4334       return true;
4335
4336     if ( nbGridNodesInt == 4 ) // all quad nodes are at FACE intersection
4337     {
4338       size_t iEmin = 0, minNbFaces = 1000;
4339       for ( int iE = 0; iE < 4; ++iE ) // look for a node with min nb FACEs
4340       {
4341         size_t nbFaces = quad._links[ iE ].FirstNode()->faces().size();
4342         if ( minNbFaces > nbFaces )
4343         {
4344           iEmin = iE;
4345           minNbFaces = nbFaces;
4346         }
4347       }
4348       // check if there is a FACE passing through all 4 nodes
4349       for ( const TGeomID& faceID : quad._links[ iEmin ].FirstNode()->faces() )
4350       {
4351         bool allNodesAtFace = true;
4352         for ( size_t iE = 0; iE < 4 &&  allNodesAtFace; ++iE )
4353           allNodesAtFace = ( iE == iEmin ||
4354                              quad._links[ iE ].FirstNode()->IsOnFace( faceID ));
4355         if ( allNodesAtFace ) // quad if on faceID
4356           return true;
4357       }
4358     }
4359     return false;
4360   }
4361   //================================================================================
4362   /*!
4363    * \brief Finds nodes at a path from one node to another via intersections with EDGEs
4364    */
4365   bool Hexahedron::findChain( _Node*          n1,
4366                               _Node*          n2,
4367                               _Face&          quad,
4368                               vector<_Node*>& chn )
4369   {
4370     chn.clear();
4371     chn.push_back( n1 );
4372     for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4373       if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4374            n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
4375            n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4376       {
4377         chn.push_back( quad._eIntNodes[ iP ]);
4378         chn.push_back( n2 );
4379         quad._eIntNodes[ iP ]->_usedInFace = &quad;
4380         return true;
4381       }
4382     bool found;
4383     do
4384     {
4385       found = false;
4386       for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4387         if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4388              chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4389         {
4390           chn.push_back( quad._eIntNodes[ iP ]);
4391           found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4392           break;
4393         }
4394     } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4395
4396     if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4397       chn.push_back( n2 );
4398
4399     return chn.size() > 1;
4400   }
4401   //================================================================================
4402   /*!
4403    * \brief Try to heal a polygon whose ends are not connected
4404    */
4405   bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4406   {
4407     int i = -1, nbLinks = polygon->_links.size();
4408     if ( nbLinks < 3 )
4409       return false;
4410     vector< _OrientedLink > newLinks;
4411     // find a node lying on the same FACE as the last one
4412     _Node*       node = polygon->_links.back().LastNode();
4413     TGeomID avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4414     for ( i = nbLinks - 2; i >= 0; --i )
4415       if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4416         break;
4417     if ( i >= 0 )
4418     {
4419       for ( ; i < nbLinks; ++i )
4420         newLinks.push_back( polygon->_links[i] );
4421     }
4422     else
4423     {
4424       // find a node lying on the same FACE as the first one
4425       node      = polygon->_links[0].FirstNode();
4426       avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4427       for ( i = 1; i < nbLinks; ++i )
4428         if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4429           break;
4430       if ( i < nbLinks )
4431         for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4432           newLinks.push_back( polygon->_links[i] );
4433     }
4434     if ( newLinks.size() > 1 )
4435     {
4436       polygon->_links.swap( newLinks );
4437       chainNodes.clear();
4438       chainNodes.push_back( polygon->_links.back().LastNode() );
4439       chainNodes.push_back( polygon->_links[0].FirstNode() );
4440       return true;
4441     }
4442     return false;
4443   }
4444   //================================================================================
4445   /*!
4446    * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4447    *
4448    * This function is for
4449    * 1) a case where an EDGE lies on a quad which lies on a FACE
4450    *    so that a part of quad in ON and another part is IN
4451    * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4452    */
4453   bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4454                                     const _OrientedLink&           prevSplit,
4455                                     const _OrientedLink&           avoidSplit,
4456                                     const std::set< TGeomID > &    concaveFaces,
4457                                     size_t &                       iS,
4458                                     _Face&                         quad,
4459                                     vector<_Node*>&                chn )
4460   {
4461     _Node* pn1 = prevSplit.FirstNode();
4462     _Node* pn2 = prevSplit.LastNode(); // pn2 is on EDGE, if not on INTERNAL FACE
4463     _Node* an3 = avoidSplit.LastNode();
4464     TGeomID avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4465     if ( avoidFace < 1 && pn1->_intPoint )
4466       return false;
4467
4468     chn.clear();
4469
4470     if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4471     {
4472       chn.push_back( pn2 );
4473       bool found;
4474       do
4475       {
4476         found = false;
4477         for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4478           if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4479               ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4480               ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4481           {
4482             chn.push_back( quad._eIntNodes[ iP ]);
4483             found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4484             break;
4485           }
4486       } while ( found );
4487       pn2 = chn.back();
4488     }
4489
4490     _Node* n = 0, *stopNode = avoidSplit.LastNode();
4491
4492     if ( pn2 == prevSplit.LastNode() && // pn2 is at avoidSplit.FirstNode()
4493          !isCorner( stopNode ))         // stopNode is in the middle of a _hexLinks
4494     {
4495       // move stopNode to a _hexNodes
4496       for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
4497         for ( size_t iL = 0; iL < quad._links[ iE ].NbResultLinks(); ++iL )
4498         {
4499           const _Link* sideSplit = & quad._links[ iE ]._link->_splits[ iL ];
4500           if ( sideSplit == avoidSplit._link )
4501           {
4502             if ( quad._links[ iE ].LastNode()->Node() )
4503               stopNode = quad._links[ iE ].LastNode();
4504             iE = 4;
4505             break;
4506           }
4507         }
4508     }
4509
4510     // connect pn2 (probably new, at _eIntNodes) with a split
4511
4512     int i, iConn = 0;
4513     size_t nbCommon;
4514     TGeomID commonFaces[20];
4515     _Node* nPrev = nullptr;
4516     for ( i = splits.size()-1; i >= 0; --i )
4517     {
4518       if ( !splits[i] )
4519         continue;
4520
4521       bool stop = false;
4522       for ( int is1st = 0; is1st < 2; ++is1st )
4523       {
4524         _Node* nConn = is1st ? splits[i].FirstNode() : splits[i].LastNode();
4525         if ( nConn == nPrev )
4526         {
4527           if ( n == nConn )
4528             iConn = i;
4529           continue;
4530         }
4531         nPrev = nConn;
4532         if (( stop = ( nConn == stopNode )))
4533           break;
4534         // find a FACE connecting nConn with pn2 but not with an3
4535         if (( nConn != pn1 ) &&
4536             ( nConn->_intPoint && !nConn->_intPoint->_faceIDs.empty() ) &&
4537             ( nbCommon = nConn->GetCommonFaces( pn2->_intPoint, commonFaces )))
4538         {
4539           bool a3Coonect = true;
4540           for ( size_t iF = 0; iF < nbCommon &&  a3Coonect; ++iF )
4541             a3Coonect = an3->IsOnFace( commonFaces[ iF ]) || concaveFaces.count( commonFaces[ iF ]);
4542           if ( a3Coonect )
4543             continue;
4544
4545           if ( !n )
4546           {
4547             n = nConn;
4548             iConn = i + !is1st;
4549           }
4550           if ( nbCommon > 1 ) // nConn is linked with pn2 by an EDGE
4551           {
4552             n = nConn;
4553             iConn = i + !is1st;
4554             stop = true;
4555             break;
4556           }
4557         }
4558       }
4559       if ( stop )
4560       {
4561         i = iConn;
4562         break;
4563       }
4564     }
4565
4566     if ( n && n != stopNode )
4567     {
4568       if ( chn.empty() )
4569         chn.push_back( pn2 );
4570       chn.push_back( n );
4571       iS = i-1;
4572       return true;
4573     }
4574     else if ( !chn.empty() && chn.back()->_isInternalFlags )
4575     {
4576       // INTERNAL FACE partially cuts the quad
4577       for ( int ip = chn.size() - 2; ip >= 0; --ip )
4578         chn.push_back( chn[ ip ]);
4579       return true;
4580     }
4581     return false;
4582   }
4583   //================================================================================
4584   /*!
4585    * \brief Checks transition at the ginen intersection node of a link
4586    */
4587   bool Hexahedron::isOutPoint( _Link& link, int iP,
4588                                SMESH_MesherHelper& helper, const Solid* solid ) const
4589   {
4590     bool isOut = false;
4591
4592     if ( link._fIntNodes[iP]->faces().size() == 1 &&
4593          _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4594       return false;
4595
4596     const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4597
4598     // get 2 _Node's
4599     _Node* n1 = link._fIntNodes[ iP ];
4600     if ( !n1->Node() )
4601       n1 = link._nodes[0];
4602     _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4603     if ( !n2 || !n2->Node() )
4604       n2 = link._nodes[1];
4605     if ( !n2->Node() )
4606       return true;
4607
4608     // get all FACEs under n1 and n2
4609     set< TGeomID > faceIDs;
4610     if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4611                                          link._fIntNodes[iP+1]->faces().end() );
4612     if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4613                                          n2->_intPoint->_faceIDs.end() );
4614     if ( faceIDs.empty() )
4615       return false; // n2 is inside
4616     if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4617                                          n1->_intPoint->_faceIDs.end() );
4618     faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4619                     link._fIntNodes[iP]->faces().end() );
4620
4621     // get a point between 2 nodes
4622     gp_Pnt p1      = n1->Point();
4623     gp_Pnt p2      = n2->Point();
4624     gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4625
4626     TopLoc_Location loc;
4627
4628     set< TGeomID >::iterator faceID = faceIDs.begin();
4629     for ( ; faceID != faceIDs.end(); ++faceID )
4630     {
4631       // project pOnLink on a FACE
4632       if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4633       const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4634       GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4635       gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4636       proj.Perform( testPnt );
4637       if ( proj.IsDone() && proj.NbPoints() > 0 )       
4638       {
4639         Standard_Real u,v;
4640         proj.LowerDistanceParameters( u,v );
4641
4642         if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4643         {
4644           isOut = false;
4645         }
4646         else
4647         {
4648           // find isOut by normals
4649           gp_Dir normal;
4650           if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4651                                    gp_Pnt2d( u,v ),
4652                                    0.1*_grid->_tol,
4653                                    normal ) < 3 )
4654           {
4655             if ( solid->Orientation( face ) == TopAbs_REVERSED )
4656               normal.Reverse();
4657             gp_Vec v( proj.NearestPoint(), testPnt );
4658             isOut = ( v * normal > 0 );
4659           }
4660         }
4661         if ( !isOut )
4662         {
4663           // classify a projection
4664           if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4665           {
4666             BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4667             TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4668             if ( state == TopAbs_OUT )
4669             {
4670               isOut = true;
4671               continue;
4672             }
4673           }
4674           return false;
4675         }
4676       }
4677     }
4678     return isOut;
4679   }
4680   //================================================================================
4681   /*!
4682    * \brief Sort nodes on a FACE
4683    */
4684   void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4685   {
4686     if ( nodes.size() > 20 ) return;
4687
4688     // get shapes under nodes
4689     TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4690     for ( size_t i = 0; i < nodes.size(); ++i )
4691       if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4692         return;
4693
4694     // get shapes of the FACE
4695     const TopoDS_Face&  face = TopoDS::Face( _grid->Shape( faceID ));
4696     list< TopoDS_Edge > edges;
4697     list< int >         nbEdges;
4698     int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4699     if ( nbW > 1 ) {
4700       // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4701       list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4702       list< int >::iterator nE = nbEdges.begin();
4703       for ( ; nbW > 0; ++nE, --nbW )
4704       {
4705         std::advance( eEnd, *nE );
4706         for ( ; e != eEnd; ++e )
4707           for ( int i = 0; i < 2; ++i )
4708           {
4709             TGeomID id = i==0 ?
4710               _grid->ShapeID( *e ) :
4711               _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4712             if (( id > 0 ) &&
4713                 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4714             {
4715               edges.erase( eEnd, edges.end() ); // remove rest wires
4716               e = eEnd = edges.end();
4717               --e;
4718               nbW = 0;
4719               break;
4720             }
4721           }
4722         if ( nbW > 0 )
4723           edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4724       }
4725     }
4726     // rotate edges to have the first one at least partially out of the hexa
4727     list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4728     for ( ; e != edges.end(); ++e )
4729     {
4730       if ( !_grid->ShapeID( *e ))
4731         continue;
4732       bool isOut = false;
4733       gp_Pnt p;
4734       double uvw[3], f,l;
4735       for ( int i = 0; i < 2 && !isOut; ++i )
4736       {
4737         if ( i == 0 )
4738         {
4739           TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4740           p = BRep_Tool::Pnt( v );
4741         }
4742         else if ( eMidOut == edges.end() )
4743         {
4744           TopLoc_Location loc;
4745           Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4746           if ( c.IsNull() ) break;
4747           p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4748         }
4749         else
4750         {
4751           continue;
4752         }
4753
4754         _grid->ComputeUVW( p.XYZ(), uvw );
4755         if ( isOutParam( uvw ))
4756         {
4757           if ( i == 0 )
4758             isOut = true;
4759           else
4760             eMidOut = e;
4761         }
4762       }
4763       if ( isOut )
4764         break;
4765     }
4766     if ( e != edges.end() )
4767       edges.splice( edges.end(), edges, edges.begin(), e );
4768     else if ( eMidOut != edges.end() )
4769       edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4770
4771     // sort nodes according to the order of edges
4772     _Node*  orderNodes   [20];
4773     //TGeomID orderShapeIDs[20];
4774     size_t nbN = 0;
4775     TGeomID id, *pID = 0;
4776     for ( e = edges.begin(); e != edges.end(); ++e )
4777     {
4778       if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4779           (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4780       {
4781         //orderShapeIDs[ nbN ] = id;
4782         orderNodes   [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4783         *pID = -1;
4784       }
4785       if (( id = _grid->ShapeID( *e )) &&
4786           (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4787       {
4788         //orderShapeIDs[ nbN ] = id;
4789         orderNodes   [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4790         *pID = -1;
4791       }
4792     }
4793     if ( nbN != nodes.size() )
4794       return;
4795
4796     bool reverse = ( orderNodes[0    ]->Point().SquareDistance( curNode->Point() ) >
4797                      orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4798
4799     for ( size_t i = 0; i < nodes.size(); ++i )
4800       nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4801   }
4802
4803   //================================================================================
4804   /*!
4805    * \brief Adds computed elements to the mesh
4806    */
4807   int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4808   {
4809     F_IntersectPoint noIntPnt;
4810     const bool toCheckNodePos = _grid->IsToCheckNodePos();
4811
4812     int nbAdded = 0;
4813     // add elements resulted from hexahedron intersection
4814     for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4815     {
4816       vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4817       for ( size_t iN = 0; iN < nodes.size(); ++iN )
4818       {
4819         if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4820         {
4821           if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4822           {
4823             nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4824               helper.AddNode( eip->_point.X(),
4825                               eip->_point.Y(),
4826                               eip->_point.Z() );
4827             if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4828               helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4829             else
4830               helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4831           }
4832           else
4833             throw SALOME_Exception("Bug: no node at intersection point");
4834         }
4835         else if ( volDef->_nodes[iN]._intPoint &&
4836                   volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4837         {
4838           // Update position of node at EDGE intersection;
4839           // see comment to _Node::Add( E_IntersectPoint )
4840           SMESHDS_Mesh* mesh = helper.GetMeshDS();
4841           TGeomID    shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4842           mesh->UnSetNodeOnShape( nodes[iN] );
4843           if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4844             mesh->SetNodeOnVertex( nodes[iN], shapeID );
4845           else
4846             mesh->SetNodeOnEdge( nodes[iN], shapeID );
4847         }
4848         else if ( toCheckNodePos &&
4849                   !nodes[iN]->isMarked() &&
4850                   _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4851         {
4852           _grid->SetOnShape( nodes[iN], noIntPnt, /*v=*/nullptr,/*unset=*/true );
4853           nodes[iN]->setIsMarked( true );
4854         }
4855       } // loop to get nodes
4856
4857       const SMDS_MeshElement* v = 0;
4858       
4859       if ( !volDef->_quantities.empty() )
4860       {      
4861         // split polyhedrons of with disjoint volumes
4862         std::vector<std::vector<int>> splitQuantities;
4863         std::vector<std::vector< const SMDS_MeshNode* > > splitNodes;
4864         if ( checkPolyhedronValidity( volDef, splitQuantities, splitNodes ) == 1 )
4865         {
4866           v = addPolyhedronToMesh( volDef, helper, nodes, volDef->_quantities );
4867         }
4868         else
4869         {
4870           int counter = -1;
4871           for (size_t id = 0; id < splitQuantities.size(); id++)
4872           {
4873             v = addPolyhedronToMesh( volDef, helper, splitNodes[ id ], splitQuantities[ id ] );
4874             if ( id < splitQuantities.size()-1 )
4875               volDef->_brotherVolume.push_back( v );
4876             counter++;
4877           }
4878           nbAdded += counter;
4879         }
4880       }
4881       else
4882       {
4883         switch ( nodes.size() )
4884         {
4885         case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4886                                       nodes[4],nodes[5],nodes[6],nodes[7] );
4887           break;
4888         case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4889           break;
4890         case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4891           break;
4892         case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4893           break;
4894         }
4895       }
4896       volDef->_volume = v;
4897       nbAdded += bool( v );
4898
4899     } // loop on _volumeDefs chain
4900
4901     // avoid creating overlapping volumes (bos #24052)
4902     if ( nbAdded > 1 )
4903     {
4904       double sumSize = 0, maxSize = 0;
4905       _volumeDef* maxSizeDef = nullptr;
4906       for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4907       {
4908         if ( !volDef->_volume )
4909           continue;
4910         sumSize += volDef->_size;
4911         if ( volDef->_size > maxSize )
4912         {
4913           maxSize    = volDef->_size;
4914           maxSizeDef = volDef;
4915         }
4916       }
4917       if ( sumSize > _sideLength[0] * _sideLength[1] * _sideLength[2] * 1.05 )
4918       {
4919         for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4920           if ( volDef != maxSizeDef && volDef->_volume )
4921           {
4922             helper.GetMeshDS()->RemoveFreeElement( volDef->_volume, /*sm=*/nullptr,
4923                                                    /*fromGroups=*/false );
4924             volDef->_volume = nullptr;
4925             //volDef->_nodes.clear();
4926             --nbAdded;
4927           }
4928       }
4929     }
4930
4931     for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4932     {
4933       if ( volDef->_volume )
4934       {
4935         helper.GetMeshDS()->SetMeshElementOnShape( volDef->_volume, volDef->_solidID );
4936         for (auto broVol : volDef->_brotherVolume )
4937         {
4938           helper.GetMeshDS()->SetMeshElementOnShape( broVol, volDef->_solidID );
4939         }
4940       }
4941     }
4942
4943     return nbAdded;
4944   }
4945   //================================================================================
4946   /*!
4947    * \brief Return true if the element is in a hole
4948    */
4949   bool Hexahedron::isInHole() const
4950   {
4951     if ( !_vIntNodes.empty() )
4952       return false;
4953
4954     const size_t ijk[3] = { _i, _j, _k };
4955     F_IntersectPoint curIntPnt;
4956
4957     // consider a cell to be in a hole if all links in any direction
4958     // comes OUT of geometry
4959     for ( int iDir = 0; iDir < 3; ++iDir )
4960     {
4961       const vector<double>& coords = _grid->_coords[ iDir ];
4962       LineIndexer               li = _grid->GetLineIndexer( iDir );
4963       li.SetIJK( _i,_j,_k );
4964       size_t lineIndex[4] = { li.LineIndex  (),
4965                               li.LineIndex10(),
4966                               li.LineIndex01(),
4967                               li.LineIndex11() };
4968       bool allLinksOut = true, hasLinks = false;
4969       for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4970       {
4971         const _Link& link = _hexLinks[ iL + 4*iDir ];
4972         // check transition of the first node of a link
4973         const F_IntersectPoint* firstIntPnt = 0;
4974         if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4975         {
4976           curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4977           const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4978           if ( !line._intPoints.empty() )
4979           {
4980             multiset< F_IntersectPoint >::const_iterator ip =
4981               line._intPoints.upper_bound( curIntPnt );
4982             --ip;
4983             firstIntPnt = &(*ip);
4984           }
4985         }
4986         else if ( !link._fIntPoints.empty() )
4987         {
4988           firstIntPnt = link._fIntPoints[0];
4989         }
4990
4991         if ( firstIntPnt )
4992         {
4993           hasLinks = true;
4994           allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4995                           !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4996         }
4997       }
4998       if ( hasLinks && allLinksOut )
4999         return true;
5000     }
5001     return false;
5002   }
5003
5004   //================================================================================
5005   /*!
5006    * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
5007    *        that will be meshed by other algo
5008    */
5009   bool Hexahedron::hasStrangeEdge() const
5010   {
5011     if ( _eIntPoints.size() < 2 )
5012       return false;
5013
5014     TopTools_MapOfShape edges;
5015     for ( size_t i = 0; i < _eIntPoints.size(); ++i )
5016     {
5017       if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
5018         continue;
5019       const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
5020       if ( s.ShapeType() == TopAbs_EDGE )
5021       {
5022         if ( ! edges.Add( s ))
5023           return true; // an EDGE encounters twice
5024       }
5025       else
5026       {
5027         PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
5028                                                                  *_grid->_helper->GetMesh(),
5029                                                                  TopAbs_EDGE );
5030         while ( const TopoDS_Shape* edge = edgeIt->next() )
5031           if ( ! edges.Add( *edge ))
5032             return true; // an EDGE encounters twice
5033       }
5034     }
5035     return false;
5036   }
5037
5038   //================================================================================
5039   /*!
5040    * \brief Return true if a polyhedron passes _sizeThreshold criterion
5041    */
5042   bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace, double & volume) const
5043   {
5044     volume = 0;
5045
5046     if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
5047     {
5048       // check if any polygon fully lies on shared/internal FACEs
5049       for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5050       {
5051         const _Face& polygon = _polygons[iP];
5052         if ( polygon._links.empty() )
5053           continue;
5054         bool allNodesInternal = true;
5055         for ( size_t iL = 0; iL < polygon._links.size() &&  allNodesInternal; ++iL )
5056         {
5057           _Node* n = polygon._links[ iL ].FirstNode();
5058           allNodesInternal = (( n->IsCutByInternal() ) ||
5059                               ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
5060         }
5061         if ( allNodesInternal )
5062           return true;
5063       }
5064     }
5065     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5066     {
5067       const _Face& polygon = _polygons[iP];
5068       if ( polygon._links.empty() )
5069         continue;
5070       gp_XYZ area (0,0,0);
5071       gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
5072       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
5073       {
5074         gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
5075         area += p1 ^ p2;
5076         p1 = p2;
5077       }
5078       volume += p1 * area;
5079     }
5080     volume /= 6;
5081
5082     if ( this->hasStrangeEdge() && volume > 1e-13 )
5083       return true;
5084
5085     double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
5086
5087     return volume > initVolume / _grid->_sizeThreshold;
5088   }
5089
5090   //================================================================================
5091   /*!
5092    * \brief Check that all faces in polyhedron are connected so a unique volume is defined.
5093    *        We test that it is possible to go from any node to all nodes in the polyhedron.
5094    *        The set of nodes that can be visit within then defines a unique element.
5095    *        In case more than one polyhedron is detected. The function return the set of quantities and nodes defining separates elements.
5096    *        Reference to issue #bos[38521][EDF] Generate polyhedron with separate volume.
5097    */
5098   int Hexahedron::checkPolyhedronValidity( _volumeDef* volDef, std::vector<std::vector<int>>& splitQuantities, 
5099                                            std::vector<std::vector<const SMDS_MeshNode*>>& splitNodes )
5100   {  
5101     int mySet = 1;
5102     std::map<int,int> numberOfSets; // define set id with the number of faces associated!
5103     if ( !volDef->_quantities.empty() )
5104     {
5105       auto connectivity = volDef->_quantities;
5106       int accum = 0;
5107       std::vector<bool> allFaces( connectivity.size(), false );
5108       std::set<int> elementSet;
5109       allFaces[ 0 ] = true; // the first node below to the first face
5110       size_t connectedFaces = 1;
5111       // Start filling the set with the nodes of the first face
5112       splitQuantities.push_back( { connectivity[ 0 ] } );
5113       splitNodes.push_back( { volDef->_nodes[ 0 ].Node() } );
5114       elementSet.insert( volDef->_nodes[ 0 ].Node()->GetID() );
5115       for (int n = 1; n < connectivity[ 0 ]; n++)
5116       {
5117         elementSet.insert( volDef->_nodes[ n ].Node()->GetID() );
5118         splitNodes.back().push_back( volDef->_nodes[ n ].Node() );
5119       }
5120       
5121       numberOfSets.insert( std::pair<int,int>(mySet,1) );
5122       while ( connectedFaces != allFaces.size() )
5123       {
5124         for (size_t innerId = 1; innerId < connectivity.size(); innerId++)
5125         {
5126           if ( innerId == 1 )
5127             accum = connectivity[ 0 ];
5128
5129           if ( !allFaces[ innerId ] )
5130           {
5131             int faceCounter = 0;
5132             for (int n = 0; n < connectivity[ innerId ]; n++)
5133             {
5134               int nodeId = volDef->_nodes[ accum + n ].Node()->GetID();
5135               if ( elementSet.count( nodeId ) != 0 ) 
5136                 faceCounter++;
5137             }
5138             if ( faceCounter >= 2 ) // found coincidences nodes
5139             {
5140               for (int n = 0; n < connectivity[ innerId ]; n++)
5141               {
5142                 int nodeId = volDef->_nodes[ accum + n ].Node()->GetID();
5143                 // insert new nodes so other faces can be identified as belowing to the element
5144                 splitNodes.back().push_back( volDef->_nodes[ accum + n ].Node() );
5145                 elementSet.insert( nodeId );
5146               }
5147               allFaces[ innerId ] = true;
5148               splitQuantities.back().push_back( connectivity[ innerId ] );
5149               numberOfSets[ mySet ]++;
5150               connectedFaces++;
5151               innerId = 0; // to restart searching!
5152             }
5153           }
5154           accum += connectivity[ innerId ];
5155         }
5156
5157         if ( connectedFaces != allFaces.size() )
5158         {
5159           // empty the set, and fill it with nodes of a unvisited face!
5160           elementSet.clear();
5161           accum = connectivity[ 0 ];
5162           for (size_t faceId = 1; faceId < connectivity.size(); faceId++)
5163           {
5164             if ( !allFaces[ faceId ] )
5165             {
5166               splitNodes.push_back( { volDef->_nodes[ accum ].Node() } );
5167               elementSet.insert( volDef->_nodes[ accum ].Node()->GetID() );
5168               for (int n = 1; n < connectivity[ faceId ]; n++)
5169               {
5170                 elementSet.insert( volDef->_nodes[ accum + n ].Node()->GetID() );
5171                 splitNodes.back().push_back( volDef->_nodes[ accum + n ].Node() );
5172               }
5173
5174               splitQuantities.push_back( { connectivity[ faceId ] } );
5175               allFaces[ faceId ] = true;
5176               connectedFaces++;
5177               break;
5178             }
5179             accum += connectivity[ faceId ];
5180           }
5181           mySet++;
5182           numberOfSets.insert( std::pair<int,int>(mySet,1) );
5183         }
5184       }
5185
5186       if ( numberOfSets.size() > 1 )
5187       {
5188         bool allMoreThan2Faces = true;
5189         for( auto k : numberOfSets )
5190         {
5191           if ( k.second <= 2 )
5192             allMoreThan2Faces &= false;
5193         }
5194         
5195         if ( allMoreThan2Faces )
5196         {        
5197           // The separate objects are suspect to be closed
5198           return numberOfSets.size();        
5199         }
5200         else
5201         {
5202           // Have to index the last face nodes to the final set
5203           // contrary case return as it were a valid polyhedron for backward compatibility
5204           return 1;  
5205         }
5206       }
5207     }
5208     return numberOfSets.size();
5209   }
5210
5211   
5212   //================================================================================
5213   /*!
5214    * \brief add original or separated polyhedrons to the mesh
5215    */
5216   const SMDS_MeshElement* Hexahedron::addPolyhedronToMesh( _volumeDef* volDef,  SMESH_MesherHelper& helper, const std::vector<const SMDS_MeshNode*>& nodes, 
5217                                                             const std::vector<int>& quantities )
5218   {
5219     const SMDS_MeshElement* v = helper.AddPolyhedralVolume( nodes, quantities );
5220
5221     volDef->_size = SMDS_VolumeTool( v ).GetSize();
5222     if ( volDef->_size < 0 ) // invalid polyhedron
5223     {
5224       if ( ! SMESH_MeshEditor( helper.GetMesh() ).Reorient( v ) || // try to fix
5225           SMDS_VolumeTool( v ).GetSize() < 0 )
5226       {
5227         helper.GetMeshDS()->RemoveFreeElement( v, /*sm=*/nullptr, /*fromGroups=*/false );
5228         v = nullptr;
5229         //_hasTooSmall = true;
5230
5231         if (SALOME::VerbosityActivated())
5232         {
5233           std::cout << "Remove INVALID polyhedron, _cellID = " << _cellID
5234                     << " ijk = ( " << _i << " " << _j << " " << _k << " ) "
5235                     << " solid " << volDef->_solidID << std::endl;
5236         }
5237       }
5238     }
5239     return v;
5240   }
5241
5242   //================================================================================
5243   /*!
5244    * \brief Tries to create a hexahedron
5245    */
5246   bool Hexahedron::addHexa()
5247   {
5248     int nbQuad = 0, iQuad = -1;
5249     for ( size_t i = 0; i < _polygons.size(); ++i )
5250     {
5251       if ( _polygons[i]._links.empty() )
5252         continue;
5253       if ( _polygons[i]._links.size() != 4 )
5254         return false;
5255       ++nbQuad;
5256       if ( iQuad < 0 )
5257         iQuad = i;
5258     }
5259     if ( nbQuad != 6 )
5260       return false;
5261
5262     _Node* nodes[8];
5263     int nbN = 0;
5264     for ( int iL = 0; iL < 4; ++iL )
5265     {
5266       // a base node
5267       nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
5268       ++nbN;
5269
5270       // find a top node above the base node
5271       _Link* link = _polygons[iQuad]._links[iL]._link;
5272       if ( !link->_faces[0] || !link->_faces[1] )
5273         return debugDumpLink( link );
5274       // a quadrangle sharing <link> with _polygons[iQuad]
5275       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
5276       for ( int i = 0; i < 4; ++i )
5277         if ( quad->_links[i]._link == link )
5278         {
5279           // 1st node of a link opposite to <link> in <quad>
5280           nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
5281           ++nbN;
5282           break;
5283         }
5284     }
5285     if ( nbN == 8 )
5286       _volumeDefs.Set( &nodes[0], 8 );
5287
5288     return nbN == 8;
5289   }
5290   //================================================================================
5291   /*!
5292    * \brief Tries to create a tetrahedron
5293    */
5294   bool Hexahedron::addTetra()
5295   {
5296     int iTria = -1;
5297     for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
5298       if ( _polygons[i]._links.size() == 3 )
5299         iTria = i;
5300     if ( iTria < 0 )
5301       return false;
5302
5303     _Node* nodes[4];
5304     nodes[0] = _polygons[iTria]._links[0].FirstNode();
5305     nodes[1] = _polygons[iTria]._links[1].FirstNode();
5306     nodes[2] = _polygons[iTria]._links[2].FirstNode();
5307
5308     _Link* link = _polygons[iTria]._links[0]._link;
5309     if ( !link->_faces[0] || !link->_faces[1] )
5310       return debugDumpLink( link );
5311
5312     // a triangle sharing <link> with _polygons[0]
5313     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
5314     for ( int i = 0; i < 3; ++i )
5315       if ( tria->_links[i]._link == link )
5316       {
5317         nodes[3] = tria->_links[(i+1)%3].LastNode();
5318         _volumeDefs.Set( &nodes[0], 4 );
5319         return true;
5320       }
5321
5322     return false;
5323   }
5324   //================================================================================
5325   /*!
5326    * \brief Tries to create a pentahedron
5327    */
5328   bool Hexahedron::addPenta()
5329   {
5330     // find a base triangular face
5331     int iTri = -1;
5332     for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
5333       if ( _polygons[ iF ]._links.size() == 3 )
5334         iTri = iF;
5335     if ( iTri < 0 ) return false;
5336
5337     // find nodes
5338     _Node* nodes[6];
5339     int nbN = 0;
5340     for ( int iL = 0; iL < 3; ++iL )
5341     {
5342       // a base node
5343       nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
5344       ++nbN;
5345
5346       // find a top node above the base node
5347       _Link* link = _polygons[ iTri ]._links[iL]._link;
5348       if ( !link->_faces[0] || !link->_faces[1] )
5349         return debugDumpLink( link );
5350       // a quadrangle sharing <link> with a base triangle
5351       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
5352       if ( quad->_links.size() != 4 ) return false;
5353       for ( int i = 0; i < 4; ++i )
5354         if ( quad->_links[i]._link == link )
5355         {
5356           // 1st node of a link opposite to <link> in <quad>
5357           nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
5358           ++nbN;
5359           break;
5360         }
5361     }
5362     if ( nbN == 6 )
5363       _volumeDefs.Set( &nodes[0], 6 );
5364
5365     return ( nbN == 6 );
5366   }
5367   //================================================================================
5368   /*!
5369    * \brief Tries to create a pyramid
5370    */
5371   bool Hexahedron::addPyra()
5372   {
5373     // find a base quadrangle
5374     int iQuad = -1;
5375     for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
5376       if ( _polygons[ iF ]._links.size() == 4 )
5377         iQuad = iF;
5378     if ( iQuad < 0 ) return false;
5379
5380     // find nodes
5381     _Node* nodes[5];
5382     nodes[0] = _polygons[iQuad]._links[0].FirstNode();
5383     nodes[1] = _polygons[iQuad]._links[1].FirstNode();
5384     nodes[2] = _polygons[iQuad]._links[2].FirstNode();
5385     nodes[3] = _polygons[iQuad]._links[3].FirstNode();
5386
5387     _Link* link = _polygons[iQuad]._links[0]._link;
5388     if ( !link->_faces[0] || !link->_faces[1] )
5389       return debugDumpLink( link );
5390
5391     // a triangle sharing <link> with a base quadrangle
5392     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
5393     if ( tria->_links.size() != 3 ) return false;
5394     for ( int i = 0; i < 3; ++i )
5395       if ( tria->_links[i]._link == link )
5396       {
5397         nodes[4] = tria->_links[(i+1)%3].LastNode();
5398         _volumeDefs.Set( &nodes[0], 5 );
5399         return true;
5400       }
5401
5402     return false;
5403   }
5404   //================================================================================
5405   /*!
5406    * \brief Return true if there are _eIntPoints at EDGEs forming a  concave corner
5407    */
5408   bool Hexahedron::hasEdgesAround( const ConcaveFace* cf ) const
5409   {
5410     int nbEdges = 0;
5411     ConcaveFace foundGeomHolder;
5412     for ( const E_IntersectPoint* ip : _eIntPoints )
5413     {
5414       if ( cf->HasEdge( ip->_shapeID ))
5415       {
5416         if ( ++nbEdges == 2 )
5417           return true;
5418         foundGeomHolder.SetEdge( ip->_shapeID );
5419       }
5420       else if ( ip->_faceIDs.size() >= 3 )
5421       {
5422         const TGeomID & vID = ip->_shapeID;
5423         if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5424         {
5425           if ( ++nbEdges == 2 )
5426             return true;
5427           foundGeomHolder.SetVertex( vID );
5428         }
5429       }
5430     }
5431
5432     for ( const _Node& hexNode: _hexNodes )
5433     {
5434       if ( !hexNode._node || !hexNode._intPoint )
5435         continue;
5436       const B_IntersectPoint* ip = hexNode._intPoint;
5437       if ( ip->_faceIDs.size() == 2 ) // EDGE
5438       {
5439         TGeomID edgeID = hexNode._node->GetShapeID();
5440         if ( cf->HasEdge( edgeID ) && !foundGeomHolder.HasEdge( edgeID ))
5441         {
5442           foundGeomHolder.SetEdge( edgeID );
5443           if ( ++nbEdges == 2 )
5444             return true;
5445         }
5446       }
5447       else if ( ip->_faceIDs.size() >= 3 ) // VERTEX
5448       {
5449         TGeomID vID = hexNode._node->GetShapeID();
5450         if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5451         {
5452           if ( ++nbEdges == 2 )
5453             return true;
5454           foundGeomHolder.SetVertex( vID );
5455         }
5456       }
5457     }
5458
5459     return false;
5460   }
5461   //================================================================================
5462   /*!
5463    * \brief Dump a link and return \c false
5464    */
5465   bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
5466   {
5467     if (SALOME::VerbosityActivated())
5468     {
5469       gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
5470       cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
5471           << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
5472           << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
5473     }
5474
5475     return false;
5476   }
5477   //================================================================================
5478   /*!
5479    * \brief Classify a point by grid parameters
5480    */
5481   bool Hexahedron::isOutParam(const double uvw[3]) const
5482   {
5483     return (( _grid->_coords[0][ _i   ] - _grid->_tol > uvw[0] ) ||
5484             ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
5485             ( _grid->_coords[1][ _j   ] - _grid->_tol > uvw[1] ) ||
5486             ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
5487             ( _grid->_coords[2][ _k   ] - _grid->_tol > uvw[2] ) ||
5488             ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
5489   }
5490   //================================================================================
5491   /*!
5492    * \brief Find existing triangulation of a polygon
5493    */
5494   int findExistingTriangulation( const SMDS_MeshElement*              polygon,
5495                                  //const SMDS_Mesh*                     mesh,
5496                                  std::vector< const SMDS_MeshNode* >& nodes )
5497   {
5498     int nbSplits = 0;
5499     nodes.clear();
5500     std::vector<const SMDS_MeshNode *>    twoNodes(2);
5501     std::vector<const SMDS_MeshElement *> foundFaces; foundFaces.reserve(10);
5502     std::set< const SMDS_MeshElement * >  avoidFaces; avoidFaces.insert( polygon );
5503
5504     const int nbPolyNodes = polygon->NbCornerNodes();
5505     twoNodes[1] = polygon->GetNode( nbPolyNodes - 1 );
5506     for ( int iN = 0; iN < nbPolyNodes; ++iN ) // loop on border links of polygon
5507     {
5508       twoNodes[0] = polygon->GetNode( iN );
5509
5510       int nbFaces = SMDS_Mesh::GetElementsByNodes( twoNodes, foundFaces, SMDSAbs_Face );
5511       int nbOkFaces = 0;
5512       for ( int iF = 0; iF < nbFaces; ++iF ) // keep faces lying over polygon
5513       {
5514         if ( avoidFaces.count( foundFaces[ iF ]))
5515           continue;
5516         int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5517         for ( i = 0; i < nbFaceNodes; ++i )
5518         {
5519           const SMDS_MeshNode* n = foundFaces[ iF ]->GetNode( i );
5520           bool isCommonNode = ( n == twoNodes[0] ||
5521                                 n == twoNodes[1] ||
5522                                 polygon->GetNodeIndex( n ) >= 0 );
5523           if ( !isCommonNode )
5524             break;
5525         }
5526         if ( i == nbFaceNodes ) // all nodes of foundFaces[iF] are shared with polygon
5527           if ( nbOkFaces++ != iF )
5528             foundFaces[ nbOkFaces-1 ] = foundFaces[ iF ];
5529       }
5530       if ( nbOkFaces > 0 )
5531       {
5532         int iFaceSelected = 0;
5533         if ( nbOkFaces > 1 ) // select a face with minimal distance from polygon
5534         {
5535           double minDist = Precision::Infinite();
5536           for ( int iF = 0; iF < nbOkFaces; ++iF )
5537           {
5538             int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5539             gp_XYZ gc = SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( 0 ));
5540             for ( i = 1; i < nbFaceNodes; ++i )
5541               gc += SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( i ));
5542             gc /= nbFaceNodes;
5543
5544             double dist = SMESH_MeshAlgos::GetDistance( polygon, gc );
5545             if ( dist < minDist )
5546             {
5547               minDist = dist;
5548               iFaceSelected = iF;
5549             }
5550           }
5551         }
5552         if ( foundFaces[ iFaceSelected ]->NbCornerNodes() != 3 )
5553           return 0;
5554         nodes.insert( nodes.end(),
5555                       foundFaces[ iFaceSelected ]->begin_nodes(),
5556                       foundFaces[ iFaceSelected ]->end_nodes());
5557         if ( !SMESH_MeshAlgos::IsRightOrder( foundFaces[ iFaceSelected ],
5558                                              twoNodes[0], twoNodes[1] ))
5559         {
5560           // reverse just added nodes
5561           std::reverse( nodes.end() - 3, nodes.end() );
5562         }
5563         avoidFaces.insert( foundFaces[ iFaceSelected ]);
5564         nbSplits++;
5565       }
5566
5567       twoNodes[1] = twoNodes[0];
5568
5569     } // loop on polygon nodes
5570
5571     return nbSplits;
5572   }
5573   //================================================================================
5574   /*!
5575    * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
5576    */
5577   void splitPolygon( const SMDS_MeshElement*         polygon,
5578                      SMDS_VolumeTool &               volume,
5579                      const int                       facetIndex,
5580                      const TGeomID                   faceID,
5581                      const TGeomID                   solidID,
5582                      SMESH_MeshEditor::ElemFeatures& face,
5583                      SMESH_MeshEditor&               editor,
5584                      const bool                      reinitVolume)
5585   {
5586     SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
5587     bool triangulationExist = false;
5588     int nbTrias = findExistingTriangulation( polygon, face.myNodes );
5589     if ( nbTrias > 0 )
5590       triangulationExist = true;
5591     else
5592       nbTrias = divider.GetTriangles( polygon, face.myNodes );
5593     face.myNodes.resize( nbTrias * 3 );
5594
5595     SMESH_MeshEditor::ElemFeatures newVolumeDef;
5596     newVolumeDef.Init( volume.Element() );
5597     newVolumeDef.SetID( volume.Element()->GetID() );
5598
5599     newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
5600     newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
5601
5602     SMESHDS_Mesh* meshDS = editor.GetMeshDS();
5603     SMDS_MeshElement* newTriangle;
5604     for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
5605     {
5606       if ( iF == facetIndex )
5607       {
5608         newVolumeDef.myPolyhedQuantities.push_back( 3 );
5609         newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5610                                      face.myNodes.begin(),
5611                                      face.myNodes.begin() + 3 );
5612         meshDS->RemoveFreeElement( polygon, 0, false );
5613         if ( !triangulationExist )
5614         {
5615           newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
5616           meshDS->SetMeshElementOnShape( newTriangle, faceID );
5617         }
5618       }
5619       else
5620       {
5621         const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
5622         const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
5623         newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
5624         newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
5625       }
5626     }
5627
5628     for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
5629     {
5630       newVolumeDef.myPolyhedQuantities.push_back( 3 );
5631       newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5632                                    face.myNodes.begin() + iN,
5633                                    face.myNodes.begin() + iN + 3 );
5634       if ( !triangulationExist )
5635       {
5636         newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
5637         meshDS->SetMeshElementOnShape( newTriangle, faceID );
5638       }
5639     }
5640
5641     meshDS->RemoveFreeElement( volume.Element(), 0, false );
5642     SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
5643     meshDS->SetMeshElementOnShape( newVolume, solidID );
5644
5645     if ( reinitVolume )
5646     {
5647       volume.Set( 0 );
5648       volume.Set( newVolume );
5649     }
5650     return;
5651   }
5652   //================================================================================
5653   /*!
5654    * \brief Look for a FACE supporting all given nodes made on EDGEs and VERTEXes
5655    */
5656   TGeomID findCommonFace( const std::vector< const SMDS_MeshNode* > & nn,
5657                           const SMESH_Mesh*                           mesh )
5658   {
5659     TGeomID faceID = 0;
5660     TGeomID shapeIDs[20];
5661     for ( size_t iN = 0; iN < nn.size(); ++iN )
5662       shapeIDs[ iN ] = nn[ iN ]->GetShapeID();
5663
5664     SMESH_subMesh* sm = mesh->GetSubMeshContaining( shapeIDs[ 0 ]);
5665     for ( const SMESH_subMesh * smFace : sm->GetAncestors() )
5666     {
5667       if ( smFace->GetSubShape().ShapeType() != TopAbs_FACE )
5668         continue;
5669
5670       faceID = smFace->GetId();
5671
5672       for ( size_t iN = 1; iN < nn.size() &&  faceID; ++iN )
5673       {
5674         if ( !smFace->DependsOn( shapeIDs[ iN ]))
5675           faceID = 0;
5676       }
5677       if ( faceID > 0 )
5678         break;
5679     }
5680     return faceID;
5681   }
5682   //================================================================================
5683   /*!
5684    * \brief Create mesh faces at free facets
5685    */
5686   void Hexahedron::addFaces( SMESH_MesherHelper&                       helper,
5687                              const vector< const SMDS_MeshElement* > & boundaryVolumes )
5688   {
5689     if ( !_grid->_toCreateFaces )
5690       return;
5691
5692     SMDS_VolumeTool vTool;
5693     vector<int> bndFacets;
5694     SMESH_MeshEditor editor( helper.GetMesh() );
5695     SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
5696     SMESHDS_Mesh* meshDS = helper.GetMeshDS();
5697
5698     // check if there are internal or shared FACEs
5699     bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
5700                          _grid->_geometry._soleSolid.HasInternalFaces() );
5701
5702     for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
5703     {
5704       if ( !vTool.Set( boundaryVolumes[ iV ]))
5705         continue;
5706
5707       TGeomID solidID = vTool.Element()->GetShapeID();
5708       Solid *   solid = _grid->GetOneOfSolids( solidID );
5709
5710       // find boundary facets
5711
5712       bndFacets.clear();
5713       for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
5714       {
5715         const SMDS_MeshElement* otherVol;
5716         bool isBoundary = vTool.IsFreeFace( iF, &otherVol );
5717         if ( isBoundary )
5718         {
5719           bndFacets.push_back( iF );
5720         }
5721         else if (( hasInternal ) ||
5722                  ( !_grid->IsSolid( otherVol->GetShapeID() )))
5723         {
5724           // check if all nodes are on internal/shared FACEs
5725           isBoundary = true;
5726           const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
5727           const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
5728           for ( size_t iN = 0; iN < nbFaceNodes &&  isBoundary; ++iN )
5729             isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
5730           if ( isBoundary )
5731             bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
5732         }
5733       }
5734       if ( bndFacets.empty() )
5735         continue;
5736
5737       // create faces
5738
5739       if ( !vTool.IsPoly() )
5740         vTool.SetExternalNormal();
5741       for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
5742       {
5743         const bool    isBoundary = ( bndFacets[i] >= 0 );
5744         const int         iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
5745         const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
5746         const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
5747         face.myNodes.assign( nn, nn + nbFaceNodes );
5748
5749         TGeomID faceID = 0;
5750         const SMDS_MeshElement* existFace = 0, *newFace = 0;
5751
5752         if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
5753         {
5754           if ( existFace->isMarked() )
5755             continue; // created by this method
5756           faceID = existFace->GetShapeID();
5757         }
5758         else
5759         {
5760           // look for a supporting FACE
5761           for ( size_t iN = 0; iN < nbFaceNodes &&  !faceID; ++iN ) // look for a node on FACE
5762           {
5763             if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
5764               faceID = nn[ iN ]->GetShapeID();
5765           }
5766           if ( faceID == 0 )
5767             faceID = findCommonFace( face.myNodes, helper.GetMesh() );
5768
5769           bool toCheckFace = faceID && (( !isBoundary ) ||
5770                                         ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
5771           if ( toCheckFace ) // check if all nodes are on the found FACE
5772           {
5773             SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
5774             for ( size_t iN = 0; iN < nbFaceNodes &&  faceID; ++iN )
5775             {
5776               TGeomID subID = nn[ iN ]->GetShapeID();
5777               if ( subID != faceID && !faceSM->DependsOn( subID ))
5778                 faceID = 0;
5779             }
5780             // if ( !faceID && !isBoundary )
5781             //   continue;
5782           }
5783           if ( !faceID && !isBoundary )
5784             continue;
5785         }
5786
5787         // orient a new face according to supporting FACE orientation in shape_to_mesh
5788         if ( !isBoundary && !solid->IsOutsideOriented( faceID ))
5789         {
5790           if ( existFace )
5791             editor.Reorient( existFace );
5792           else
5793             std::reverse( face.myNodes.begin(), face.myNodes.end() );
5794         }
5795
5796         if ( ! ( newFace = existFace ))
5797         {
5798           face.SetPoly( nbFaceNodes > 4 );
5799           newFace = editor.AddElement( face.myNodes, face );
5800           if ( !newFace )
5801             continue;
5802           newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
5803         }
5804
5805         if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
5806         {
5807           // set newFace to the found FACE provided that it fully lies on the FACE
5808           for ( size_t iN = 0; iN < nbFaceNodes &&  faceID; ++iN )
5809             if ( nn[iN]->GetShapeID() == solidID )
5810             {
5811               if ( existFace )
5812                 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
5813               faceID = 0;
5814             }
5815         }
5816
5817         if ( faceID && nbFaceNodes > 4 &&
5818              !_grid->IsInternal( faceID ) &&
5819              !_grid->IsShared( faceID ) &&
5820              !_grid->IsBoundaryFace( faceID ))
5821         {
5822           // split a polygon that will be used by other 3D algorithm
5823           if ( !existFace )
5824             splitPolygon( newFace, vTool, iFacet, faceID, solidID,
5825                           face, editor, i+1 < bndFacets.size() );
5826         }
5827         else
5828         {
5829           if ( faceID )
5830             meshDS->SetMeshElementOnShape( newFace, faceID );
5831           else
5832             meshDS->SetMeshElementOnShape( newFace, solidID );
5833         }
5834       } // loop on bndFacets
5835     } // loop on boundaryVolumes
5836
5837
5838     // Orient coherently mesh faces on INTERNAL FACEs
5839
5840     if ( hasInternal )
5841     {
5842       TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5843       for ( ; faceExp.More(); faceExp.Next() )
5844       {
5845         if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5846           continue;
5847
5848         SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5849         if ( !sm ) continue;
5850
5851         TIDSortedElemSet facesToOrient;
5852         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5853           facesToOrient.insert( facesToOrient.end(), fIt->next() );
5854         if ( facesToOrient.size() < 2 )
5855           continue;
5856
5857         gp_Dir direction(1,0,0);
5858         TIDSortedElemSet refFaces;
5859         editor.Reorient2D( facesToOrient, direction, refFaces, /*allowNonManifold=*/true );
5860       }
5861     }
5862     return;
5863   }
5864
5865   //================================================================================
5866   /*!
5867    * \brief Create mesh segments.
5868    */
5869   void Hexahedron::addSegments( SMESH_MesherHelper&                      helper,
5870                                 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5871   {
5872     SMESHDS_Mesh* mesh = helper.GetMeshDS();
5873
5874     std::vector<const SMDS_MeshNode*> nodes;
5875     std::vector<const SMDS_MeshElement *> elems;
5876     map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5877     for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5878     {
5879       const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5880       const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5881       StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5882       nodes = side.GetOrderedNodes();
5883
5884       elems.clear();
5885       if ( nodes.size() == 2 )
5886         // check that there is an element connecting two nodes
5887         if ( !mesh->GetElementsByNodes( nodes, elems ))
5888           continue;
5889
5890       for ( size_t i = 1; i < nodes.size(); i++ )
5891       {
5892         if ( mesh->FindEdge( nodes[i-1], nodes[i] ))
5893           continue;
5894         SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5895         mesh->SetMeshElementOnShape( segment, e2ff->first );
5896       }
5897     }
5898     return;
5899   }
5900
5901   //================================================================================
5902   /*!
5903    * \brief Return created volumes and volumes that can have free facet because of
5904    *        skipped small volume. Also create mesh faces on free facets
5905    *        of adjacent not-cut volumes if the result volume is too small.
5906    */
5907   void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5908   {
5909     if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5910     {
5911       // create faces around a missing small volume
5912       TGeomID faceID = 0;
5913       SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5914       SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5915       SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5916       std::vector<const SMDS_MeshElement *> adjVolumes(2);
5917       for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5918       {
5919         const size_t nbLinks = _polygons[ iF ]._links.size();
5920         if ( nbLinks != 4 ) continue;
5921         polygon.myNodes.resize( nbLinks );
5922         polygon.myNodes.back() = 0;
5923         for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5924           if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5925             break;
5926         if ( !polygon.myNodes.back() )
5927           continue;
5928
5929         meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5930         if ( adjVolumes.size() != 1 )
5931           continue;
5932         if ( !adjVolumes[0]->isMarked() )
5933         {
5934           boundaryElems.push_back( adjVolumes[0] );
5935           adjVolumes[0]->setIsMarked( true );
5936         }
5937
5938         bool sameShape = true;
5939         TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5940         for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5941           sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5942
5943         if ( !sameShape || !_grid->IsSolid( shapeID ))
5944           continue; // some of shapes must be FACE
5945
5946         if ( !faceID )
5947         {
5948           faceID = getAnyFace();
5949           if ( !faceID )
5950             break;
5951           if ( _grid->IsInternal( faceID ) ||
5952                _grid->IsShared( faceID ) //||
5953                //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5954                ) 
5955             break; // create only if a new face will be used by other 3D algo
5956         }
5957
5958         Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5959         if ( !solid->IsOutsideOriented( faceID ))
5960           std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5961
5962         //polygon.SetPoly( polygon.myNodes.size() > 4 );
5963         const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5964         meshDS->SetMeshElementOnShape( newFace, faceID );
5965       }
5966     }
5967
5968     // return created volumes
5969     for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5970     {
5971       if ( volDef ->_volume &&
5972            !volDef->_volume->IsNull() &&
5973            !volDef->_volume->isMarked() )
5974       {
5975         volDef->_volume->setIsMarked( true );
5976         boundaryElems.push_back( volDef->_volume );
5977
5978         if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5979           for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5980             volDef->_nodes[iN].Node()->setIsMarked( false );
5981       }
5982       if ( volDef->_brotherVolume.size() > 0 )
5983       {
5984         for (auto _bro : volDef->_brotherVolume )
5985         {
5986           _bro->setIsMarked( true );
5987           boundaryElems.push_back( _bro );
5988         }        
5989       }
5990     }
5991   }
5992
5993   //================================================================================
5994   /*!
5995    * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5996    *        volume also sharing the dividing edge is missing due to its small side.
5997    *        Issue #19887.
5998    */
5999   //================================================================================
6000
6001   void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
6002   {
6003     if ( ! _volumeDefs.IsPolyhedron() )
6004       return; // not a polyhedron
6005       
6006     // look for a divided side adjacent to a small hexahedron
6007
6008     int di[6] = { 0, 0, 0, 0,-1, 1 };
6009     int dj[6] = { 0, 0,-1, 1, 0, 0 };
6010     int dk[6] = {-1, 1, 0, 0, 0, 0 };
6011
6012     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6013     {
6014       size_t neighborIndex = _grid->CellIndex( _i + di[iF],
6015                                                _j + dj[iF],
6016                                                _k + dk[iF] );
6017       if ( neighborIndex >= allHexa.size() ||
6018            !allHexa[ neighborIndex ]       ||
6019            !allHexa[ neighborIndex ]->_hasTooSmall )
6020         continue;
6021
6022       // check if a side is divided into several polygons
6023       for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
6024       {
6025         int nbPolygons = 0, nbNodes = 0;
6026         for ( size_t i = 0; i < volDef->_names.size(); ++i )
6027           if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
6028           {
6029             ++nbPolygons;
6030             nbNodes += volDef->_quantities[ i ];
6031           }
6032         if ( nbPolygons < 2 )
6033           continue;
6034
6035         // construct loops from polygons
6036         typedef _volumeDef::_linkDef TLinkDef;
6037         std::vector< TLinkDef* > loops;
6038         std::vector< TLinkDef > links( nbNodes );
6039         for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
6040         {
6041           size_t nbLinks = volDef->_quantities[ iLoop ];
6042           if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
6043           {
6044             iN += nbLinks;
6045             continue;
6046           }
6047           loops.push_back( & links[i] );
6048           for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
6049           {
6050             links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
6051             links[i].setNext( &links[i+1] );
6052           }
6053           links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
6054           links[i].setNext( &links[i-nbLinks+1] );
6055           ++i; ++iN;
6056         }
6057
6058         // look for equal links in different loops and join such loops
6059         bool loopsJoined = false;
6060         std::set< TLinkDef > linkSet;
6061         for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
6062         {
6063           TLinkDef* beg = 0;
6064           for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
6065           {
6066             std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
6067             if ( !it2new.second ) // equal found, join loops
6068             {
6069               const TLinkDef* equal = &(*it2new.first);
6070               if ( equal->_loopIndex == l->_loopIndex )
6071                 continue; // error?
6072
6073               loopsJoined = true;
6074
6075               for ( size_t i = iLoop - 1; i < loops.size(); --i )
6076                 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
6077                   loops[ i ] = 0;
6078
6079               // exclude l and equal and join two loops
6080               if ( l->_prev != equal )
6081                 l->_prev->setNext( equal->_next );
6082               if ( equal->_prev != l )
6083                 equal->_prev->setNext( l->_next );
6084
6085               if ( volDef->_quantities[ l->_loopIndex ] > 0 )
6086                 volDef->_quantities[ l->_loopIndex     ] *= -1;
6087               if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
6088                 volDef->_quantities[ equal->_loopIndex ] *= -1;
6089
6090               if ( loops[ iLoop ] == l )
6091                 loops[ iLoop ] = l->_prev->_next;
6092             }
6093             beg = loops[ iLoop ];
6094           }
6095         }
6096         // update volDef
6097         if ( loopsJoined )
6098         {
6099           // set unchanged polygons
6100           std::vector< int >             newQuantities;
6101           std::vector< _volumeDef::_nodeDef > newNodes;
6102           vector< SMESH_Block::TShapeID >     newNames;
6103           newQuantities.reserve( volDef->_quantities.size() );
6104           newNodes.reserve     ( volDef->_nodes.size() );
6105           newNames.reserve     ( volDef->_names.size() );
6106           for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
6107           {
6108             if ( volDef->_quantities[ iLoop ] < 0 )
6109             {
6110               i -= volDef->_quantities[ iLoop ];
6111               continue;
6112             }
6113             newQuantities.push_back( volDef->_quantities[ iLoop ]);
6114             newNodes.insert( newNodes.end(),
6115                              volDef->_nodes.begin() + i,
6116                              volDef->_nodes.begin() + i + newQuantities.back() );
6117             newNames.push_back( volDef->_names[ iLoop ]);
6118             i += volDef->_quantities[ iLoop ];
6119           }
6120
6121           // set joined loops
6122           for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
6123           {
6124             if ( !loops[ iLoop ] )
6125               continue;
6126             newQuantities.push_back( 0 );
6127             TLinkDef* beg = 0;
6128             for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
6129             {
6130               newNodes.push_back( l->_node1 );
6131               beg = loops[ iLoop ];
6132             }
6133             newNames.push_back( _hexQuads[ iF ]._name );
6134           }
6135           volDef->_quantities.swap( newQuantities );
6136           volDef->_nodes.swap( newNodes );
6137           volDef->_names.swap( newNames );
6138         }
6139       } // loop on volDef's
6140     } // loop on hex sides
6141
6142     return;
6143   } // removeExcessSideDivision()
6144
6145
6146   //================================================================================
6147   /*!
6148    * \brief Remove nodes splitting Cartesian cell edges in the case if a node
6149    *        is used in every cells only by two polygons sharing the edge
6150    *        Issue #19887.
6151    */
6152   //================================================================================
6153
6154   void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
6155   {
6156     if ( ! _volumeDefs.IsPolyhedron() )
6157       return; // not a polyhedron
6158
6159     typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
6160     vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
6161     vector< int > volDefInd  [ 4 ]; // index of a _volumeDefs
6162     Hexahedron*   hexa       [ 4 ];
6163     int i,j,k, cellIndex, iLink = 0, iCellLink;
6164     for ( int iDir = 0; iDir < 3; ++iDir )
6165     {
6166       CellsAroundLink fourCells( _grid, iDir );
6167       for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
6168       {
6169         _Link& link = _hexLinks[ iLink ];
6170         fourCells.Init( _i, _j, _k, iLink );
6171
6172         for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
6173         {
6174           bool nodeRemoved = true;
6175           _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
6176
6177           for ( size_t i = 0, nb = _volumeDefs.size(); i < nb &&  nodeRemoved; ++i )
6178             if ( _volumeDef* vol = _volumeDefs.at( i ))
6179               nodeRemoved =
6180                 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
6181           if ( nodeRemoved )
6182             continue; // node already removed
6183
6184           // check if a node encounters zero or two times in 4 cells sharing iLink
6185           // if so, the node can be removed from the cells
6186           bool       nodeIsOnEdge = true;
6187           int nbPolyhedraWithNode = 0;
6188           for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
6189           {
6190             nodesInPoly[ iC ].clear();
6191             volDefInd  [ iC ].clear();
6192             hexa       [ iC ] = 0;
6193             if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
6194               continue;
6195             hexa[ iC ] = allHexa[ cellIndex ];
6196             if ( !hexa[ iC ])
6197               continue;
6198             for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
6199               if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
6200               {
6201                 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
6202                 {
6203                   nIt = std::find( nIt, vol->_nodes.end(), node );
6204                   if ( nIt != vol->_nodes.end() )
6205                   {
6206                     nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
6207                     volDefInd  [ iC ].push_back( i );
6208                   }
6209                   else
6210                     break;
6211                 }
6212                 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
6213               }
6214             if ( nodesInPoly[ iC ].size() != 0 &&
6215                  nodesInPoly[ iC ].size() != 2 )
6216             {
6217               nodeIsOnEdge = false;
6218               break;
6219             }
6220           } // loop  on 4 cells
6221
6222           // remove nodes from polyhedra
6223           if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
6224           {
6225             for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
6226             {
6227               if ( nodesInPoly[ iC ].empty() )
6228                 continue;
6229               for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
6230               {
6231                 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
6232                 int nIndex = nodesInPoly[ iC ][ i ];
6233                 // decrement _quantities
6234                 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
6235                   if ( nIndex < vol->_quantities[ iQ ])
6236                   {
6237                     vol->_quantities[ iQ ]--;
6238                     break;
6239                   }
6240                   else
6241                   {
6242                     nIndex -= vol->_quantities[ iQ ];
6243                   }
6244                 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
6245
6246                 if ( i == 0 &&
6247                      vol->_nodes.size() == 6 * 4 &&
6248                      vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
6249                 {
6250                   bool allQuads = true;
6251                   for ( size_t iQ = 0; iQ < vol->_quantities.size() &&  allQuads; ++iQ )
6252                     allQuads = ( vol->_quantities[ iQ ] == 4 );
6253                   if ( allQuads )
6254                   {
6255                     // set side nodes as this: bottom, top, top, ...
6256                     int iTop = 0, iBot = 0; // side indices
6257                     for ( int iS = 0; iS < 6; ++iS )
6258                     {
6259                       if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
6260                         iBot = iS;
6261                       if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
6262                         iTop = iS;
6263                     }
6264                     if ( iBot != 0 )
6265                     {
6266                       if ( iTop == 0 )
6267                       {
6268                         std::copy( vol->_nodes.begin(),
6269                                    vol->_nodes.begin() + 4,
6270                                    vol->_nodes.begin() + 4 );
6271                         iTop = 1;
6272                       }
6273                       std::copy( vol->_nodes.begin() + 4 * iBot,
6274                                  vol->_nodes.begin() + 4 * ( iBot + 1),
6275                                  vol->_nodes.begin() );
6276                     }
6277                     if ( iTop != 1 )
6278                       std::copy( vol->_nodes.begin() + 4 * iTop,
6279                                  vol->_nodes.begin() + 4 * ( iTop + 1),
6280                                  vol->_nodes.begin() + 4 );
6281
6282                     std::copy( vol->_nodes.begin() + 4,
6283                                vol->_nodes.begin() + 8,
6284                                vol->_nodes.begin() + 8 );
6285                     // set up top facet nodes by comparing their uvw with bottom nodes
6286                     E_IntersectPoint ip[8];
6287                     for ( int iN = 0; iN < 8; ++iN )
6288                     {
6289                       SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
6290                       _grid->ComputeUVW( p, ip[ iN ]._uvw );
6291                     }
6292                     const double tol2 = _grid->_tol * _grid->_tol;
6293                     for ( int iN = 0; iN < 4; ++iN )
6294                     {
6295                       gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
6296                       for ( int iT = 4; iT < 8; ++iT )
6297                       {
6298                         gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
6299                         if ( pBot.SquareDistance( pTop ) < tol2 )
6300                         {
6301                           // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
6302                           // vol->_nodes[ iN + 4 ]._intPoint = 0;
6303                           vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
6304                           break;
6305                         }
6306                       }
6307                     }
6308                     vol->_nodes.resize( 8 );
6309                     vol->_quantities.clear();
6310                     //vol->_names.clear();
6311                   }
6312                 }
6313               } // loop on _volumeDefs
6314             } // loop on 4 cell abound a link
6315           } // if ( nodeIsOnEdge )
6316         } // loop on intersection points of a link
6317       } // loop on 4 links of a direction
6318     } // loop on 3 directions
6319
6320     return;
6321
6322   } // removeExcessNodes()
6323
6324   //================================================================================
6325   /*!
6326    * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
6327    */
6328   //================================================================================
6329
6330   void Hexahedron::preventVolumesOverlapping()
6331   {
6332     // Cut off a quadrangle corner if two links sharing the corner
6333     // are shared by same two solids, in this case each of solids gets
6334     // a triangle for it-self.
6335     std::vector< TGeomID > soIDs[4];
6336     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6337     {
6338       _Face& quad = _hexQuads[ iF ] ;
6339
6340       int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
6341       _Face& quadOpp = _hexQuads[ iFOpposite ] ;
6342
6343       int nbSides = 0, nbSidesOpp = 0;
6344       for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
6345       {
6346         nbSides    += ( quad._links   [ iE ].NbResultLinks() > 0 );
6347         nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
6348       }
6349       if ( nbSides < 4 || nbSidesOpp != 2 )
6350         continue;
6351
6352       for ( int iE = 0; iE < 4; ++iE )
6353       {
6354         soIDs[ iE ].clear();
6355         _Node* n = quad._links[ iE ].FirstNode();
6356         if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
6357           soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
6358       }
6359       if ((( soIDs[0].size() >= 2 ) +
6360            ( soIDs[1].size() >= 2 ) +
6361            ( soIDs[2].size() >= 2 ) +
6362            ( soIDs[3].size() >= 2 ) ) < 3 )
6363         continue;
6364
6365       bool done = false;
6366       for ( int i = 0; i < 4; ++i )
6367       {
6368         int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
6369         int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
6370         int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
6371         if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
6372              soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
6373              soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
6374         {
6375           quad._links[ i1 ]._link->_splits.clear();
6376           quad._links[ i2 ]._link->_splits.clear();
6377           done = true;
6378           break;
6379         }
6380       }
6381       if ( done )
6382         break;
6383     }
6384     return;
6385   } // preventVolumesOverlapping()
6386
6387   //================================================================================
6388   /*!
6389    * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
6390    */
6391   bool Hexahedron::_SplitIterator::Next()
6392   {
6393     if ( _iterationNb > 0 )
6394       // count used splits
6395       for ( size_t i = 0; i < _splits.size(); ++i )
6396       {
6397         if ( _splits[i]._iCheckIteration == _iterationNb )
6398         {
6399           _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
6400           _nbUsed += _splits[i]._isUsed;
6401         }
6402         if ( !More() )
6403           return false;
6404       }
6405
6406     ++_iterationNb;
6407
6408     bool toTestUsed = ( _nbChecked >= _splits.size() );
6409     if ( toTestUsed )
6410     {
6411       // all splits are checked; find all not used splits
6412       for ( size_t i = 0; i < _splits.size(); ++i )
6413         if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6414           _splits[i]._iCheckIteration = _iterationNb;
6415
6416       _nbUsed = _splits.size(); // to stop iteration
6417     }
6418     else
6419     {
6420       // get any not used/checked split to start from
6421       _freeNodes.clear();
6422       for ( size_t i = 0; i < _splits.size(); ++i )
6423       {
6424         if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6425         {
6426           _freeNodes.push_back( _splits[i]._nodes[0] );
6427           _freeNodes.push_back( _splits[i]._nodes[1] );
6428           _splits[i]._iCheckIteration = _iterationNb;
6429           break;
6430         }
6431       }
6432       // find splits connected to the start one via _freeNodes
6433       for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
6434       {
6435         for ( size_t iS = 0; iS < _splits.size(); ++iS )
6436         {
6437           if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
6438             continue;
6439           int iN2 = -1;
6440           if (      _freeNodes[iN] == _splits[iS]._nodes[0] )
6441             iN2 = 1;
6442           else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
6443             iN2 = 0;
6444           else
6445             continue;
6446           if ( _freeNodes[iN]->_isInternalFlags > 0 )
6447           {
6448             if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
6449               continue;
6450             if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
6451               continue;
6452           }
6453           _splits[iS]._iCheckIteration = _iterationNb;
6454           _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
6455         }
6456       }
6457     }
6458     // set splits to hex links
6459
6460     for ( int iL = 0; iL < 12; ++iL )
6461       _hexLinks[ iL ]._splits.clear();
6462
6463     _Link split;
6464     for ( size_t i = 0; i < _splits.size(); ++i )
6465     {
6466       if ( _splits[i]._iCheckIteration == _iterationNb )
6467       {
6468         split._nodes[0] = _splits[i]._nodes[0];
6469         split._nodes[1] = _splits[i]._nodes[1];
6470         _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
6471         hexLink._splits.push_back( split );
6472         _splits[i]._checkedSplit = & hexLink._splits.back();
6473         ++_nbChecked;
6474       }
6475     }
6476     return More();
6477   }
6478
6479   //================================================================================
6480   /*!
6481    * \brief computes exact bounding box with axes parallel to given ones
6482    */
6483   //================================================================================
6484
6485   void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
6486                        const double*                 axesDirs,
6487                        Bnd_Box&                      shapeBox )
6488   {
6489     BRep_Builder b;
6490     TopoDS_Compound allFacesComp;
6491     b.MakeCompound( allFacesComp );
6492     for ( size_t iF = 0; iF < faceVec.size(); ++iF )
6493       b.Add( allFacesComp, faceVec[ iF ] );
6494
6495     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
6496     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
6497     double farDist = 0;
6498     for ( int i = 0; i < 6; ++i )
6499       farDist = Max( farDist, 10 * sP[i] );
6500
6501     gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
6502                        gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
6503                        gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
6504     axis[0].Normalize();
6505     axis[1].Normalize();
6506     axis[2].Normalize();
6507
6508     gp_Mat basis( axis[0], axis[1], axis[2] );
6509     gp_Mat bi = basis.Inverted();
6510
6511     gp_Pnt pMin, pMax;
6512     for ( int iDir = 0; iDir < 3; ++iDir )
6513     {
6514       gp_XYZ axis0 = axis[ iDir ];
6515       gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
6516       gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
6517       for ( int isMax = 0; isMax < 2; ++isMax )
6518       {
6519         double shift = isMax ? farDist : -farDist;
6520         gp_XYZ orig = shift * axis0;
6521         gp_XYZ norm = axis1 ^ axis2;
6522         gp_Pln pln( orig, norm );
6523         norm = pln.Axis().Direction().XYZ();
6524         BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
6525
6526         gp_Pnt& pAxis = isMax ? pMax : pMin;
6527         gp_Pnt pPlane, pFaces;
6528         double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
6529         if ( dist < 0 )
6530         {
6531           Bnd_B3d bb;
6532           gp_XYZ corner;
6533           for ( int i = 0; i < 2; ++i ) {
6534             corner.SetCoord( 1, sP[ i*3 ]);
6535             for ( int j = 0; j < 2; ++j ) {
6536               corner.SetCoord( 2, sP[ i*3 + 1 ]);
6537               for ( int k = 0; k < 2; ++k )
6538               {
6539                 corner.SetCoord( 3, sP[ i*3 + 2 ]);
6540                 corner *= bi;
6541                 bb.Add( corner );
6542               }
6543             }
6544           }
6545           corner = isMax ? bb.CornerMax() : bb.CornerMin();
6546           pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
6547         }
6548         else
6549         {
6550           gp_XYZ pf = pFaces.XYZ() * bi;
6551           pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
6552         }
6553       }
6554     } // loop on 3 axes
6555
6556     shapeBox.SetVoid();
6557     shapeBox.Add( pMin );
6558     shapeBox.Add( pMax );
6559
6560     return;
6561   }
6562
6563 } // namespace
6564
6565 //=============================================================================
6566 /*!
6567  * \brief Generates 3D structured Cartesian mesh in the internal part of
6568  * solid shapes and polyhedral volumes near the shape boundary.
6569  *  \param theMesh - mesh to fill in
6570  *  \param theShape - a compound of all SOLIDs to mesh
6571  *  \retval bool - true in case of success
6572  */
6573 //=============================================================================
6574
6575 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh &         theMesh,
6576                                       const TopoDS_Shape & theShape)
6577 {
6578   if ( _hypViscousLayers )
6579   {
6580     const StdMeshers_ViscousLayers* hypViscousLayers = _hypViscousLayers;
6581     _hypViscousLayers = nullptr;
6582
6583     StdMeshers_Cartesian_VL::ViscousBuilder builder( hypViscousLayers, theMesh, theShape );
6584
6585     std::string error;
6586     TopoDS_Shape offsetShape = builder.MakeOffsetShape( theShape, theMesh, error );
6587     if ( offsetShape.IsNull() )
6588       throw SALOME_Exception( error );
6589
6590     SMESH_Mesh* offsetMesh = new TmpMesh(); 
6591     offsetMesh->ShapeToMesh( offsetShape );
6592     offsetMesh->GetSubMesh( offsetShape )->DependsOn();
6593
6594     this->_isComputeOffset = true;
6595     if ( ! this->Compute( *offsetMesh, offsetShape ))
6596       return false;
6597
6598     return builder.MakeViscousLayers( *offsetMesh, theMesh, theShape );
6599   }
6600
6601   // The algorithm generates the mesh in following steps:
6602
6603   // 1) Intersection of grid lines with the geometry boundary.
6604   // This step allows to find out if a given node of the initial grid is
6605   // inside or outside the geometry.
6606
6607   // 2) For each cell of the grid, check how many of it's nodes are outside
6608   // of the geometry boundary. Depending on a result of this check
6609   // - skip a cell, if all it's nodes are outside
6610   // - skip a cell, if it is too small according to the size threshold
6611   // - add a hexahedron in the mesh, if all nodes are inside
6612   // - add a polyhedron in the mesh, if some nodes are inside and some outside
6613
6614   _computeCanceled = false;
6615
6616   SMESH_MesherHelper helper( theMesh );
6617   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
6618
6619   try
6620   {
6621     Grid grid;
6622     grid._helper                         = &helper;
6623     grid._toAddEdges                     = _hyp->GetToAddEdges();
6624     grid._toCreateFaces                  = _hyp->GetToCreateFaces();
6625     grid._toConsiderInternalFaces        = _hyp->GetToConsiderInternalFaces();
6626     grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
6627     grid._sizeThreshold                  = _hyp->GetSizeThreshold();
6628     if ( _isComputeOffset )
6629     {
6630       grid._toAddEdges = true;
6631       grid._toCreateFaces = true;
6632     }
6633     grid.InitGeometry( theShape );
6634
6635     vector< TopoDS_Shape > faceVec;
6636     {
6637       TopTools_MapOfShape faceMap;
6638       TopExp_Explorer fExp;
6639       for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
6640       {
6641         bool isNewFace = faceMap.Add( fExp.Current() );
6642         if ( !grid._toConsiderInternalFaces )
6643           if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
6644             // remove an internal face
6645             faceMap.Remove( fExp.Current() );
6646       }
6647       faceVec.reserve( faceMap.Extent() );
6648       faceVec.assign( faceMap.cbegin(), faceMap.cend() );
6649     }
6650     vector<FaceGridIntersector> facesItersectors( faceVec.size() );
6651     Bnd_Box shapeBox;
6652     for ( size_t i = 0; i < faceVec.size(); ++i )
6653     {
6654       facesItersectors[i]._face   = TopoDS::Face( faceVec[i] );
6655       facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
6656       facesItersectors[i]._grid   = &grid;
6657       shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
6658     }
6659     getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
6660
6661
6662     vector<double> xCoords, yCoords, zCoords;
6663     _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
6664
6665     grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
6666
6667     if ( _computeCanceled ) return false;
6668
6669 #ifdef WITH_TBB
6670     { // copy partner faces and curves of not thread-safe types
6671       set< const Standard_Transient* > tshapes;
6672       BRepBuilderAPI_Copy copier;
6673       for ( size_t i = 0; i < facesItersectors.size(); ++i )
6674       {
6675         if ( !facesItersectors[i].IsThreadSafe( tshapes ))
6676         {
6677           copier.Perform( facesItersectors[i]._face );
6678           facesItersectors[i]._face = TopoDS::Face( copier );
6679         }
6680       }
6681     }
6682     // Intersection of grid lines with the geometry boundary.
6683     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
6684                         ParallelIntersector( facesItersectors ),
6685                         tbb::simple_partitioner());
6686 #else
6687     for ( size_t i = 0; i < facesItersectors.size(); ++i )
6688       facesItersectors[i].Intersect();
6689 #endif
6690
6691     // put intersection points onto the GridLine's; this is done after intersection
6692     // to avoid contention of facesItersectors for writing into the same GridLine
6693     // in case of parallel work of facesItersectors
6694     for ( size_t i = 0; i < facesItersectors.size(); ++i )
6695       facesItersectors[i].StoreIntersections();
6696
6697     if ( _computeCanceled ) return false;
6698
6699     // create nodes on the geometry
6700     grid.ComputeNodes( helper );
6701
6702     if ( _computeCanceled ) return false;
6703
6704     // get EDGEs to take into account
6705     map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
6706     grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
6707
6708     // create volume elements
6709     Hexahedron hex( &grid );
6710     int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
6711
6712     if ( nbAdded > 0 )
6713     {
6714       if ( !grid._toConsiderInternalFaces )
6715       {
6716         // make all SOLIDs computed
6717         TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
6718         if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
6719         {
6720           SMDS_ElemIteratorPtr volIt = sm1->GetElements();
6721           for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
6722           {
6723             const SMDS_MeshElement* vol = volIt->next();
6724             sm1->RemoveElement( vol );
6725             meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
6726           }
6727         }
6728       }
6729       // make other sub-shapes computed
6730       setSubmeshesComputed( theMesh, theShape );
6731     }
6732
6733     // remove free nodes
6734     //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
6735     {
6736       std::vector< const SMDS_MeshNode* > nodesToRemove;
6737       // get intersection nodes
6738       for ( int iDir = 0; iDir < 3; ++iDir )
6739       {
6740         vector< GridLine >& lines = grid._lines[ iDir ];
6741         for ( size_t i = 0; i < lines.size(); ++i )
6742         {
6743           multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
6744           for ( ; ip != lines[i]._intPoints.end(); ++ip )
6745             if ( ip->_node &&
6746                  !ip->_node->IsNull() &&
6747                  ip->_node->NbInverseElements() == 0 &&
6748                  !ip->_node->isMarked() )
6749             {
6750               nodesToRemove.push_back( ip->_node );
6751               ip->_node->setIsMarked( true );
6752             }
6753         }
6754       }
6755       // get grid nodes
6756       for ( size_t i = 0; i < grid._nodes.size(); ++i )
6757         if ( grid._nodes[i] &&
6758              !grid._nodes[i]->IsNull() &&
6759              grid._nodes[i]->NbInverseElements() == 0 &&
6760              !grid._nodes[i]->isMarked() )
6761         {
6762           nodesToRemove.push_back( grid._nodes[i] );
6763           grid._nodes[i]->setIsMarked( true );
6764         }
6765
6766       // do remove
6767       for ( size_t i = 0; i < nodesToRemove.size(); ++i )
6768         meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
6769     }
6770
6771     return nbAdded;
6772
6773   }
6774   // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
6775   catch ( SMESH_ComputeError& e)
6776   {
6777     return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
6778   }
6779   return false;
6780 }
6781
6782 //=============================================================================
6783 /*!
6784  *  Evaluate
6785  */
6786 //=============================================================================
6787
6788 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh &         /*theMesh*/,
6789                                        const TopoDS_Shape & /*theShape*/,
6790                                        MapShapeNbElems&     /*theResMap*/)
6791 {
6792   // TODO
6793 //   std::vector<int> aResVec(SMDSEntity_Last);
6794 //   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
6795 //   if(IsQuadratic) {
6796 //     aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6797 //     int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
6798 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
6799 //   }
6800 //   else {
6801 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
6802 //     aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6803 //   }
6804 //   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
6805 //   aResMap.insert(std::make_pair(sm,aResVec));
6806
6807   return true;
6808 }
6809
6810 //=============================================================================
6811 namespace
6812 {
6813   /*!
6814    * \brief Event listener setting/unsetting _alwaysComputed flag to
6815    *        submeshes of inferior levels to prevent their computing
6816    */
6817   struct _EventListener : public SMESH_subMeshEventListener
6818   {
6819     string _algoName;
6820
6821     _EventListener(const string& algoName):
6822       SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
6823       _algoName(algoName)
6824     {}
6825     // --------------------------------------------------------------------------------
6826     // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
6827     //
6828     static void setAlwaysComputed( const bool     isComputed,
6829                                    SMESH_subMesh* subMeshOfSolid)
6830     {
6831       SMESH_subMeshIteratorPtr smIt =
6832         subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
6833       while ( smIt->more() )
6834       {
6835         SMESH_subMesh* sm = smIt->next();
6836         sm->SetIsAlwaysComputed( isComputed );
6837       }
6838       subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
6839     }
6840
6841     // --------------------------------------------------------------------------------
6842     // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
6843     //
6844     virtual void ProcessEvent(const int          /*event*/,
6845                               const int          eventType,
6846                               SMESH_subMesh*     subMeshOfSolid,
6847                               SMESH_subMeshEventListenerData* /*data*/,
6848                               const SMESH_Hypothesis*         /*hyp*/ = 0)
6849     {
6850       if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
6851       {
6852         setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
6853                            subMeshOfSolid );
6854       }
6855       else
6856       {
6857         SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
6858         if ( !algo3D || _algoName != algo3D->GetName() )
6859           setAlwaysComputed( false, subMeshOfSolid );
6860       }
6861     }
6862
6863     // --------------------------------------------------------------------------------
6864     // set the event listener
6865     //
6866     static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
6867     {
6868       subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6869                                         /*data=*/0,
6870                                         subMeshOfSolid );
6871     }
6872
6873   }; // struct _EventListener
6874
6875 } // namespace
6876
6877 //================================================================================
6878 /*!
6879  * \brief Sets event listener to submeshes if necessary
6880  *  \param subMesh - submesh where algo is set
6881  * This method is called when a submesh gets HYP_OK algo_state.
6882  * After being set, event listener is notified on each event of a submesh.
6883  */
6884 //================================================================================
6885
6886 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6887 {
6888   _EventListener::SetOn( subMesh, GetName() );
6889 }
6890
6891 //================================================================================
6892 /*!
6893  * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6894  */
6895 //================================================================================
6896
6897 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh&         theMesh,
6898                                                    const TopoDS_Shape& theShape)
6899 {
6900   for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6901     _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));
6902 }