Salome HOME
bos #20256: [CEA 18523] Porting SMESH to int 64 bits
[modules/smesh.git] / src / SMDS / SMDS_ElementFactory.hxx
1 // Copyright (C) 2007-2021  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, 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   : SMDS_ElementFactory.hxx
23 //  Module : SMESH
24 //
25 #ifndef _SMDS_ElementFactory_HeaderFile
26 #define _SMDS_ElementFactory_HeaderFile
27
28 #include "SMDS_MeshCell.hxx"
29 #include "SMDS_Position.hxx"
30
31 #include <Utils_SALOME_Exception.hxx>
32
33 #include <boost/container/flat_set.hpp>
34 #include <boost/dynamic_bitset.hpp>
35 #include <boost/make_shared.hpp>
36 #include <boost/ptr_container/ptr_vector.hpp>
37 #include <boost/shared_ptr.hpp>
38
39 #include <set>
40
41 #include <vtkType.h>
42
43 #include <smIdType.hxx>
44
45 class SMDS_ElementChunk;
46 class SMDS_Mesh;
47 class SMDS_MeshCell;
48 class SMDS_MeshNode;
49
50 struct _ChunkCompare {
51   bool operator () (const SMDS_ElementChunk* c1, const SMDS_ElementChunk* c2) const;
52 };
53 typedef boost::ptr_vector<SMDS_ElementChunk>       TChunkVector;
54 typedef std::set<SMDS_ElementChunk*,_ChunkCompare> TChunkPtrSet;
55
56 //------------------------------------------------------------------------------------
57 /*!
58  * \brief Allocate SMDS_MeshElement's (SMDS_MeshCell's or SMDS_MeshNode's )
59  *        and bind some attributes to elements:
60  *        element ID, element VTK ID, sub-mesh ID, position on shape.
61  *
62  * Elements are allocated by chunks, so there are used and non-used elements
63  */
64 class SMDS_ElementFactory
65 {
66 protected:
67   bool                     myIsNodal;          // what to allocate: nodes or cells
68   SMDS_Mesh*               myMesh;
69   TChunkVector             myChunks;           // array of chunks of elements
70   TChunkPtrSet             myChunksWithUnused; // sorted chunks having unused elements
71   std::vector< vtkIdType > myVtkIDs;           // myVtkIDs[ smdsID-1 ] == vtkID
72   std::vector< smIdType >  mySmdsIDs;          // mySmdsIDs[ vtkID ] == smdsID - 1
73   smIdType                 myNbUsedElements;   // counter of elements
74
75   friend class SMDS_ElementChunk;
76
77 public:
78
79   SMDS_ElementFactory( SMDS_Mesh* mesh, const bool isNodal=false );
80   virtual ~SMDS_ElementFactory();
81
82   //! Return minimal ID of a non-used element
83   smIdType GetFreeID();
84
85   //! Return maximal ID of an used element
86   smIdType GetMaxID();
87
88   //! Return minimal ID of an used element
89   smIdType GetMinID();
90
91   //! Return an element by ID. NULL if the element with the given ID is already used
92   SMDS_MeshElement* NewElement( const smIdType id );
93
94   //! Return a SMDS_MeshCell by ID. NULL if the cell with the given ID is already used
95   SMDS_MeshCell* NewCell( const smIdType id ) { return static_cast<SMDS_MeshCell*>( NewElement( id )); }
96
97   //! Return an used element by ID. NULL if the element with the given ID is not yet used
98   const SMDS_MeshElement* FindElement( const smIdType id ) const;
99
100   //! Return a number of used elements
101   smIdType NbUsedElements() const { return myNbUsedElements; }
102
103   //! Return an iterator on all element filtered using a given filter.
104   //  nbElemsToReturn is used to optimize by stopping the iteration as soon as
105   //  all elements satisfying filtering condition encountered.
106   template< class ElemIterator >
107   boost::shared_ptr< ElemIterator > GetIterator( SMDS_MeshElement::Filter* filter,
108                                                  size_t nbElemsToReturn = -1 );
109
110   //! Return an iterator on all element assigned to a given shape.
111   //  nbElemsToReturn is used to optimize by stopping the iteration as soon as
112   //  all elements assigned to the shape encountered.
113   //  sm1stElem is used to quickly find the first chunk holding elements of the shape;
114   //  it must have smallest ID between elements on the shape
115   template< class ElemIterator >
116   boost::shared_ptr< ElemIterator > GetShapeIterator( int                     shapeID,
117                                                       size_t                  nbElemsToReturn,
118                                                       const SMDS_MeshElement* sm1stElem );
119
120   //! Mark the element as non-used
121   void Free( const SMDS_MeshElement* );
122
123   //! Return an SMDS ID by a Vtk one
124   smIdType FromVtkToSmds( vtkIdType vtkID );
125
126   //! De-allocate all elements
127   virtual void Clear();
128
129   //! Remove unused elements located not at the end of the last chunk.
130   //  Minimize allocated memory
131   virtual void Compact(std::vector<smIdType>& idCellsOldToNew);
132
133   //! Return true if Compact() will change IDs of elements
134   virtual bool CompactChangePointers();
135
136   //! Return a number of elements in a chunk
137   static int ChunkSize();
138 };
139
140 //------------------------------------------------------------------------------------
141 /*!
142  * \brief Allocate SMDS_MeshNode's
143  */
144 class SMDS_NodeFactory : public SMDS_ElementFactory
145 {
146   std::vector<char> myShapeDim; // dimension of shapes
147
148 public:
149
150   SMDS_NodeFactory( SMDS_Mesh* mesh );
151   ~SMDS_NodeFactory();
152
153   //! Return a SMDS_MeshNode by ID. NULL if the node with the given ID is already used
154   SMDS_MeshNode* NewNode( smIdType id ) { return (SMDS_MeshNode*) NewElement(id); }
155
156   //! Return an used node by ID. NULL if the node with the given ID is not yet used
157   const SMDS_MeshNode* FindNode( smIdType id ) { return (const SMDS_MeshNode*) FindElement(id); }
158
159   //! Set a total number of sub-shapes in the main shape
160   void SetNbShapes( size_t nbShapes );
161
162   //! Return a dimension of a shape
163   int  GetShapeDim( int shapeID ) const;
164
165   //! Set a dimension of a shape
166   void SetShapeDim( int shapeID, int dim );
167
168   //! De-allocate all nodes
169   virtual void Clear();
170
171   //! Remove unused nodes located not at the end of the last chunk.
172   //  Minimize allocated memory
173   virtual void Compact(std::vector<smIdType>& idNodesOldToNew);
174
175   //! Return true if Compact() will change IDs of node
176   virtual bool CompactChangePointers();
177 };
178
179 //------------------------------------------------------------------------------------
180 /*!
181  * \brief Range of elements in a chunk having the same attribute value
182  */
183 template< typename ATTR>
184 struct _Range
185 {
186   typedef ATTR attr_t;
187
188   attr_t myValue; // common attribute value
189   int    my1st;   // index in the chunk of the 1st element 
190   _Range( int i0 = 0, attr_t v = 0 ): myValue( v ), my1st( i0 ) {}
191
192   bool operator < (const _Range& other) const { return my1st < other.my1st; }
193 };
194
195 typedef std::vector< std::pair< int, int > > TIndexRanges;
196
197 //------------------------------------------------------------------------------------
198 /*!
199  * \brief Sorted set of ranges
200  */
201 template< class RANGE >
202 struct _RangeSet
203 {
204   typedef typename RANGE::attr_t              attr_t;
205   typedef boost::container::flat_set< RANGE > set_t;
206   typedef typename set_t::const_iterator      set_iterator;
207
208   set_t mySet;
209
210   _RangeSet() { mySet.insert( RANGE( 0, 0 )); }
211
212   /*!
213    * \brief Return a number of ranges
214    */
215   size_t Size() const { return mySet.size(); }
216
217   /*!
218    * \brief Return a mutable _Range::my1st of a range pointed by an iterator
219    */
220   int&   First( set_iterator rangePtr ) { return const_cast< int& >( rangePtr->my1st ); }
221
222   /*!
223    * \brief Return a number of elements in a range pointed by an iterator
224    */
225   size_t Size( set_iterator rangePtr ) const
226   {
227     int next1st =
228       ( rangePtr + 1 == mySet.end() ) ? SMDS_ElementFactory::ChunkSize() : ( rangePtr + 1 )->my1st;
229     return next1st - rangePtr->my1st;
230   }
231
232   /*!
233    * \brief Return ranges of indices (from,to) of elements having a given value
234    */
235   bool GetIndices( const attr_t theValue, TIndexRanges & theIndices,
236                    const attr_t* /*theMinValue*/ = 0, const attr_t* /*theMaxValue*/ = 0) const
237   {
238     bool isFound = false;
239
240     // if ( sizeof( attr_t ) == sizeof( int ) && theMinValue )
241     //   if ( theValue < *theMinValue || theValue > *theMaxValue )
242     //     return isFound;
243
244     for ( set_iterator it = mySet.begin(); it < mySet.end(); ++it )
245     {
246       if ( it->myValue == theValue )
247       {
248         theIndices.push_back( std::make_pair( it->my1st, it->my1st + Size( it )));
249         isFound = true;
250         ++it; // the next range value differs from theValue
251       }
252     }
253     return isFound;
254   }
255
256   /*!
257    * \brief Return value of an element attribute
258    *  \param [in] theIndex - element index
259    *  \return attr_t - attribute value
260    */
261   attr_t GetValue( int theIndex ) const
262   {
263     set_iterator r = mySet.upper_bound( theIndex ) - 1;
264     return r->myValue;
265   }
266
267   /*!
268    * \brief Change value of an element attribute
269    *  \param [in] theIndex - element index
270    *  \param [in] theValue - attribute value
271    *  \return attr_t - previous value
272    */
273   attr_t SetValue( int theIndex, attr_t theValue )
274   {
275     set_iterator rNext = mySet.end(); // case of adding elements
276     set_iterator     r = rNext - 1;
277     if ( r->my1st > theIndex )
278     {
279       rNext = mySet.upper_bound( theIndex );
280       r     = rNext - 1;
281     }
282     int         rSize = Size( r ); // range size
283     attr_t      rValue = r->myValue;
284     if ( rValue == theValue )
285       return rValue; // it happens while compacting
286
287     if ( r->my1st == theIndex ) // theIndex is the first in the range
288     {
289       bool joinPrev = // can join theIndex to the previous range
290         ( r->my1st > 0 && ( r-1 )->myValue == theValue );
291
292       if ( rSize == 1 )
293       {
294         bool joinNext = // can join to the next range
295           ( rNext != mySet.end() && rNext->myValue == theValue );
296
297         if ( joinPrev )
298         {
299           if ( joinNext ) // && joinPrev
300           {
301             mySet.erase( r, r + 2 );
302           }
303           else // joinPrev && !joinNext
304           {
305             mySet.erase( r );
306           }
307         }
308         else
309         {
310           if ( joinNext ) // && !joinPrev
311           {
312             r = mySet.erase( r ); // then r points to the next range
313             First( r )--;
314           }
315           else // !joinPrev && !joinNext
316           {
317             const_cast< attr_t & >( r->myValue ) = theValue;
318           }
319         }
320       }
321       else // if rSize > 1
322       {
323         if ( joinPrev )
324         {
325           First( r )++;
326         }
327         else
328         {
329           r = mySet.insert( r, RANGE( theIndex + 1, rValue )) - 1;
330           const_cast< attr_t & >( r->myValue ) = theValue;
331         }
332       }
333     }
334     else if ( r->my1st + rSize - 1 == theIndex ) // theIndex is last in the range
335     {
336       if ( rNext != mySet.end() && rNext->myValue == theValue ) // join to the next
337       {
338         First( rNext )--;
339       }
340       else
341       {
342         mySet.insert( r, RANGE( theIndex, theValue ));
343       }
344     }
345     else // theIndex in the middle of the range
346     {
347       r = mySet.insert( r, RANGE( theIndex,     theValue ));
348       r = mySet.insert( r, RANGE( theIndex + 1, rValue ));
349     }
350     return rValue;
351   }
352 }; // struct _RangeSet
353
354
355 typedef _Range< int >  _ShapeIDRange; // sub-mesh ID range
356 typedef _Range< bool > _UsedRange;    // range of used elements
357
358 typedef _RangeSet< _ShapeIDRange > TSubIDRangeSet;
359 typedef _RangeSet< _UsedRange >    TUsedRangeSet;
360 typedef boost::dynamic_bitset<>    TBitSet;
361 //typedef float                       TParam;
362 typedef double                     TParam;
363 //typedef std::unordered_set<int>    TSubIDSet;
364
365 //------------------------------------------------------------------------------------
366 /*!
367  * \brief Allocate SMDS_MeshElement's (SMDS_MeshCell's or SMDS_MeshNode's )
368  *        and bind some attributes to elements:
369  *        element ID, sub-shape ID, isMarked flag, parameters on shape
370  */
371 class SMDS_ElementChunk
372 {
373   SMDS_ElementFactory* myFactory;     // holder of this chunk
374   SMDS_MeshElement*    myElements;    // array of elements
375   smIdType             my1stID;       // ID of myElements[0]
376   TBitSet              myMarkedSet;   // mark some elements
377   TUsedRangeSet        myUsedRanges;  // ranges of used/unused elements
378   TSubIDRangeSet       mySubIDRanges; // ranges of elements on the same sub-shape
379   //TSubIDSet*           mySubIDSet;    // set of sub-shape IDs
380   // int                  myMinSubID;    // min sub-shape ID
381   // int                  myMaxSubID;    // max sub-shape ID
382   std::vector<TParam>  myPositions;   // UV parameters on shape: 2*param_t per an element
383
384 public:
385
386   SMDS_ElementChunk( SMDS_ElementFactory* factory = 0, smIdType id0 = 0 );
387   ~SMDS_ElementChunk();
388
389   //! Return an element by an index [0,ChunkSize()]
390   SMDS_MeshElement* Element(int index) { return & myElements[index]; }
391
392   //! Return an element by an index [0,ChunkSize()]
393   const SMDS_MeshElement* Element(int index) const { return & myElements[index]; }
394
395   //! Return ID of the first non-used element
396   smIdType  GetUnusedID() const;
397
398   //! Mark an element as used
399   void UseElement( const int index );
400
401   //! Mark an element as non-used
402   void Free( const SMDS_MeshElement* e );
403
404   //! Check if a given range holds used or non-used elements
405   static bool IsUsed( const _UsedRange& r ) { return r.myValue; }
406
407   //! Return index of an element in the chunk
408   int Index( const SMDS_MeshElement* e ) const { return (int)( e - myElements ); }
409
410   //! Return ID of the 1st element in the chunk
411   smIdType Get1stID() const { return my1stID; }
412
413   //! Return pointer to on-shape-parameters of a node
414   TParam* GetPositionPtr( const SMDS_MeshElement* node, bool allocate=false );
415
416   //! Return ranges of used/non-used elements
417   const TUsedRangeSet&  GetUsedRanges() const { return myUsedRanges; }
418   const TUsedRangeSet&  GetUsedRangesMinMax( bool& min, bool& max ) const
419   { min = false; max = true; return myUsedRanges; }
420
421   //! Return ranges of elements assigned to sub-shapes and min/max of sub-shape IDs
422   const TSubIDRangeSet& GetSubIDRangesMinMax( int& /*min*/, int& /*max*/ ) const
423   { /*min = myMinSubID; max = myMaxSubID;*/ return mySubIDRanges; }
424
425   //! Minimize allocated memory
426   void Compact();
427
428   //! Print some data
429   void Dump() const; // debug
430
431
432   // Methods called by SMDS_MeshElement
433
434   smIdType  GetID( const SMDS_MeshElement* e ) const;
435
436   vtkIdType  GetVtkID( const SMDS_MeshElement* e ) const;
437   void SetVTKID( const SMDS_MeshElement* e, const vtkIdType id );
438
439   int  GetShapeID( const SMDS_MeshElement* e ) const;
440   void SetShapeID( const SMDS_MeshElement* e, int shapeID ) const;
441
442   bool IsMarked   ( const SMDS_MeshElement* e ) const;
443   void SetIsMarked( const SMDS_MeshElement* e, bool is );
444
445   SMDS_PositionPtr GetPosition( const SMDS_MeshNode* n ) const;
446   void SetPosition( const SMDS_MeshNode* n, const SMDS_PositionPtr& pos, int shapeID );
447
448   SMDS_Mesh* GetMesh() { return myFactory->myMesh; }
449 };
450
451 //------------------------------------------------------------------------------------
452 /*!
453  * \brief Iterator on elements in chunks
454  */
455 template< class ELEM_ITERATOR, class RANGE_SET >
456 struct _ChunkIterator : public ELEM_ITERATOR
457 {
458   typedef typename ELEM_ITERATOR::value_type    element_type;
459   typedef SMDS_MeshElement::Filter*             filter_ptr;
460   typedef typename RANGE_SET::attr_t            attr_type;
461   typedef const RANGE_SET& (SMDS_ElementChunk::*get_rangeset_fun)(attr_type&, attr_type&) const;
462
463   const SMDS_MeshElement* myElement;
464   TIndexRanges            myRanges;
465   int                     myRangeIndex;
466   const TChunkVector&     myChunks;
467   int                     myChunkIndex;
468   get_rangeset_fun        myGetRangeSetFun;
469   attr_type               myValue;
470   attr_type               myMinValue;
471   attr_type               myMaxValue;
472   filter_ptr              myFilter;
473   size_t                  myNbElemsToReturn;
474   size_t                  myNbReturned;
475
476   _ChunkIterator( const TChunkVector &      theChunks,
477                   get_rangeset_fun          theGetRangeSetFun,
478                   attr_type                 theAttrValue,
479                   SMDS_MeshElement::Filter* theFilter,
480                   size_t                    theNbElemsToReturn = -1,
481                   int                       theChunkIndex = 0):
482     myElement( 0 ),
483     myRangeIndex( 0 ),
484     myChunks( theChunks ),
485     myChunkIndex( theChunkIndex-1 ),
486     myGetRangeSetFun( theGetRangeSetFun ),
487     myValue( theAttrValue ),
488     myFilter( theFilter ),
489     myNbElemsToReturn( theNbElemsToReturn ),
490     myNbReturned( 0 )
491   {
492     next();
493   }
494   ~_ChunkIterator()
495   {
496     delete myFilter;
497   }
498
499   virtual bool more()
500   {
501     return myElement;
502   }
503
504   virtual element_type next()
505   {
506     element_type result = (element_type) myElement;
507     myNbReturned += bool( result );
508
509     myElement = 0;
510     if ( myNbReturned < myNbElemsToReturn )
511       while ( ! nextInRange() )
512       {
513         if ( ++myRangeIndex >= (int)myRanges.size() )
514         {
515           myRanges.clear();
516           myRangeIndex = 0;
517           while ( ++myChunkIndex < (int)myChunks.size() &&
518                   !getRangeSet().GetIndices( myValue, myRanges, &myMinValue, &myMaxValue ))
519             ;
520           if ( myChunkIndex >= (int)myChunks.size() )
521             break;
522         }
523       }
524     return result;
525   }
526
527   bool nextInRange()
528   {
529     if ( myRangeIndex < (int)myRanges.size() )
530     {
531       std::pair< int, int > & range = myRanges[ myRangeIndex ];
532       while ( range.first < range.second && !myElement )
533       {
534         myElement = myChunks[ myChunkIndex ].Element( range.first++ );
535         if ( !(*myFilter)( myElement ))
536           myElement = 0;
537       }
538     }
539     return myElement;
540   }
541
542   const RANGE_SET& getRangeSet()
543   {
544     return ( myChunks[  myChunkIndex ].*myGetRangeSetFun )( myMinValue, myMaxValue );
545   }
546 }; // struct _ChunkIterator
547
548
549 template< class ElemIterator >
550 boost::shared_ptr< ElemIterator >
551 SMDS_ElementFactory::GetIterator( SMDS_MeshElement::Filter* filter,
552                                   size_t                    nbElemsToReturn )
553 {
554   typedef _ChunkIterator< ElemIterator, TUsedRangeSet > TChuckIterator;
555   return boost::make_shared< TChuckIterator >( myChunks,
556                                                & SMDS_ElementChunk::GetUsedRangesMinMax,
557                                                /*isUsed=*/true,
558                                                filter,
559                                                nbElemsToReturn );
560 }
561
562 template< class ElemIterator >
563 boost::shared_ptr< ElemIterator >
564 SMDS_ElementFactory::GetShapeIterator( int                     shapeID,
565                                        size_t                  nbElemsToReturn,
566                                        const SMDS_MeshElement* sm1stElem )
567 {
568   smIdType iChunk = sm1stElem ? (( sm1stElem->GetID() - 1 ) / ChunkSize()) : 0;
569   typedef _ChunkIterator< ElemIterator, TSubIDRangeSet > TChuckIterator;
570   return boost::make_shared< TChuckIterator >( myChunks,
571                                                & SMDS_ElementChunk::GetSubIDRangesMinMax,
572                                                /*shapeID=*/shapeID,
573                                                new SMDS_MeshElement::NonNullFilter(),
574                                                nbElemsToReturn,
575                                                iChunk );
576 }
577
578 #endif