Salome HOME
Merge from V6_main 13/12/2012
[modules/smesh.git] / src / StdMeshers / StdMeshers_Cartesian_3D.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, 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.
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
27 #include "SMDS_MeshNode.hxx"
28 #include "SMESH_Block.hxx"
29 #include "SMESH_Comment.hxx"
30 #include "SMESH_Mesh.hxx"
31 #include "SMESH_MesherHelper.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_subMeshEventListener.hxx"
34 #include "StdMeshers_CartesianParameters3D.hxx"
35
36 #include "utilities.h"
37 #include "Utils_ExceptHandlers.hxx"
38 #include <Basics_OCCTVersion.hxx>
39
40 #include <BRepAdaptor_Surface.hxx>
41 #include <BRepBndLib.hxx>
42 #include <BRepBuilderAPI_Copy.hxx>
43 #include <BRepTools.hxx>
44 #include <BRep_Tool.hxx>
45 #include <Bnd_Box.hxx>
46 #include <ElSLib.hxx>
47 #include <Geom2d_BSplineCurve.hxx>
48 #include <Geom2d_BezierCurve.hxx>
49 #include <Geom2d_TrimmedCurve.hxx>
50 #include <Geom_BSplineCurve.hxx>
51 #include <Geom_BSplineSurface.hxx>
52 #include <Geom_BezierCurve.hxx>
53 #include <Geom_BezierSurface.hxx>
54 #include <Geom_RectangularTrimmedSurface.hxx>
55 #include <Geom_TrimmedCurve.hxx>
56 #include <IntAna_IntConicQuad.hxx>
57 #include <IntAna_IntLinTorus.hxx>
58 #include <IntAna_Quadric.hxx>
59 #include <IntCurveSurface_TransitionOnCurve.hxx>
60 #include <IntCurvesFace_Intersector.hxx>
61 #include <Poly_Triangulation.hxx>
62 #include <Precision.hxx>
63 #include <TopExp.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopLoc_Location.hxx>
66 #include <TopTools_MapIteratorOfMapOfShape.hxx>
67 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_TShape.hxx>
71 #include <gp_Cone.hxx>
72 #include <gp_Cylinder.hxx>
73 #include <gp_Lin.hxx>
74 #include <gp_Pln.hxx>
75 #include <gp_Pnt2d.hxx>
76 #include <gp_Sphere.hxx>
77 #include <gp_Torus.hxx>
78
79 //#undef WITH_TBB
80 #ifdef WITH_TBB
81 #include <tbb/parallel_for.h>
82 //#include <tbb/enumerable_thread_specific.h>
83 #endif
84
85 using namespace std;
86
87 #ifdef _DEBUG_
88 //#define _MY_DEBUG_
89 #endif
90
91 #if OCC_VERSION_LARGE <= 0x06050300
92 // workaround is required only for OCCT6.5.3 and older (see OCC22809)
93 #define ELLIPSOLID_WORKAROUND
94 #endif
95
96 #ifdef ELLIPSOLID_WORKAROUND
97 #include <BRepIntCurveSurface_Inter.hxx>
98 #include <BRepTopAdaptor_TopolTool.hxx>
99 #include <BRepAdaptor_HSurface.hxx>
100 #endif
101
102 //=============================================================================
103 /*!
104  * Constructor
105  */
106 //=============================================================================
107
108 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, int studyId, SMESH_Gen * gen)
109   :SMESH_3D_Algo(hypId, studyId, gen)
110 {
111   _name = "Cartesian_3D";
112   _shapeType = (1 << TopAbs_SOLID);       // 1 bit /shape type
113   _compatibleHypothesis.push_back("CartesianParameters3D");
114
115   _onlyUnaryInput = false;          // to mesh all SOLIDs at once
116   _requireDiscreteBoundary = false; // 2D mesh not needed
117   _supportSubmeshes = false;        // do not use any existing mesh
118 }
119
120 //=============================================================================
121 /*!
122  * Check presence of a hypothesis
123  */
124 //=============================================================================
125
126 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh&          aMesh,
127                                                const TopoDS_Shape&  aShape,
128                                                Hypothesis_Status&   aStatus)
129 {
130   aStatus = SMESH_Hypothesis::HYP_MISSING;
131
132   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
133   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
134   if ( h == hyps.end())
135   {
136     return false;
137   }
138
139   for ( ; h != hyps.end(); ++h )
140   {
141     if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
142     {
143       aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
144       break;
145     }
146   }
147
148   return aStatus == HYP_OK;
149 }
150
151 namespace
152 {
153   //=============================================================================
154   // Definitions of internal utils
155   // --------------------------------------------------------------------------
156   enum Transition {
157     Trans_TANGENT = IntCurveSurface_Tangent,
158     Trans_IN      = IntCurveSurface_In,
159     Trans_OUT     = IntCurveSurface_Out,
160     Trans_APEX
161   };
162   // --------------------------------------------------------------------------
163   /*!
164    * \brief Data of intersection between a GridLine and a TopoDS_Face
165    */
166   struct IntersectionPoint
167   {
168     double                       _paramOnLine;
169     mutable Transition           _transition;
170     mutable const SMDS_MeshNode* _node;
171     mutable size_t               _indexOnLine;
172
173     IntersectionPoint(): _node(0) {}
174     bool operator< ( const IntersectionPoint& o ) const { return _paramOnLine < o._paramOnLine; }
175   };
176   // --------------------------------------------------------------------------
177   /*!
178    * \brief A line of the grid and its intersections with 2D geometry
179    */
180   struct GridLine
181   {
182     gp_Lin _line;
183     double _length; // line length
184     multiset< IntersectionPoint > _intPoints;
185
186     void RemoveExcessIntPoints( const double tol );
187     bool GetIsOutBefore( multiset< IntersectionPoint >::iterator ip, bool prevIsOut );
188   };
189   // --------------------------------------------------------------------------
190   /*!
191    * \brief Iterator on the parallel grid lines of one direction
192    */
193   struct LineIndexer
194   {
195     size_t _size  [3];
196     size_t _curInd[3];
197     size_t _iVar1, _iVar2, _iConst;
198     string _name1, _name2, _nameConst;
199     LineIndexer() {}
200     LineIndexer( size_t sz1, size_t sz2, size_t sz3,
201                  size_t iv1, size_t iv2, size_t iConst,
202                  const string& nv1, const string& nv2, const string& nConst )
203     {
204       _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
205       _curInd[0] = _curInd[1] = _curInd[2] = 0;
206       _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst; 
207       _name1 = nv1; _name2 = nv2; _nameConst = nConst;
208     }
209
210     size_t I() const { return _curInd[0]; }
211     size_t J() const { return _curInd[1]; }
212     size_t K() const { return _curInd[2]; }
213     void SetIJK( size_t i, size_t j, size_t k )
214     {
215       _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
216     }
217     void operator++()
218     {
219       if ( ++_curInd[_iVar1] == _size[_iVar1] )
220         _curInd[_iVar1] = 0, ++_curInd[_iVar2];
221     }
222     bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
223     size_t LineIndex   () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
224     size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
225     size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
226     size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
227     void SetIndexOnLine (size_t i)  { _curInd[ _iConst ] = i; }
228     size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
229   };
230   // --------------------------------------------------------------------------
231   /*!
232    * \brief Container of GridLine's
233    */
234   struct Grid
235   {
236     vector< double >   _coords[3]; // coordinates of grid nodes
237     vector< GridLine > _lines [3]; //  in 3 directions
238     double             _tol, _minCellSize;
239
240     vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
241     vector< bool >                 _isBndNode; // is mesh node at intersection with geometry
242
243     size_t CellIndex( size_t i, size_t j, size_t k ) const
244     {
245       return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
246     }
247     size_t NodeIndex( size_t i, size_t j, size_t k ) const
248     {
249       return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
250     }
251     size_t NodeIndexDX() const { return 1; }
252     size_t NodeIndexDY() const { return _coords[0].size(); }
253     size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
254
255     LineIndexer GetLineIndexer(size_t iDir) const;
256
257     void SetCoordinates(const vector<double>& xCoords,
258                         const vector<double>& yCoords,
259                         const vector<double>& zCoords,
260                         const TopoDS_Shape&   shape );
261     void ComputeNodes(SMESH_MesherHelper& helper);
262   };
263 #ifdef ELLIPSOLID_WORKAROUND
264   // --------------------------------------------------------------------------
265   /*!
266    * \brief struct temporary replacing IntCurvesFace_Intersector until
267    *        OCCT bug 0022809 is fixed
268    *        http://tracker.dev.opencascade.org/view.php?id=22809
269    */
270   struct TMP_IntCurvesFace_Intersector
271   {
272     BRepAdaptor_Surface                       _surf;
273     double                                    _tol;
274     BRepIntCurveSurface_Inter                 _intcs;
275     vector<IntCurveSurface_IntersectionPoint> _points;
276     BRepTopAdaptor_TopolTool                  _clsf;
277
278     TMP_IntCurvesFace_Intersector(const TopoDS_Face& face, const double tol)
279       :_surf( face ), _tol( tol ), _clsf( new BRepAdaptor_HSurface(_surf) ) {}
280     Bnd_Box Bounding() const { Bnd_Box b; BRepBndLib::Add (_surf.Face(), b); return b; }
281     void Perform( const gp_Lin& line, const double w0, const double w1 )
282     {
283       _points.clear();
284       for ( _intcs.Init( _surf.Face(), line, _tol ); _intcs.More(); _intcs.Next() )
285         if ( w0 <= _intcs.W() && _intcs.W() <= w1 )
286           _points.push_back( _intcs.Point() );
287     }
288     bool IsDone() const { return true; }
289     int  NbPnt()  const { return _points.size(); }
290     IntCurveSurface_TransitionOnCurve Transition( const int i ) const { return _points[ i-1 ].Transition(); }
291     double       WParameter( const int i ) const { return _points[ i-1 ].W(); }
292     TopAbs_State ClassifyUVPoint(const gp_Pnt2d& p) { return _clsf.Classify( p, _tol ); }
293   };
294 #define __IntCurvesFace_Intersector TMP_IntCurvesFace_Intersector
295 #else
296 #define __IntCurvesFace_Intersector IntCurvesFace_Intersector
297 #endif
298   // --------------------------------------------------------------------------
299   /*!
300    * \brief Intersector of TopoDS_Face with all GridLine's
301    */
302   struct FaceGridIntersector
303   {
304     TopoDS_Face _face;
305     Grid*       _grid;
306     Bnd_Box     _bndBox;
307     __IntCurvesFace_Intersector* _surfaceInt;
308     vector< std::pair< GridLine*, IntersectionPoint > > _intersections;
309
310     FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
311     void Intersect();
312     bool IsInGrid(const Bnd_Box& gridBox);
313
314     void StoreIntersections()
315     {
316       for ( size_t i = 0; i < _intersections.size(); ++i )
317         _intersections[i].first->_intPoints.insert( _intersections[i].second );
318     }
319     const Bnd_Box& GetFaceBndBox()
320     {
321       GetCurveFaceIntersector();
322       return _bndBox;
323     }
324     __IntCurvesFace_Intersector* GetCurveFaceIntersector()
325     {
326       if ( !_surfaceInt )
327       {
328         _surfaceInt = new __IntCurvesFace_Intersector( _face, Precision::PConfusion() );
329         _bndBox     = _surfaceInt->Bounding();
330         if ( _bndBox.IsVoid() )
331           BRepBndLib::Add (_face, _bndBox);
332       }
333       return _surfaceInt;
334     }
335     bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
336   };
337   // --------------------------------------------------------------------------
338   /*!
339    * \brief Intersector of a surface with a GridLine
340    */
341   struct FaceLineIntersector
342   {
343     double      _tol;
344     double      _u, _v, _w; // params on the face and the line
345     Transition  _transition; // transition of at intersection (see IntCurveSurface.cdl)
346     Transition  _transIn, _transOut; // IN and OUT transitions depending of face orientation
347
348     gp_Pln      _plane;
349     gp_Cylinder _cylinder;
350     gp_Cone     _cone;
351     gp_Sphere   _sphere;
352     gp_Torus    _torus;
353     __IntCurvesFace_Intersector* _surfaceInt;
354
355     vector< IntersectionPoint > _intPoints;
356
357     void IntersectWithPlane   (const GridLine& gridLine);
358     void IntersectWithCylinder(const GridLine& gridLine);
359     void IntersectWithCone    (const GridLine& gridLine);
360     void IntersectWithSphere  (const GridLine& gridLine);
361     void IntersectWithTorus   (const GridLine& gridLine);
362     void IntersectWithSurface (const GridLine& gridLine);
363
364     bool UVIsOnFace() const;
365     void addIntPoint(const bool toClassify=true);
366     bool isParamOnLineOK( const double linLength )
367     {
368       return -_tol < _w && _w < linLength + _tol;
369     }
370     FaceLineIntersector():_surfaceInt(0) {}
371     ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
372   };
373   // --------------------------------------------------------------------------
374   /*!
375    * \brief Class representing topology of the hexahedron and creating a mesh
376    *        volume basing on analysis of hexahedron intersection with geometry
377    */
378   class Hexahedron
379   {
380     // --------------------------------------------------------------------------------
381     struct _Face;
382     struct _Link;
383     // --------------------------------------------------------------------------------
384     struct _Node //!< node either at a hexahedron corner or at GridLine intersection
385     {
386       const SMDS_MeshNode*     _node; // mesh node at hexahedron corner
387       const IntersectionPoint* _intPoint;
388
389       _Node(const SMDS_MeshNode* n=0, const IntersectionPoint* ip=0):_node(n), _intPoint(ip) {} 
390       const SMDS_MeshNode* Node() const { return _intPoint ? _intPoint->_node : _node; }
391       //bool IsCorner() const { return _node; }
392     };
393     // --------------------------------------------------------------------------------
394     struct _Link // link connecting two _Node's
395     {
396       _Node* _nodes[2];
397       vector< _Node>  _intNodes; // _Node's at GridLine intersections
398       vector< _Link > _splits;
399       vector< _Face*> _faces;
400     };
401     // --------------------------------------------------------------------------------
402     struct _OrientedLink
403     {
404       _Link* _link;
405       bool   _reverse;
406       _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
407       void Reverse() { _reverse = !_reverse; }
408       int NbResultLinks() const { return _link->_splits.size(); }
409       _OrientedLink ResultLink(int i) const
410       {
411         return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
412       }
413       _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
414       _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
415     };
416     // --------------------------------------------------------------------------------
417     struct _Face
418     {
419       vector< _OrientedLink > _links;
420       vector< _Link >         _polyLinks; // links added to close a polygonal face
421     };
422     // --------------------------------------------------------------------------------
423     struct _volumeDef // holder of nodes of a volume mesh element
424     {
425       vector< const SMDS_MeshNode* > _nodes;
426       vector< int >                  _quantities;
427       typedef boost::shared_ptr<_volumeDef> Ptr;
428       void set( const vector< const SMDS_MeshNode* >& nodes,
429                 const vector< int > quant = vector< int >() )
430       { _nodes = nodes; _quantities = quant; }
431       // static Ptr New( const vector< const SMDS_MeshNode* >& nodes,
432       //                 const vector< int > quant = vector< int >() )
433       // {
434       //   _volumeDef* def = new _volumeDef;
435       //   def->_nodes = nodes;
436       //   def->_quantities = quant;
437       //   return Ptr( def );
438       // }
439     };
440
441     // topology of a hexahedron
442     int   _nodeShift[8];
443     _Node _hexNodes[8];
444     _Link _hexLinks[12];
445     _Face _hexQuads[6];
446
447     // faces resulted from hexahedron intersection
448     vector< _Face > _polygons;
449
450     // computed volume elements
451     //vector< _volumeDef::Ptr > _volumeDefs;
452     _volumeDef _volumeDefs;
453
454     Grid*       _grid;
455     double      _sizeThreshold, _sideLength[3];
456     int         _nbCornerNodes, _nbIntNodes, _nbBndNodes;
457     int         _origNodeInd; // index of _hexNodes[0] node within the _grid
458     size_t      _i,_j,_k;
459
460   public:
461     Hexahedron(const double sizeThreshold, Grid* grid);
462     int MakeElements(SMESH_MesherHelper& helper);
463     void ComputeElements();
464     void Init() { init( _i, _j, _k ); }
465
466   private:
467     Hexahedron(const Hexahedron& other );
468     void init( size_t i, size_t j, size_t k );
469     void init( size_t i );
470     int  addElements(SMESH_MesherHelper& helper);
471     bool isInHole() const;
472     bool checkPolyhedronSize() const;
473     bool addHexa ();
474     bool addTetra();
475     bool addPenta();
476     bool addPyra ();
477   };
478  
479 #ifdef WITH_TBB
480   // --------------------------------------------------------------------------
481   /*!
482    * \brief Hexahedron computing volumes in one thread
483    */
484   struct ParallelHexahedron
485   {
486     vector< Hexahedron* >& _hexVec;
487     vector<int>&           _index;
488     ParallelHexahedron( vector< Hexahedron* >& hv, vector<int>& ind): _hexVec(hv), _index(ind) {}
489     void operator() ( const tbb::blocked_range<size_t>& r ) const
490     {
491       for ( size_t i = r.begin(); i != r.end(); ++i )
492         if ( Hexahedron* hex = _hexVec[ _index[i]] )
493           hex->ComputeElements();
494     }
495   };
496   // --------------------------------------------------------------------------
497   /*!
498    * \brief Structure intersecting certain nb of faces with GridLine's in one thread
499    */
500   struct ParallelIntersector
501   {
502     vector< FaceGridIntersector >& _faceVec;
503     ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
504     void operator() ( const tbb::blocked_range<size_t>& r ) const
505     {
506       for ( size_t i = r.begin(); i != r.end(); ++i )
507         _faceVec[i].Intersect();
508     }
509   };
510
511 #endif
512   //=============================================================================
513   // Implementation of internal utils
514   //=============================================================================
515   /*
516    * Remove coincident intersection points
517    */
518   void GridLine::RemoveExcessIntPoints( const double tol )
519   {
520     if ( _intPoints.size() < 2 ) return;
521
522     set< Transition > tranSet;
523     multiset< IntersectionPoint >::iterator ip1, ip2 = _intPoints.begin();
524     while ( ip2 != _intPoints.end() )
525     {
526       tranSet.clear();
527       ip1 = ip2++;
528       while ( ip2->_paramOnLine - ip1->_paramOnLine <= tol  && ip2 != _intPoints.end())
529       {
530         tranSet.insert( ip1->_transition );
531         tranSet.insert( ip2->_transition );
532         _intPoints.erase( ip1 );
533         ip1 = ip2++;
534       }
535       if ( tranSet.size() > 1 ) // points with different transition coincide
536       {
537         bool isIN  = tranSet.count( Trans_IN );
538         bool isOUT = tranSet.count( Trans_OUT );
539         if ( isIN && isOUT )
540           (*ip1)._transition = Trans_TANGENT;
541         else
542           (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
543       }
544     }
545   }
546   //================================================================================
547   /*
548    * Return "is OUT" state for nodes before the given intersection point
549    */
550   bool GridLine::GetIsOutBefore( multiset< IntersectionPoint >::iterator ip, bool prevIsOut )
551   {
552     if ( ip->_transition == Trans_IN )
553       return true;
554     if ( ip->_transition == Trans_OUT )
555       return false;
556     if ( ip->_transition == Trans_APEX )
557     {
558       // singularity point (apex of a cone)
559       if ( _intPoints.size() == 1 || ip == _intPoints.begin() )
560         return true;
561       multiset< IntersectionPoint >::iterator ipBef = ip, ipAft = ++ip;
562       if ( ipAft == _intPoints.end() )
563         return false;
564       --ipBef;
565       if ( ipBef->_transition != ipAft->_transition )
566         return ( ipBef->_transition == Trans_OUT );
567       return ( ipBef->_transition != Trans_OUT );
568     }
569     return prevIsOut; // _transition == Trans_TANGENT
570   }
571   //================================================================================
572   /*
573    * Return an iterator on GridLine's in a given direction
574    */
575   LineIndexer Grid::GetLineIndexer(size_t iDir) const
576   {
577     const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
578     const string s[] = { "X", "Y", "Z" };
579     LineIndexer li( _coords[0].size(),  _coords[1].size(),    _coords[2].size(),
580                     indices[iDir*3],    indices[iDir*3+1],    indices[iDir*3+2],
581                     s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
582     return li;
583   }
584   //=============================================================================
585   /*
586    * Creates GridLine's of the grid
587    */
588   void Grid::SetCoordinates(const vector<double>& xCoords,
589                             const vector<double>& yCoords,
590                             const vector<double>& zCoords,
591                             const TopoDS_Shape&   shape)
592   {
593     _coords[0] = xCoords;
594     _coords[1] = yCoords;
595     _coords[2] = zCoords;
596
597     // compute tolerance
598     _minCellSize = Precision::Infinite();
599     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
600     {
601       for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
602       {
603         double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
604         if ( cellLen < _minCellSize )
605           _minCellSize = cellLen;
606       }
607     }
608     if ( _minCellSize < Precision::Confusion() )
609       throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
610                                 SMESH_Comment("Too small cell size: ") << _tol );
611     _tol = _minCellSize / 1000.;
612
613     // attune grid extremities to shape bounding box computed by vertices
614     Bnd_Box shapeBox;
615     for ( TopExp_Explorer vExp( shape, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
616       shapeBox.Add( BRep_Tool::Pnt( TopoDS::Vertex( vExp.Current() )));
617     
618     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
619     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
620     double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
621                       &_coords[0].back(),  &_coords[1].back(),  &_coords[2].back() };
622     for ( int i = 0; i < 6; ++i )
623       if ( fabs( sP[i] - *cP[i] ) < _tol )
624         *cP[i] = sP[i] + _tol/1000. * ( i < 3 ? +1 : -1 );
625
626     // create lines
627     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
628     {
629       LineIndexer li = GetLineIndexer( iDir );
630       _lines[iDir].resize( li.NbLines() );
631       double len = _coords[ iDir ].back() - _coords[iDir].front();
632       gp_Vec dir( iDir==0, iDir==1, iDir==2 );
633       for ( ; li.More(); ++li )
634       {
635         GridLine& gl = _lines[iDir][ li.LineIndex() ];
636         gl._line.SetLocation(gp_Pnt(_coords[0][li.I()], _coords[1][li.J()], _coords[2][li.K()])); 
637         gl._line.SetDirection( dir );
638         gl._length = len;
639       }
640     }
641   }
642   //================================================================================
643   /*
644    * Creates all nodes
645    */
646   void Grid::ComputeNodes(SMESH_MesherHelper& helper)
647   {
648     // state of each node of the grid relative to the geomerty
649     const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
650     vector< bool > isNodeOut( nbGridNodes, false );
651     _nodes.resize( nbGridNodes, 0 );
652     _isBndNode.resize( nbGridNodes, false );
653
654     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
655     {
656       LineIndexer li = GetLineIndexer( iDir );
657
658       // find out a shift of node index while walking along a GridLine in this direction
659       li.SetIndexOnLine( 0 );
660       size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
661       li.SetIndexOnLine( 1 );
662       const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
663       
664       const vector<double> & coords = _coords[ iDir ];
665       for ( ; li.More(); ++li ) // loop on lines in iDir
666       {
667         li.SetIndexOnLine( 0 );
668         nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
669
670         GridLine& line = _lines[ iDir ][ li.LineIndex() ];
671         line.RemoveExcessIntPoints( _tol );
672         multiset< IntersectionPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
673         multiset< IntersectionPoint >::iterator ip = intPnts.begin();
674
675         bool isOut = true;
676         const double* nodeCoord = & coords[0], *coord0 = nodeCoord, *coordEnd = coord0 + coords.size();
677         double nodeParam = 0;
678         for ( ; ip != intPnts.end(); ++ip )
679         {
680           // set OUT state or just skip IN nodes before ip
681           if ( nodeParam < ip->_paramOnLine - _tol )
682           {
683             isOut = line.GetIsOutBefore( ip, isOut );
684
685             while ( nodeParam < ip->_paramOnLine - _tol )
686             {
687               if ( isOut )
688                 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = isOut;
689               if ( ++nodeCoord <  coordEnd )
690                 nodeParam = *nodeCoord - *coord0;
691               else
692                 break;
693             }
694             if ( nodeCoord == coordEnd ) break;
695           }
696           // create a mesh node on a GridLine at ip if it does not coincide with a grid node
697           if ( nodeParam > ip->_paramOnLine + _tol )
698           {
699             li.SetIndexOnLine( 0 );
700             double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
701             xyz[ li._iConst ] += ip->_paramOnLine;
702             ip->_node = helper.AddNode( xyz[0], xyz[1], xyz[2] );
703             ip->_indexOnLine = nodeCoord-coord0-1;
704           }
705           // create a mesh node at ip concident with a grid node
706           else
707           {
708             int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
709             if ( ! _nodes[ nodeIndex ] )
710             {
711               li.SetIndexOnLine( nodeCoord-coord0 );
712               double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
713               _nodes[ nodeIndex ] = helper.AddNode( xyz[0], xyz[1], xyz[2] );
714               _isBndNode[ nodeIndex ] = true;
715             }
716             //ip->_node = _nodes[ nodeIndex ];
717             ip->_indexOnLine = nodeCoord-coord0;
718             if ( ++nodeCoord < coordEnd )
719               nodeParam = *nodeCoord - *coord0;
720           }
721         }
722         // set OUT state to nodes after the last ip
723         for ( ; nodeCoord < coordEnd; ++nodeCoord )
724           isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = true;
725       }
726     }
727
728     // Create mesh nodes at !OUT nodes of the grid
729
730     for ( size_t z = 0; z < _coords[2].size(); ++z )
731       for ( size_t y = 0; y < _coords[1].size(); ++y )
732         for ( size_t x = 0; x < _coords[0].size(); ++x )
733         {
734           size_t nodeIndex = NodeIndex( x, y, z );
735           if ( !isNodeOut[ nodeIndex ] && !_nodes[ nodeIndex] )
736             _nodes[ nodeIndex ] = helper.AddNode( _coords[0][x], _coords[1][y], _coords[2][z] );
737         }
738
739 #ifdef _MY_DEBUG_
740     // check validity of transitions
741     const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
742     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
743     {
744       LineIndexer li = GetLineIndexer( iDir );
745       for ( ; li.More(); ++li )
746       {
747         multiset< IntersectionPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
748         if ( intPnts.empty() ) continue;
749         if ( intPnts.size() == 1 )
750         {
751           if ( intPnts.begin()->_transition != Trans_TANGENT &&
752                intPnts.begin()->_transition != Trans_APEX )
753           throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
754                                     SMESH_Comment("Wrong SOLE transition of GridLine (")
755                                     << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
756                                     << ") along " << li._nameConst
757                                     << ": " << trName[ intPnts.begin()->_transition] );
758         }
759         else
760         {
761           if ( intPnts.begin()->_transition == Trans_OUT )
762             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
763                                       SMESH_Comment("Wrong START transition of GridLine (")
764                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
765                                       << ") along " << li._nameConst
766                                       << ": " << trName[ intPnts.begin()->_transition ]);
767           if ( intPnts.rbegin()->_transition == Trans_IN )
768             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
769                                       SMESH_Comment("Wrong END transition of GridLine (")
770                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
771                                       << ") along " << li._nameConst
772                                     << ": " << trName[ intPnts.rbegin()->_transition ]);
773         }
774       }
775     }
776 #endif
777   }
778
779   //=============================================================================
780   /*
781    * Checks if the face is encosed by the grid
782    */
783   bool FaceGridIntersector::IsInGrid(const Bnd_Box& gridBox)
784   {
785     double x0,y0,z0, x1,y1,z1;
786     const Bnd_Box& faceBox = GetFaceBndBox();
787     faceBox.Get(x0,y0,z0, x1,y1,z1);
788
789     if ( !gridBox.IsOut( gp_Pnt( x0,y0,z0 )) &&
790          !gridBox.IsOut( gp_Pnt( x1,y1,z1 )))
791       return true;
792
793     double X0,Y0,Z0, X1,Y1,Z1;
794     gridBox.Get(X0,Y0,Z0, X1,Y1,Z1);
795     double faceP[6] = { x0,y0,z0, x1,y1,z1 };
796     double gridP[6] = { X0,Y0,Z0, X1,Y1,Z1 };
797     gp_Dir axes[3]  = { gp::DX(), gp::DY(), gp::DZ() };
798     for ( int iDir = 0; iDir < 6; ++iDir )
799     {
800       if ( iDir < 3  && gridP[ iDir ] <= faceP[ iDir ] ) continue;
801       if ( iDir >= 3 && gridP[ iDir ] >= faceP[ iDir ] ) continue;
802
803       // check if the face intersects a side of a gridBox
804
805       gp_Pnt p = iDir < 3 ? gp_Pnt( X0,Y0,Z0 ) : gp_Pnt( X1,Y1,Z1 );
806       gp_Ax1 norm( p, axes[ iDir % 3 ] );
807       if ( iDir < 3 ) norm.Reverse();
808
809       gp_XYZ O = norm.Location().XYZ(), N = norm.Direction().XYZ();
810
811       TopLoc_Location loc = _face.Location();
812       Handle(Poly_Triangulation) aPoly = BRep_Tool::Triangulation(_face,loc);
813       if ( !aPoly.IsNull() )
814       {
815         if ( !loc.IsIdentity() )
816         {
817           norm.Transform( loc.Transformation().Inverted() );
818           O = norm.Location().XYZ(), N = norm.Direction().XYZ();
819         }
820         const double deflection = aPoly->Deflection();
821
822         const TColgp_Array1OfPnt& nodes = aPoly->Nodes();
823         for ( int i = nodes.Lower(); i <= nodes.Upper(); ++i )
824           if (( nodes( i ).XYZ() - O ) * N > _grid->_tol + deflection )
825             return false;
826       }
827       else
828       {
829         BRepAdaptor_Surface surf( _face );
830         double u0, u1, v0, v1, du, dv, u, v;
831         BRepTools::UVBounds( _face, u0, u1, v0, v1);
832         if ( surf.GetType() == GeomAbs_Plane ) {
833           du = u1 - u0, dv = v1 - v0;
834         }
835         else {
836           du = surf.UResolution( _grid->_minCellSize / 10. );
837           dv = surf.VResolution( _grid->_minCellSize / 10. );
838         }
839         for ( u = u0, v = v0; u <= u1 && v <= v1; u += du, v += dv )
840         {
841           gp_Pnt p = surf.Value( u, v );
842           if (( p.XYZ() - O ) * N > _grid->_tol )
843           {
844             TopAbs_State state = GetCurveFaceIntersector()->ClassifyUVPoint(gp_Pnt2d( u, v ));
845             if ( state == TopAbs_IN || state == TopAbs_ON )
846               return false;
847           }
848         }
849       }
850     }
851     return true;
852   }
853   //=============================================================================
854   /*
855    * Intersects TopoDS_Face with all GridLine's
856    */
857   void FaceGridIntersector::Intersect()
858   {
859     FaceLineIntersector intersector;
860     intersector._surfaceInt = GetCurveFaceIntersector();
861     intersector._tol        = _grid->_tol;
862     intersector._transOut   = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
863     intersector._transIn    = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
864
865     typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
866     PIntFun interFunction;
867
868     BRepAdaptor_Surface surf( _face );
869     switch ( surf.GetType() ) {
870     case GeomAbs_Plane:
871       intersector._plane = surf.Plane();
872       interFunction = &FaceLineIntersector::IntersectWithPlane;
873       break;
874     case GeomAbs_Cylinder:
875       intersector._cylinder = surf.Cylinder();
876       interFunction = &FaceLineIntersector::IntersectWithCylinder;
877       break;
878     case GeomAbs_Cone:
879       intersector._cone = surf.Cone();
880       interFunction = &FaceLineIntersector::IntersectWithCone;
881       break;
882     case GeomAbs_Sphere:
883       intersector._sphere = surf.Sphere();
884       interFunction = &FaceLineIntersector::IntersectWithSphere;
885       break;
886     case GeomAbs_Torus:
887       intersector._torus = surf.Torus();
888       interFunction = &FaceLineIntersector::IntersectWithTorus;
889       break;
890     default:
891       interFunction = &FaceLineIntersector::IntersectWithSurface;
892     }
893
894     _intersections.clear();
895     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
896     {
897       if ( surf.GetType() == GeomAbs_Plane )
898       {
899         // check if all lines in this direction are parallel to a plane
900         if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
901                                                  Precision::Angular()))
902           continue;
903         // find out a transition, that is the same for all lines of a direction
904         gp_Dir plnNorm = intersector._plane.Axis().Direction();
905         gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
906         intersector._transition =
907           ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
908       }
909       if ( surf.GetType() == GeomAbs_Cylinder )
910       {
911         // check if all lines in this direction are parallel to a cylinder
912         if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
913                                                       Precision::Angular()))
914           continue;
915       }
916
917       // intersect the grid lines with the face
918       for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
919       {
920         GridLine& gridLine = _grid->_lines[iDir][iL];
921         if ( _bndBox.IsOut( gridLine._line )) continue;
922
923         intersector._intPoints.clear();
924         (intersector.*interFunction)( gridLine );
925         for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
926           _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
927       }
928     }
929   }
930   //================================================================================
931   /*
932    * Return true if (_u,_v) is on the face
933    */
934   bool FaceLineIntersector::UVIsOnFace() const
935   {
936     TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
937     return ( state == TopAbs_IN || state == TopAbs_ON );
938   }
939   //================================================================================
940   /*
941    * Store an intersection if it is IN or ON the face
942    */
943   void FaceLineIntersector::addIntPoint(const bool toClassify)
944   {
945     if ( !toClassify || UVIsOnFace() )
946     {
947       IntersectionPoint p;
948       p._paramOnLine = _w;
949       p._transition  = _transition;
950       _intPoints.push_back( p );
951     }
952   }
953   //================================================================================
954   /*
955    * Intersect a line with a plane
956    */
957   void FaceLineIntersector::IntersectWithPlane   (const GridLine& gridLine)
958   {
959     IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
960     _w = linPlane.ParamOnConic(1);
961     if ( isParamOnLineOK( gridLine._length ))
962     {
963       ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
964       addIntPoint();
965     }
966   }
967   //================================================================================
968   /*
969    * Intersect a line with a cylinder
970    */
971   void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
972   {
973     IntAna_IntConicQuad linCylinder( gridLine._line,_cylinder);
974     if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
975     {
976       _w = linCylinder.ParamOnConic(1);
977       if ( linCylinder.NbPoints() == 1 )
978         _transition = Trans_TANGENT;
979       else
980         _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
981       if ( isParamOnLineOK( gridLine._length ))
982       {
983         ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
984         addIntPoint();
985       }
986       if ( linCylinder.NbPoints() > 1 )
987       {
988         _w = linCylinder.ParamOnConic(2);
989         if ( isParamOnLineOK( gridLine._length ))
990         {
991           ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
992           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
993           addIntPoint();
994         }
995       }
996     }
997   }
998   //================================================================================
999   /*
1000    * Intersect a line with a cone
1001    */
1002   void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1003   {
1004     IntAna_IntConicQuad linCone(gridLine._line,_cone);
1005     if ( !linCone.IsDone() ) return;
1006     gp_Pnt P;
1007     gp_Vec du, dv, norm;
1008     for ( int i = 1; i <= linCone.NbPoints(); ++i )
1009     {
1010       _w = linCone.ParamOnConic( i );
1011       if ( !isParamOnLineOK( gridLine._length )) continue;
1012       ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1013       if ( UVIsOnFace() )
1014       {
1015         ElSLib::D1( _u, _v, _cone, P, du, dv );
1016         norm = du ^ dv;
1017         double normSize2 = norm.SquareMagnitude();
1018         if ( normSize2 > Precision::Angular() * Precision::Angular() )
1019         {
1020           double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1021           cos /= sqrt( normSize2 );
1022           if ( cos < -Precision::Angular() )
1023             _transition = _transIn;
1024           else if ( cos > Precision::Angular() )
1025             _transition = _transOut;
1026           else
1027             _transition = Trans_TANGENT;
1028         }
1029         else
1030         {
1031           _transition = Trans_APEX;
1032         }
1033         addIntPoint( /*toClassify=*/false);
1034       }
1035     }
1036   }
1037   //================================================================================
1038   /*
1039    * Intersect a line with a sphere
1040    */
1041   void FaceLineIntersector::IntersectWithSphere  (const GridLine& gridLine)
1042   {
1043     IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1044     if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1045     {
1046       _w = linSphere.ParamOnConic(1);
1047       if ( linSphere.NbPoints() == 1 )
1048         _transition = Trans_TANGENT;
1049       else
1050         _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1051       if ( isParamOnLineOK( gridLine._length ))
1052       {
1053         ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1054         addIntPoint();
1055       }
1056       if ( linSphere.NbPoints() > 1 )
1057       {
1058         _w = linSphere.ParamOnConic(2);
1059         if ( isParamOnLineOK( gridLine._length ))
1060         {
1061           ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
1062           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1063           addIntPoint();
1064         }
1065       }
1066     }
1067   }
1068   //================================================================================
1069   /*
1070    * Intersect a line with a torus
1071    */
1072   void FaceLineIntersector::IntersectWithTorus   (const GridLine& gridLine)
1073   {
1074     IntAna_IntLinTorus linTorus(gridLine._line,_torus);
1075     if ( !linTorus.IsDone()) return;
1076     gp_Pnt P;
1077     gp_Vec du, dv, norm;
1078     for ( int i = 1; i <= linTorus.NbPoints(); ++i )
1079     {
1080       _w = linTorus.ParamOnLine( i );
1081       if ( !isParamOnLineOK( gridLine._length )) continue;
1082       linTorus.ParamOnTorus( i, _u,_v );
1083       if ( UVIsOnFace() )
1084       {
1085         ElSLib::D1( _u, _v, _torus, P, du, dv );
1086         norm = du ^ dv;
1087         double normSize = norm.Magnitude();
1088         double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1089         cos /= normSize;
1090         if ( cos < -Precision::Angular() )
1091           _transition = _transIn;
1092         else if ( cos > Precision::Angular() )
1093           _transition = _transOut;
1094         else
1095           _transition = Trans_TANGENT;
1096         addIntPoint( /*toClassify=*/false);
1097       }
1098     }
1099   }
1100   //================================================================================
1101   /*
1102    * Intersect a line with a non-analytical surface
1103    */
1104   void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
1105   {
1106     _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
1107     if ( !_surfaceInt->IsDone() ) return;
1108     for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
1109     {
1110       _transition = Transition( _surfaceInt->Transition( i ) );
1111       _w = _surfaceInt->WParameter( i );
1112       addIntPoint(/*toClassify=*/false);
1113     }
1114   }
1115   //================================================================================
1116   /*
1117    * check if its face can be safely intersected in a thread
1118    */
1119   bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
1120   {
1121     bool isSafe = true;
1122
1123     // check surface
1124     TopLoc_Location loc;
1125     Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
1126     Handle(Geom_RectangularTrimmedSurface) ts =
1127       Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
1128     while( !ts.IsNull() ) {
1129       surf = ts->BasisSurface();
1130       ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
1131     }
1132     if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
1133          surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
1134       if ( !noSafeTShapes.insert((const Standard_Transient*) _face.TShape() ).second )
1135         isSafe = false;
1136
1137     double f, l;
1138     TopExp_Explorer exp( _face, TopAbs_EDGE );
1139     for ( ; exp.More(); exp.Next() )
1140     {
1141       bool edgeIsSafe = true;
1142       const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1143       // check 3d curve
1144       {
1145         Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
1146         if ( !c.IsNull() )
1147         {
1148           Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1149           while( !tc.IsNull() ) {
1150             c = tc->BasisCurve();
1151             tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1152           }
1153           if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
1154                c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
1155             edgeIsSafe = false;
1156         }
1157       }
1158       // check 2d curve
1159       if ( edgeIsSafe )
1160       {
1161         Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
1162         if ( !c2.IsNull() )
1163         {
1164           Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1165           while( !tc.IsNull() ) {
1166             c2 = tc->BasisCurve();
1167             tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1168           }
1169           if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
1170                c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
1171             edgeIsSafe = false;
1172         }
1173       }
1174       if ( !edgeIsSafe && !noSafeTShapes.insert((const Standard_Transient*) e.TShape() ).second )
1175         isSafe = false;
1176     }
1177     return isSafe;
1178   }
1179   //================================================================================
1180   /*!
1181    * \brief Creates topology of the hexahedron
1182    */
1183   Hexahedron::Hexahedron(const double sizeThreshold, Grid* grid)
1184     : _grid( grid ), _sizeThreshold( sizeThreshold ), _nbIntNodes(0)
1185   {
1186     _polygons.reserve(100); // to avoid reallocation;
1187
1188     //set nodes shift within grid->_nodes from the node 000 
1189     size_t dx = _grid->NodeIndexDX();
1190     size_t dy = _grid->NodeIndexDY();
1191     size_t dz = _grid->NodeIndexDZ();
1192     size_t i000 = 0;
1193     size_t i100 = i000 + dx;
1194     size_t i010 = i000 + dy;
1195     size_t i110 = i010 + dx;
1196     size_t i001 = i000 + dz;
1197     size_t i101 = i100 + dz;
1198     size_t i011 = i010 + dz;
1199     size_t i111 = i110 + dz;
1200     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
1201     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
1202     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
1203     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
1204     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
1205     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
1206     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
1207     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
1208
1209     vector< int > idVec;
1210     // set nodes to links
1211     for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
1212     {
1213       SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
1214       _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
1215       link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
1216       link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
1217       link._intNodes.reserve( 10 ); // to avoid reallocation
1218       link._splits.reserve( 10 );
1219     }
1220
1221     // set links to faces
1222     int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
1223     for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
1224     {
1225       SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
1226       _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
1227       bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
1228                        faceID == SMESH_Block::ID_Fx1z ||
1229                        faceID == SMESH_Block::ID_F0yz );
1230       quad._links.resize(4);
1231       vector<_OrientedLink>::iterator         frwLinkIt = quad._links.begin();
1232       vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
1233       for ( int i = 0; i < 4; ++i )
1234       {
1235         bool revLink = revFace;
1236         if ( i > 1 ) // reverse links u1 and v0
1237           revLink = !revLink;
1238         _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
1239         link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
1240                               revLink );
1241       }
1242     }
1243   }
1244   //================================================================================
1245   /*!
1246    * \brief Copy constructor
1247    */
1248   Hexahedron::Hexahedron( const Hexahedron& other )
1249     :_grid( other._grid ), _sizeThreshold( other._sizeThreshold ), _nbIntNodes(0)
1250   {
1251     _polygons.reserve(100); // to avoid reallocation;
1252
1253     for ( int i = 0; i < 8; ++i )
1254       _nodeShift[i] = other._nodeShift[i];
1255
1256     for ( int i = 0; i < 12; ++i )
1257     {
1258       const _Link& srcLink = other._hexLinks[ i ];
1259       _Link&       tgtLink = this->_hexLinks[ i ];
1260       tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
1261       tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
1262       tgtLink._intNodes.reserve( 10 ); // to avoid reallocation
1263       tgtLink._splits.reserve( 10 );
1264     }
1265
1266     for ( int i = 0; i < 6; ++i )
1267     {
1268       const _Face& srcQuad = other._hexQuads[ i ];
1269       _Face&       tgtQuad = this->_hexQuads[ i ];
1270       tgtQuad._links.resize(4);
1271       for ( int j = 0; j < 4; ++j )
1272       {
1273         const _OrientedLink& srcLink = srcQuad._links[ j ];
1274         _OrientedLink&       tgtLink = tgtQuad._links[ j ];
1275         tgtLink._reverse = srcLink._reverse;
1276         tgtLink._link    = _hexLinks + ( srcLink._link - other._hexLinks );
1277       }
1278     }
1279   }
1280   
1281   //================================================================================
1282   /*!
1283    * \brief Initializes its data by given grid cell
1284    */
1285   void Hexahedron::init( size_t i, size_t j, size_t k )
1286   {
1287     _i = i; _j = j; _k = k;
1288     // set nodes of grid to nodes of the hexahedron and
1289     // count nodes at hexahedron corners located IN and ON geometry
1290     _nbCornerNodes = _nbBndNodes = 0;
1291     _origNodeInd   = _grid->NodeIndex( i,j,k );
1292     for ( int iN = 0; iN < 8; ++iN )
1293     {
1294       _hexNodes[iN]._node = _grid->_nodes[ _origNodeInd + _nodeShift[iN] ];
1295       _nbCornerNodes += bool( _hexNodes[iN]._node );
1296       _nbBndNodes    += _grid->_isBndNode[ _origNodeInd + _nodeShift[iN] ];
1297     }
1298
1299     _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
1300     _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
1301     _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
1302
1303     if ( _nbCornerNodes < 8 && _nbIntNodes + _nbCornerNodes > 3)
1304     {
1305       _Link split;
1306       // create sub-links (_splits) by splitting links with _intNodes
1307       for ( int iLink = 0; iLink < 12; ++iLink )
1308       {
1309         _Link& link = _hexLinks[ iLink ];
1310         link._splits.clear();
1311         split._nodes[ 0 ] = link._nodes[0];
1312         for ( size_t i = 0; i < link._intNodes.size(); ++ i )
1313         {
1314           if ( split._nodes[ 0 ]->Node() )
1315           {
1316             split._nodes[ 1 ] = &link._intNodes[i];
1317             link._splits.push_back( split );
1318           }
1319           split._nodes[ 0 ] = &link._intNodes[i];
1320         }
1321         if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() )
1322         {
1323           split._nodes[ 1 ] = link._nodes[1];
1324           link._splits.push_back( split );
1325         }
1326       }
1327     }
1328   }
1329   //================================================================================
1330   /*!
1331    * \brief Initializes its data by given grid cell (countered from zero)
1332    */
1333   void Hexahedron::init( size_t iCell )
1334   {
1335     size_t iNbCell = _grid->_coords[0].size() - 1;
1336     size_t jNbCell = _grid->_coords[1].size() - 1;
1337     _i = iCell % iNbCell;
1338     _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
1339     _k = iCell / iNbCell / jNbCell;
1340     init( _i, _j, _k );
1341   }
1342
1343   //================================================================================
1344   /*!
1345    * \brief Compute mesh volumes resulted from intersection of the Hexahedron
1346    */
1347   void Hexahedron::ComputeElements()
1348   {
1349     Init();
1350
1351     if ( _nbCornerNodes + _nbIntNodes < 4 )
1352       return;
1353
1354     if ( _nbBndNodes == _nbCornerNodes && isInHole() )
1355       return;
1356
1357     _polygons.clear();
1358
1359     vector<const SMDS_MeshNode* > polyhedraNodes;
1360     vector<int>                   quantities;
1361
1362     // create polygons from quadrangles and get their nodes
1363
1364     vector<_Node*> nodes;
1365     nodes.reserve( _nbCornerNodes + _nbIntNodes );
1366
1367     _Link polyLink;
1368     polyLink._faces.reserve( 1 );
1369
1370     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
1371     {
1372       const _Face& quad = _hexQuads[ iF ] ;
1373
1374       _polygons.resize( _polygons.size() + 1 );
1375       _Face& polygon = _polygons.back();
1376       polygon._links.clear();
1377       polygon._polyLinks.clear(); polygon._polyLinks.reserve( 10 );
1378
1379       // add splits of a link to a polygon and collect info on nodes
1380       //int nbIn = 0, nbOut = 0, nbCorners = 0;
1381       nodes.clear();
1382       for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
1383       {
1384         int nbSpits = quad._links[ iE ].NbResultLinks();
1385         for ( int iS = 0; iS < nbSpits; ++iS )
1386         {
1387           _OrientedLink split = quad._links[ iE ].ResultLink( iS );
1388           _Node* n = split.FirstNode();
1389           if ( !polygon._links.empty() )
1390           {
1391             _Node* nPrev = polygon._links.back().LastNode();
1392             if ( nPrev != n )
1393             {
1394               polyLink._nodes[0] = nPrev;
1395               polyLink._nodes[1] = n;
1396               polygon._polyLinks.push_back( polyLink );
1397               polygon._links.push_back( _OrientedLink( &polygon._polyLinks.back() ));
1398               nodes.push_back( nPrev );
1399             }
1400           }
1401           polygon._links.push_back( split );
1402           nodes.push_back( n );
1403         }
1404       }
1405       if ( polygon._links.size() > 1 )
1406       {
1407         _Node* n1 = polygon._links.back().LastNode();
1408         _Node* n2 = polygon._links.front().FirstNode();
1409         if ( n1 != n2 )
1410         {
1411           polyLink._nodes[0] = n1;
1412           polyLink._nodes[1] = n2;
1413           polygon._polyLinks.push_back( polyLink );
1414           polygon._links.push_back( _OrientedLink( &polygon._polyLinks.back() ));
1415           nodes.push_back( n1 );
1416         }
1417         // add polygon to its links
1418         for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1419           polygon._links[ iL ]._link->_faces.push_back( &polygon );
1420         // store polygon nodes
1421         quantities.push_back( nodes.size() );
1422         for ( size_t i = 0; i < nodes.size(); ++i )
1423           polyhedraNodes.push_back( nodes[i]->Node() );
1424       }
1425       else
1426       {
1427         _polygons.resize( _polygons.size() - 1 );
1428       }
1429     }
1430
1431     // create polygons closing holes in a polyhedron
1432
1433     // find free links
1434     vector< _OrientedLink* > freeLinks;
1435     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1436     {
1437       _Face& polygon = _polygons[ iP ];
1438       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1439         if ( polygon._links[ iL ]._link->_faces.size() < 2 )
1440           freeLinks.push_back( & polygon._links[ iL ]);
1441     }
1442     // make closed chains of free links
1443     int nbFreeLinks = freeLinks.size();
1444     if ( 0 < nbFreeLinks && nbFreeLinks < 3 ) return;
1445     while ( nbFreeLinks > 0 )
1446     {
1447       nodes.clear();
1448       _polygons.resize( _polygons.size() + 1 );
1449       _Face& polygon = _polygons.back();
1450       polygon._links.clear();
1451
1452       // get a remaining link to start from
1453       _OrientedLink* curLink = 0;
1454       for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
1455         if (( curLink = freeLinks[ iL ] ))
1456           freeLinks[ iL ] = 0;
1457       nodes.push_back( curLink->LastNode() );
1458       polygon._links.push_back( *curLink );
1459
1460       // find all links connected to curLink
1461       _Node* curNode = 0;
1462       do
1463       {
1464         curNode = curLink->FirstNode();
1465         curLink = 0;
1466         for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
1467           if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
1468           {
1469             curLink = freeLinks[ iL ];
1470             freeLinks[ iL ] = 0;
1471             nodes.push_back( curNode );
1472             polygon._links.push_back( *curLink );
1473           }
1474       } while ( curLink );
1475
1476       nbFreeLinks -= polygon._links.size();
1477
1478       if ( curNode != nodes.front() || polygon._links.size() < 3 )
1479         return; // closed polygon not found -> invalid polyhedron
1480
1481       quantities.push_back( nodes.size() );
1482       for ( size_t i = 0; i < nodes.size(); ++i )
1483         polyhedraNodes.push_back( nodes[i]->Node() );
1484
1485       // add polygon to its links and reverse links
1486       for ( size_t i = 0; i < polygon._links.size(); ++i )
1487       {
1488         polygon._links[i].Reverse();
1489         polygon._links[i]._link->_faces.push_back( &polygon );
1490       }
1491
1492       //const size_t firstPoly = _polygons.size();
1493     }
1494
1495     if ( ! checkPolyhedronSize() )
1496     {
1497       return;
1498     }
1499
1500     // create a classic cell if possible
1501     const int nbNodes = _nbCornerNodes + _nbIntNodes;
1502     bool isClassicElem = false;
1503     if (      nbNodes == 8 && _polygons.size() == 6 ) isClassicElem = addHexa();
1504     else if ( nbNodes == 4 && _polygons.size() == 4 ) isClassicElem = addTetra();
1505     else if ( nbNodes == 6 && _polygons.size() == 5 ) isClassicElem = addPenta();
1506     else if ( nbNodes == 5 && _polygons.size() == 5 ) isClassicElem = addPyra ();
1507     if ( !isClassicElem )
1508       _volumeDefs.set( polyhedraNodes, quantities );
1509   }
1510   //================================================================================
1511   /*!
1512    * \brief Create elements in the mesh
1513    */
1514   int Hexahedron::MakeElements(SMESH_MesherHelper& helper)
1515   {
1516     SMESHDS_Mesh* mesh = helper.GetMeshDS();
1517
1518     size_t nbCells[3] = { _grid->_coords[0].size() - 1,
1519                           _grid->_coords[1].size() - 1,
1520                           _grid->_coords[2].size() - 1 };
1521     const size_t nbGridCells = nbCells[0] *nbCells [1] * nbCells[2];
1522     vector< Hexahedron* > intersectedHex( nbGridCells, 0 );
1523     int nbIntHex = 0;
1524
1525     // set intersection nodes from GridLine's to links of intersectedHex
1526     int i,j,k, iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
1527     for ( int iDir = 0; iDir < 3; ++iDir )
1528     {
1529       int dInd[4][3] = { {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
1530       dInd[1][ iDirOther[iDir][0] ] = -1;
1531       dInd[2][ iDirOther[iDir][1] ] = -1;
1532       dInd[3][ iDirOther[iDir][0] ] = -1; dInd[3][ iDirOther[iDir][1] ] = -1;
1533       // loop on GridLine's parallel to iDir
1534       LineIndexer lineInd = _grid->GetLineIndexer( iDir );
1535       for ( ; lineInd.More(); ++lineInd )
1536       {
1537         GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
1538         multiset< IntersectionPoint >::const_iterator ip = line._intPoints.begin();
1539         for ( ; ip != line._intPoints.end(); ++ip )
1540         {
1541           if ( !ip->_node ) continue;
1542           lineInd.SetIndexOnLine( ip->_indexOnLine );
1543           for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
1544           {
1545             i = int(lineInd.I()) + dInd[iL][0];
1546             j = int(lineInd.J()) + dInd[iL][1];
1547             k = int(lineInd.K()) + dInd[iL][2];
1548             if ( i < 0 || i >= nbCells[0] ||
1549                  j < 0 || j >= nbCells[1] ||
1550                  k < 0 || k >= nbCells[2] ) continue;
1551
1552             const size_t hexIndex = _grid->CellIndex( i,j,k );
1553             Hexahedron *& hex = intersectedHex[ hexIndex ];
1554             if ( !hex)
1555             {
1556               hex = new Hexahedron( *this );
1557               hex->_i = i;
1558               hex->_j = j;
1559               hex->_k = k;
1560               ++nbIntHex;
1561             }
1562             const int iLink = iL + iDir * 4;
1563             hex->_hexLinks[iLink]._intNodes.push_back( _Node( 0, &(*ip) ));
1564             hex->_nbIntNodes++;
1565           }
1566         }
1567       }
1568     }
1569
1570     // add not split hexadrons to the mesh
1571     int nbAdded = 0;
1572     vector<int> intHexInd( nbIntHex );
1573     nbIntHex = 0;
1574     for ( size_t i = 0; i < intersectedHex.size(); ++i )
1575     {
1576       Hexahedron * & hex = intersectedHex[ i ];
1577       if ( hex )
1578       {
1579         intHexInd[ nbIntHex++ ] = i;
1580         if ( hex->_nbIntNodes > 0 ) continue;
1581         init( hex->_i, hex->_j, hex->_k );
1582       }
1583       else
1584       {    
1585         init( i );
1586       }
1587       if ( _nbCornerNodes == 8 && ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
1588       {
1589         // order of _hexNodes is defined by enum SMESH_Block::TShapeID
1590         SMDS_MeshElement* el =
1591           mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
1592                            _hexNodes[3].Node(), _hexNodes[1].Node(),
1593                            _hexNodes[4].Node(), _hexNodes[6].Node(),
1594                            _hexNodes[7].Node(), _hexNodes[5].Node() );
1595         mesh->SetMeshElementOnShape( el, helper.GetSubShapeID() );
1596         ++nbAdded;
1597         if ( hex )
1598         {
1599           delete hex;
1600           intersectedHex[ i ] = 0;
1601           --nbIntHex;
1602         }
1603       }
1604       else if ( _nbCornerNodes > 3  && !hex )
1605       {
1606         // all intersection of hex with geometry are at grid nodes
1607         hex = new Hexahedron( *this );
1608         hex->init( i );
1609         intHexInd.push_back(0);
1610         intHexInd[ nbIntHex++ ] = i;
1611       }
1612     }
1613
1614     // add elements resulted from hexadron intersection
1615 #ifdef WITH_TBB
1616     intHexInd.resize( nbIntHex );
1617     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, nbIntHex ),
1618                         ParallelHexahedron( intersectedHex, intHexInd ),
1619                         tbb::simple_partitioner()); // ComputeElements() is called here
1620     for ( size_t i = 0; i < intHexInd.size(); ++i )
1621       if ( Hexahedron * hex = intersectedHex[ intHexInd[ i ]] )
1622         nbAdded += hex->addElements( helper );
1623 #else
1624     for ( size_t i = 0; i < intHexInd.size(); ++i )
1625       if ( Hexahedron * hex = intersectedHex[ intHexInd[ i ]] )
1626       {
1627         hex->ComputeElements();
1628         nbAdded += hex->addElements( helper );
1629       }
1630 #endif
1631
1632     for ( size_t i = 0; i < intersectedHex.size(); ++i )
1633       if ( intersectedHex[ i ] )
1634         delete intersectedHex[ i ];
1635
1636     return nbAdded;
1637   }
1638
1639   //================================================================================
1640   /*!
1641    * \brief Adds computed elements to the mesh
1642    */
1643   int Hexahedron::addElements(SMESH_MesherHelper& helper)
1644   {
1645     int nbAdded = 0;
1646     // add elements resulted from hexahedron intersection
1647     //for ( size_t i = 0; i < _volumeDefs.size(); ++i )
1648     {
1649       vector< const SMDS_MeshNode* >& nodes = _volumeDefs._nodes;
1650       
1651       if ( !_volumeDefs._quantities.empty() )
1652       {
1653         helper.AddPolyhedralVolume( nodes, _volumeDefs._quantities );
1654       }
1655       else
1656       {
1657         switch ( nodes.size() )
1658         {
1659         case 8: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
1660                                   nodes[4],nodes[5],nodes[6],nodes[7] );
1661           break;
1662         case 4: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
1663           break;
1664         case 6: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3], nodes[4],nodes[5] );
1665           break;
1666         case 5:
1667           helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
1668           break;
1669         }
1670       }
1671       nbAdded += int ( _volumeDefs._nodes.size() > 0 );
1672     }
1673
1674     return nbAdded;
1675   }
1676   //================================================================================
1677   /*!
1678    * \brief Return true if the element is in a hole
1679    */
1680   bool Hexahedron::isInHole() const
1681   {
1682     const int ijk[3] = { _i, _j, _k };
1683     IntersectionPoint curIntPnt;
1684
1685     // consider a cell to be in a hole if all links in any direction
1686     // comes OUT of geometry
1687     for ( int iDir = 0; iDir < 3; ++iDir )
1688     {
1689       const vector<double>& coords = _grid->_coords[ iDir ];
1690       LineIndexer               li = _grid->GetLineIndexer( iDir );
1691       li.SetIJK( _i,_j,_k );
1692       size_t lineIndex[4] = { li.LineIndex  (),
1693                               li.LineIndex10(),
1694                               li.LineIndex01(),
1695                               li.LineIndex11() };
1696       bool allLinksOut = true, hasLinks = false;
1697       for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
1698       {
1699         const _Link& link = _hexLinks[ iL + 4*iDir ];
1700         // check transition of the first node of a link
1701         const IntersectionPoint* firstIntPnt = 0;
1702         if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
1703         {
1704           curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0];
1705           const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
1706           multiset< IntersectionPoint >::const_iterator ip =
1707             line._intPoints.upper_bound( curIntPnt );
1708           --ip;
1709           firstIntPnt = &(*ip);
1710         }
1711         else if ( !link._intNodes.empty() )
1712         {
1713           firstIntPnt = link._intNodes[0]._intPoint;
1714         }
1715
1716         if ( firstIntPnt )
1717         {
1718           hasLinks = true;
1719           allLinksOut = ( firstIntPnt->_transition == Trans_OUT );
1720         }
1721       }
1722       if ( hasLinks && allLinksOut )
1723         return true;
1724     }
1725     return false;
1726   }
1727
1728   //================================================================================
1729   /*!
1730    * \brief Return true if a polyhedron passes _sizeThreshold criterion
1731    */
1732   bool Hexahedron::checkPolyhedronSize() const
1733   {
1734     double volume = 0;
1735     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1736     {
1737       const _Face& polygon = _polygons[iP];
1738       gp_XYZ area (0,0,0);
1739       SMESH_TNodeXYZ p1 ( polygon._links[ 0 ].FirstNode()->Node() );
1740       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1741       {
1742         SMESH_TNodeXYZ p2 ( polygon._links[ iL ].LastNode()->Node() );
1743         area += p1 ^ p2;
1744         p1 = p2;
1745       }
1746       volume += p1 * area;
1747     }
1748     volume /= 6;
1749
1750     double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
1751
1752     return volume > initVolume / _sizeThreshold;
1753   }
1754   //================================================================================
1755   /*!
1756    * \brief Tries to create a hexahedron
1757    */
1758   bool Hexahedron::addHexa()
1759   {
1760     if ( _polygons[0]._links.size() != 4 ||
1761          _polygons[1]._links.size() != 4 ||
1762          _polygons[2]._links.size() != 4 ||
1763          _polygons[3]._links.size() != 4 ||
1764          _polygons[4]._links.size() != 4 ||
1765          _polygons[5]._links.size() != 4   )
1766       return false;
1767     const SMDS_MeshNode* nodes[8];
1768     int nbN = 0;
1769     for ( int iL = 0; iL < 4; ++iL )
1770     {
1771       // a base node
1772       nodes[iL] = _polygons[0]._links[iL].FirstNode()->Node();
1773       ++nbN;
1774
1775       // find a top node above the base node
1776       _Link* link = _polygons[0]._links[iL]._link;
1777       ASSERT( link->_faces.size() > 1 );
1778       // a quadrangle sharing <link> with _polygons[0]
1779       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[0] )];
1780       for ( int i = 0; i < 4; ++i )
1781         if ( quad->_links[i]._link == link )
1782         {
1783           // 1st node of a link opposite to <link> in <quad>
1784           nodes[iL+4] = quad->_links[(i+2)%4].FirstNode()->Node();
1785           ++nbN;
1786           break;
1787         }
1788     }
1789     if ( nbN == 8 )
1790       _volumeDefs.set( vector< const SMDS_MeshNode* >( nodes, nodes+8 ));
1791
1792     return nbN == 8;
1793   }
1794   //================================================================================
1795   /*!
1796    * \brief Tries to create a tetrahedron
1797    */
1798   bool Hexahedron::addTetra()
1799   {
1800     const SMDS_MeshNode* nodes[4];
1801     nodes[0] = _polygons[0]._links[0].FirstNode()->Node();
1802     nodes[1] = _polygons[0]._links[1].FirstNode()->Node();
1803     nodes[2] = _polygons[0]._links[2].FirstNode()->Node();
1804
1805     _Link* link = _polygons[0]._links[0]._link;
1806     ASSERT( link->_faces.size() > 1 );
1807
1808     // a triangle sharing <link> with _polygons[0]
1809     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[0] )];
1810     for ( int i = 0; i < 3; ++i )
1811       if ( tria->_links[i]._link == link )
1812       {
1813         nodes[3] = tria->_links[(i+1)%3].LastNode()->Node();
1814         _volumeDefs.set( vector< const SMDS_MeshNode* >( nodes, nodes+4 ));
1815         return true;
1816       }
1817
1818     return false;
1819   }
1820   //================================================================================
1821   /*!
1822    * \brief Tries to create a pentahedron
1823    */
1824   bool Hexahedron::addPenta()
1825   {
1826     // find a base triangular face
1827     int iTri = -1;
1828     for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
1829       if ( _polygons[ iF ]._links.size() == 3 )
1830         iTri = iF;
1831     if ( iTri < 0 ) return false;
1832
1833     // find nodes
1834     const SMDS_MeshNode* nodes[6];
1835     int nbN = 0;
1836     for ( int iL = 0; iL < 3; ++iL )
1837     {
1838       // a base node
1839       nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode()->Node();
1840       ++nbN;
1841
1842       // find a top node above the base node
1843       _Link* link = _polygons[ iTri ]._links[iL]._link;
1844       ASSERT( link->_faces.size() > 1 );
1845       // a quadrangle sharing <link> with a base triangle
1846       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
1847       if ( quad->_links.size() != 4 ) return false;
1848       for ( int i = 0; i < 4; ++i )
1849         if ( quad->_links[i]._link == link )
1850         {
1851           // 1st node of a link opposite to <link> in <quad>
1852           nodes[iL+3] = quad->_links[(i+2)%4].FirstNode()->Node();
1853           ++nbN;
1854           break;
1855         }
1856     }
1857     if ( nbN == 6 )
1858       _volumeDefs.set( vector< const SMDS_MeshNode* >( nodes, nodes+6 ));
1859
1860     return ( nbN == 6 );
1861   }
1862   //================================================================================
1863   /*!
1864    * \brief Tries to create a pyramid
1865    */
1866   bool Hexahedron::addPyra()
1867   {
1868     // find a base quadrangle
1869     int iQuad = -1;
1870     for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
1871       if ( _polygons[ iF ]._links.size() == 4 )
1872         iQuad = iF;
1873     if ( iQuad < 0 ) return false;
1874
1875     // find nodes
1876     const SMDS_MeshNode* nodes[5];
1877     nodes[0] = _polygons[iQuad]._links[0].FirstNode()->Node();
1878     nodes[1] = _polygons[iQuad]._links[1].FirstNode()->Node();
1879     nodes[2] = _polygons[iQuad]._links[2].FirstNode()->Node();
1880     nodes[3] = _polygons[iQuad]._links[3].FirstNode()->Node();
1881
1882     _Link* link = _polygons[iQuad]._links[0]._link;
1883     ASSERT( link->_faces.size() > 1 );
1884
1885     // a triangle sharing <link> with a base quadrangle
1886     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
1887     if ( tria->_links.size() != 3 ) return false;
1888     for ( int i = 0; i < 3; ++i )
1889       if ( tria->_links[i]._link == link )
1890       {
1891         nodes[4] = tria->_links[(i+1)%3].LastNode()->Node();
1892         _volumeDefs.set( vector< const SMDS_MeshNode* >( nodes, nodes+5 ));
1893         return true;
1894       }
1895
1896     return false;
1897   }
1898
1899 } // namespace
1900
1901 //=============================================================================
1902 /*!
1903  * \brief Generates 3D structured Cartesian mesh in the internal part of
1904  * solid shapes and polyhedral volumes near the shape boundary.
1905  *  \param theMesh - mesh to fill in
1906  *  \param theShape - a compound of all SOLIDs to mesh
1907  *  \retval bool - true in case of success
1908  */
1909 //=============================================================================
1910
1911 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh &         theMesh,
1912                                       const TopoDS_Shape & theShape)
1913 {
1914   // The algorithm generates the mesh in following steps:
1915
1916   // 1) Intersection of grid lines with the geometry boundary.
1917   // This step allows to find out if a given node of the initial grid is
1918   // inside or outside the geometry.
1919
1920   // 2) For each cell of the grid, check how many of it's nodes are outside
1921   // of the geometry boundary. Depending on a result of this check
1922   // - skip a cell, if all it's nodes are outside
1923   // - skip a cell, if it is too small according to the size threshold
1924   // - add a hexahedron in the mesh, if all nodes are inside
1925   // - add a polyhedron in the mesh, if some nodes are inside and some outside
1926
1927   _computeCanceled = false;
1928
1929   try
1930   {
1931     Grid grid;
1932
1933     TopTools_MapOfShape faceMap;
1934     for ( TopExp_Explorer fExp( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
1935       if ( !faceMap.Add( fExp.Current() ))
1936         faceMap.Remove( fExp.Current() ); // remove a face shared by two solids
1937
1938     Bnd_Box shapeBox;
1939     vector<FaceGridIntersector> facesItersectors( faceMap.Extent() );
1940     TopTools_MapIteratorOfMapOfShape faceMppIt( faceMap );
1941     for ( int i = 0; faceMppIt.More(); faceMppIt.Next(), ++i )
1942     {
1943       facesItersectors[i]._face = TopoDS::Face( faceMppIt.Key() );
1944       facesItersectors[i]._grid = &grid;
1945       shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
1946     }
1947
1948     vector<double> xCoords, yCoords, zCoords;
1949     _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
1950
1951     grid.SetCoordinates( xCoords, yCoords, zCoords, theShape );
1952
1953     // check if the grid encloses the shape
1954     if ( !_hyp->IsGridBySpacing(0) ||
1955          !_hyp->IsGridBySpacing(1) ||
1956          !_hyp->IsGridBySpacing(2) )
1957     {
1958       Bnd_Box gridBox;
1959       gridBox.Add( gp_Pnt( xCoords[0], yCoords[0], zCoords[0] ));
1960       gridBox.Add( gp_Pnt( xCoords.back(), yCoords.back(), zCoords.back() ));
1961       double x0,y0,z0, x1,y1,z1;
1962       shapeBox.Get(x0,y0,z0, x1,y1,z1);
1963       if ( gridBox.IsOut( gp_Pnt( x0,y0,z0 )) ||
1964            gridBox.IsOut( gp_Pnt( x1,y1,z1 )))
1965         for ( size_t i = 0; i < facesItersectors.size(); ++i )
1966         {
1967           if ( !facesItersectors[i].IsInGrid( gridBox ))
1968             return error("The grid doesn't enclose the geometry");
1969 #ifdef ELLIPSOLID_WORKAROUND
1970           delete facesItersectors[i]._surfaceInt, facesItersectors[i]._surfaceInt = 0;
1971 #endif
1972         }
1973     }
1974     if ( _computeCanceled ) return false;
1975
1976 #ifdef WITH_TBB
1977     { // copy partner faces and curves of not thread-safe types
1978       set< const Standard_Transient* > tshapes;
1979       BRepBuilderAPI_Copy copier;
1980       for ( size_t i = 0; i < facesItersectors.size(); ++i )
1981       {
1982         if ( !facesItersectors[i].IsThreadSafe(tshapes) )
1983         {
1984           copier.Perform( facesItersectors[i]._face );
1985           facesItersectors[i]._face = TopoDS::Face( copier );
1986         }
1987       }
1988     }
1989     // Intersection of grid lines with the geometry boundary.
1990     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
1991                         ParallelIntersector( facesItersectors ),
1992                         tbb::simple_partitioner());
1993 #else
1994     for ( size_t i = 0; i < facesItersectors.size(); ++i )
1995       facesItersectors[i].Intersect();
1996 #endif
1997
1998     // put interesection points onto the GridLine's; this is done after intersection
1999     // to avoid contention of facesItersectors for writing into the same GridLine
2000     // in case of parallel work of facesItersectors
2001     for ( size_t i = 0; i < facesItersectors.size(); ++i )
2002       facesItersectors[i].StoreIntersections();
2003
2004     SMESH_MesherHelper helper( theMesh );
2005     TopExp_Explorer solidExp (theShape, TopAbs_SOLID);
2006     helper.SetSubShape( solidExp.Current() );
2007     helper.SetElementsOnShape( true );
2008
2009     if ( _computeCanceled ) return false;
2010
2011     // create nodes on the geometry
2012     grid.ComputeNodes(helper);
2013
2014     if ( _computeCanceled ) return false;
2015
2016     // create volume elements
2017     Hexahedron hex( _hyp->GetSizeThreshold(), &grid );
2018     int nbAdded = hex.MakeElements( helper );
2019
2020     SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
2021     if ( nbAdded > 0 )
2022     {
2023       // make all SOLIDS computed
2024       if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
2025       {
2026         SMDS_ElemIteratorPtr volIt = sm1->GetElements();
2027         for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
2028         {
2029           const SMDS_MeshElement* vol = volIt->next();
2030           sm1->RemoveElement( vol, /*isElemDeleted=*/false );
2031           meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
2032         }
2033       }
2034       // make other sub-shapes computed
2035       setSubmeshesComputed( theMesh, theShape );
2036     }
2037
2038     // remove free nodes
2039     if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
2040     {
2041       // intersection nodes
2042       for ( int iDir = 0; iDir < 3; ++iDir )
2043       {
2044         vector< GridLine >& lines = grid._lines[ iDir ];
2045         for ( size_t i = 0; i < lines.size(); ++i )
2046         {
2047           multiset< IntersectionPoint >::iterator ip = lines[i]._intPoints.begin();
2048           for ( ; ip != lines[i]._intPoints.end(); ++ip )
2049             if ( ip->_node && ip->_node->NbInverseElements() == 0 )
2050               meshDS->RemoveFreeNode( ip->_node, smDS, /*fromGroups=*/false );
2051         }
2052       }
2053       // grid nodes
2054       for ( size_t i = 0; i < grid._nodes.size(); ++i )
2055         if ( !grid._isBndNode[i] ) // nodes on boundary are already removed
2056           if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 )
2057             meshDS->RemoveFreeNode( grid._nodes[i], smDS, /*fromGroups=*/false );
2058     }
2059
2060     return nbAdded;
2061
2062   }
2063   // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
2064   catch ( SMESH_ComputeError& e)
2065   {
2066     return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
2067   }
2068   return false;
2069 }
2070
2071 //=============================================================================
2072 /*!
2073  *  Evaluate
2074  */
2075 //=============================================================================
2076
2077 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh &         theMesh,
2078                                        const TopoDS_Shape & theShape,
2079                                        MapShapeNbElems&     theResMap)
2080 {
2081   // TODO
2082 //   std::vector<int> aResVec(SMDSEntity_Last);
2083 //   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
2084 //   if(IsQuadratic) {
2085 //     aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
2086 //     int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
2087 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
2088 //   }
2089 //   else {
2090 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
2091 //     aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
2092 //   }
2093 //   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
2094 //   aResMap.insert(std::make_pair(sm,aResVec));
2095
2096   return true;
2097 }
2098
2099 //=============================================================================
2100 namespace
2101 {
2102   /*!
2103    * \brief Event listener setting/unsetting _alwaysComputed flag to
2104    *        submeshes of inferior levels to prevent their computing
2105    */
2106   struct _EventListener : public SMESH_subMeshEventListener
2107   {
2108     string _algoName;
2109
2110     _EventListener(const string& algoName):
2111       SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
2112       _algoName(algoName)
2113     {}
2114     // --------------------------------------------------------------------------------
2115     // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
2116     //
2117     static void setAlwaysComputed( const bool     isComputed,
2118                                    SMESH_subMesh* subMeshOfSolid)
2119     {
2120       SMESH_subMeshIteratorPtr smIt =
2121         subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
2122       while ( smIt->more() )
2123       {
2124         SMESH_subMesh* sm = smIt->next();
2125         sm->SetIsAlwaysComputed( isComputed );
2126       }
2127     }
2128
2129     // --------------------------------------------------------------------------------
2130     // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
2131     //
2132     virtual void ProcessEvent(const int          event,
2133                               const int          eventType,
2134                               SMESH_subMesh*     subMeshOfSolid,
2135                               SMESH_subMeshEventListenerData* data,
2136                               const SMESH_Hypothesis*         hyp = 0)
2137     {
2138       if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
2139       {
2140         setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
2141                            subMeshOfSolid );
2142       }
2143       else
2144       {
2145         SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
2146         if ( !algo3D || _algoName != algo3D->GetName() )
2147           setAlwaysComputed( false, subMeshOfSolid );
2148       }
2149     }
2150
2151     // --------------------------------------------------------------------------------
2152     // set the event listener
2153     //
2154     static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
2155     {
2156       subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
2157                                         /*data=*/0,
2158                                         subMeshOfSolid );
2159     }
2160
2161   }; // struct _EventListener
2162
2163 } // namespace
2164
2165 //================================================================================
2166 /*!
2167  * \brief Sets event listener to submeshes if necessary
2168  *  \param subMesh - submesh where algo is set
2169  * This method is called when a submesh gets HYP_OK algo_state.
2170  * After being set, event listener is notified on each event of a submesh.
2171  */
2172 //================================================================================
2173
2174 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
2175 {
2176   _EventListener::SetOn( subMesh, GetName() );
2177 }
2178
2179 //================================================================================
2180 /*!
2181  * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
2182  */
2183 //================================================================================
2184
2185 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh&         theMesh,
2186                                                    const TopoDS_Shape& theShape)
2187 {
2188   for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
2189     _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));
2190 }
2191