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