Salome HOME
a03ed6a82c19a97058955131261d1797f3db6daa
[modules/smesh.git] / src / StdMeshers / StdMeshers_QuadToTriaAdaptor.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_QuadToTriaAdaptor.cxx
21 // Module    : SMESH
22 // Created   : Wen May 07 16:37:07 2008
23 // Author    : Sergey KUUL (skl)
24
25 #include "StdMeshers_QuadToTriaAdaptor.hxx"
26
27 #include "SMDS_IteratorOnIterators.hxx"
28 #include "SMDS_SetIterator.hxx"
29 #include "SMESHDS_GroupBase.hxx"
30 #include "SMESHDS_Mesh.hxx"
31 #include "SMESH_Algo.hxx"
32 #include "SMESH_Group.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_MeshAlgos.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_subMesh.hxx"
37
38 #include <IntAna_IntConicQuad.hxx>
39 #include <IntAna_Quadric.hxx>
40 #include <TColgp_Array1OfPnt.hxx>
41 #include <TColgp_Array1OfVec.hxx>
42 #include <TColgp_SequenceOfPnt.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopoDS.hxx>
45 #include <TopoDS_Iterator.hxx>
46 #include <gp_Lin.hxx>
47 #include <gp_Pln.hxx>
48
49 #include "utilities.h"
50
51 #include <string>
52 #include <numeric>
53 #include <limits>
54
55 using namespace std;
56
57 enum EQuadNature { NOT_QUAD, QUAD, DEGEN_QUAD, PYRAM_APEX = 4, TRIA_APEX = 0 };
58
59 // std-like iterator used to get coordinates of nodes of mesh element
60 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
61
62 namespace
63 {
64   //================================================================================
65   /*!
66    * \brief Return true if two nodes of triangles are equal
67    */
68   //================================================================================
69
70   bool EqualTriangles(const SMDS_MeshElement* F1,const SMDS_MeshElement* F2)
71   {
72     return
73       ( F1->GetNode(1)==F2->GetNode(2) && F1->GetNode(2)==F2->GetNode(1) ) ||
74       ( F1->GetNode(1)==F2->GetNode(1) && F1->GetNode(2)==F2->GetNode(2) );
75   }
76   //================================================================================
77   /*!
78    * \brief Return true if two adjacent pyramids are too close one to another
79    * so that a tetrahedron to built between them would have too poor quality
80    */
81   //================================================================================
82
83   bool TooCloseAdjacent( const SMDS_MeshElement* PrmI,
84                          const SMDS_MeshElement* PrmJ,
85                          const bool              hasShape)
86   {
87     const SMDS_MeshNode* nApexI = PrmI->GetNode(4);
88     const SMDS_MeshNode* nApexJ = PrmJ->GetNode(4);
89     if ( nApexI == nApexJ ||
90          nApexI->getshapeId() != nApexJ->getshapeId() )
91       return false;
92
93     // Find two common base nodes and their indices within PrmI and PrmJ
94     const SMDS_MeshNode* baseNodes[2] = { 0,0 };
95     int baseNodesIndI[2], baseNodesIndJ[2];
96     for ( int i = 0; i < 4 ; ++i )
97     {
98       int j = PrmJ->GetNodeIndex( PrmI->GetNode(i));
99       if ( j >= 0 )
100       {
101         int ind = baseNodes[0] ? 1:0;
102         if ( baseNodes[ ind ])
103           return false; // pyramids with a common base face
104         baseNodes    [ ind ] = PrmI->GetNode(i);
105         baseNodesIndI[ ind ] = i;
106         baseNodesIndJ[ ind ] = j;
107       }
108     }
109     if ( !baseNodes[1] ) return false; // not adjacent
110
111     // Get normals of triangles sharing baseNodes
112     gp_XYZ apexI = SMESH_TNodeXYZ( nApexI );
113     gp_XYZ apexJ = SMESH_TNodeXYZ( nApexJ );
114     gp_XYZ base1 = SMESH_TNodeXYZ( baseNodes[0]);
115     gp_XYZ base2 = SMESH_TNodeXYZ( baseNodes[1]);
116     gp_Vec baseVec( base1, base2 );
117     gp_Vec baI( base1, apexI );
118     gp_Vec baJ( base1, apexJ );
119     gp_Vec nI = baseVec.Crossed( baI );
120     gp_Vec nJ = baseVec.Crossed( baJ );
121
122     // Check angle between normals
123     double  angle = nI.Angle( nJ );
124     bool tooClose = ( angle < 15. * M_PI / 180. );
125
126     // Check if pyramids collide
127     if ( !tooClose && ( baI * baJ > 0 ) && ( nI * nJ > 0 ))
128     {
129       // find out if nI points outside of PrmI or inside
130       int    dInd = baseNodesIndI[1] - baseNodesIndI[0];
131       bool isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
132
133       // find out sign of projection of baI to nJ
134       double proj = baI * nJ;
135
136       tooClose = ( isOutI ? proj > 0 : proj < 0 );
137     }
138
139     // Check if PrmI and PrmJ are in same domain
140     if ( tooClose && !hasShape )
141     {
142       // check order of baseNodes within pyramids, it must be opposite
143       int dInd;
144       dInd = baseNodesIndI[1] - baseNodesIndI[0];
145       bool isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
146       dInd = baseNodesIndJ[1] - baseNodesIndJ[0];
147       bool isOutJ = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
148       if ( isOutJ == isOutI )
149         return false; // other domain
150
151       // direct both normals outside pyramid
152       ( isOutI ? nJ : nI ).Reverse();
153
154       // check absence of a face separating domains between pyramids
155       TIDSortedElemSet emptySet, avoidSet;
156       int i1, i2;
157       while ( const SMDS_MeshElement* f =
158               SMESH_MeshAlgos::FindFaceInSet( baseNodes[0], baseNodes[1],
159                                               emptySet, avoidSet, &i1, &i2 ))
160       {
161         avoidSet.insert( f );
162
163         // face node other than baseNodes
164         int otherNodeInd = 0;
165         while ( otherNodeInd == i1 || otherNodeInd == i2 ) otherNodeInd++;
166         const SMDS_MeshNode* otherFaceNode = f->GetNode( otherNodeInd );
167
168         if ( otherFaceNode == nApexI || otherFaceNode == nApexJ )
169           continue; // f is a temporary triangle
170
171         // check if f is a base face of either of pyramids
172         if ( f->NbCornerNodes() == 4 &&
173              ( PrmI->GetNodeIndex( otherFaceNode ) >= 0 ||
174                PrmJ->GetNodeIndex( otherFaceNode ) >= 0 ))
175           continue; // f is a base quadrangle
176
177         // check projections of face direction (baOFN) to triange normals (nI and nJ)
178         gp_Vec baOFN( base2, SMESH_TNodeXYZ( otherFaceNode ));
179         if ( nI * baOFN > 0 && nJ * baOFN > 0 &&
180              baI* baOFN > 0 && baJ* baOFN > 0 ) // issue 0023212
181         {
182           tooClose = false; // f is between pyramids
183           break;
184         }
185       }
186     }
187
188     return tooClose;
189   }
190
191   //================================================================================
192   /*!
193    * \brief Move medium nodes of merged quadratic pyramids
194    */
195   //================================================================================
196
197   void UpdateQuadraticPyramids(const set<const SMDS_MeshNode*>& commonApex,
198                                SMESHDS_Mesh*                    meshDS)
199   {
200     typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
201     TStdElemIterator itEnd;
202
203     // shift of node index to get medium nodes between the 4 base nodes and the apex
204     const int base2MediumShift = 9;
205
206     set<const SMDS_MeshNode*>::const_iterator nIt = commonApex.begin();
207     for ( ; nIt != commonApex.end(); ++nIt )
208     {
209       SMESH_TNodeXYZ apex( *nIt );
210
211       vector< const SMDS_MeshElement* > pyrams // pyramids sharing the apex node
212         ( TStdElemIterator( apex._node->GetInverseElementIterator( SMDSAbs_Volume )), itEnd );
213
214       // Select medium nodes to keep and medium nodes to remove
215
216       typedef map < const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
217       TN2NMap base2medium; // to keep
218       vector< const SMDS_MeshNode* > nodesToRemove;
219
220       for ( unsigned i = 0; i < pyrams.size(); ++i )
221         for ( int baseIndex = 0; baseIndex < PYRAM_APEX; ++baseIndex )
222         {
223           SMESH_TNodeXYZ         base = pyrams[i]->GetNode( baseIndex );
224           const SMDS_MeshNode* medium = pyrams[i]->GetNode( baseIndex + base2MediumShift );
225           TN2NMap::iterator b2m = base2medium.insert( make_pair( base._node, medium )).first;
226           if ( b2m->second != medium )
227           {
228             nodesToRemove.push_back( medium );
229           }
230           else
231           {
232             // move the kept medium node
233             gp_XYZ newXYZ = 0.5 * ( apex + base );
234             meshDS->MoveNode( medium, newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
235           }
236         }
237
238       // Within pyramids, replace nodes to remove by nodes to keep
239
240       for ( unsigned i = 0; i < pyrams.size(); ++i )
241       {
242         vector< const SMDS_MeshNode* > nodes( pyrams[i]->begin_nodes(),
243                                               pyrams[i]->end_nodes() );
244         for ( int baseIndex = 0; baseIndex < PYRAM_APEX; ++baseIndex )
245         {
246           const SMDS_MeshNode* base = pyrams[i]->GetNode( baseIndex );
247           nodes[ baseIndex + base2MediumShift ] = base2medium[ base ];
248         }
249         meshDS->ChangeElementNodes( pyrams[i], &nodes[0], nodes.size());
250       }
251
252       // Remove the replaced nodes
253
254       if ( !nodesToRemove.empty() )
255       {
256         SMESHDS_SubMesh * sm = meshDS->MeshElements( nodesToRemove[0]->getshapeId() );
257         for ( unsigned i = 0; i < nodesToRemove.size(); ++i )
258           meshDS->RemoveFreeNode( nodesToRemove[i], sm, /*fromGroups=*/false);
259       }
260     }
261   }
262
263   //================================================================================
264   /*!
265    * \brief Store an error about overlapping faces
266    */
267   //================================================================================
268
269   bool overlapError( SMESH_Mesh&             mesh,
270                      const SMDS_MeshElement* face1,
271                      const SMDS_MeshElement* face2,
272                      const TopoDS_Shape&     shape = TopoDS_Shape())
273   {
274     if ( !face1 || !face2 ) return false;
275
276     SMESH_Comment msg;
277     msg << "face " << face1->GetID() << " overlaps face " << face2->GetID();
278
279     SMESH_subMesh * sm = 0;
280     if ( shape.IsNull() )
281     {
282       sm = mesh.GetSubMesh( mesh.GetShapeToMesh() );
283     }
284     else if ( shape.ShapeType() >= TopAbs_SOLID )
285     {
286       sm = mesh.GetSubMesh( shape );
287     }
288     else
289     {
290       TopoDS_Iterator it ( shape );
291       if ( it.More() )
292         sm = mesh.GetSubMesh( it.Value() );
293     }
294     if ( sm )
295     {
296       SMESH_ComputeErrorPtr& err = sm->GetComputeError();
297       if ( !err || err->IsOK() )
298       {
299         err = SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH, msg, sm->GetAlgo() );
300         err->myBadElements.push_back( face1 );
301         err->myBadElements.push_back( face2 );
302       }
303     }
304     //throw SALOME_Exception( msg.c_str() );
305
306     return false; // == "algo fails"
307   }
308 }
309
310 //================================================================================
311 /*!
312  * \brief Merge the two pyramids (i.e. fuse their apex) and others already merged with them
313  */
314 //================================================================================
315
316 void StdMeshers_QuadToTriaAdaptor::MergePiramids( const SMDS_MeshElement*     PrmI,
317                                                   const SMDS_MeshElement*     PrmJ,
318                                                   set<const SMDS_MeshNode*> & nodesToMove)
319 {
320   // cout << endl << "Merge " << PrmI->GetID() << " " << PrmJ->GetID() << " "
321   //      << PrmI->GetNode(4) << PrmJ->GetNode(4) << endl;
322   const SMDS_MeshNode* Nrem = PrmJ->GetNode(4); // node to remove
323   //int nbJ = Nrem->NbInverseElements( SMDSAbs_Volume );
324   SMESH_TNodeXYZ Pj( Nrem );
325
326   // an apex node to make common to all merged pyramids
327   SMDS_MeshNode* CommonNode = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
328   if ( CommonNode == Nrem ) return; // already merged
329   //int nbI = CommonNode->NbInverseElements( SMDSAbs_Volume );
330   SMESH_TNodeXYZ Pi( CommonNode );
331   gp_XYZ Pnew = /*( nbI*Pi + nbJ*Pj ) / (nbI+nbJ);*/ 0.5 * ( Pi + Pj );
332   CommonNode->setXYZ( Pnew.X(), Pnew.Y(), Pnew.Z() );
333
334   nodesToMove.insert( CommonNode );
335   nodesToMove.erase ( Nrem );
336
337   typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
338   TStdElemIterator itEnd;
339
340   // find and remove coincided faces of merged pyramids
341   vector< const SMDS_MeshElement* > inverseElems
342     // copy inverse elements to avoid iteration on changing container
343     ( TStdElemIterator( CommonNode->GetInverseElementIterator(SMDSAbs_Face)), itEnd);
344   for ( size_t i = 0; i < inverseElems.size(); ++i )
345   {
346     const SMDS_MeshElement* FI = inverseElems[i];
347     const SMDS_MeshElement* FJEqual = 0;
348     SMDS_ElemIteratorPtr triItJ = Nrem->GetInverseElementIterator(SMDSAbs_Face);
349     while ( !FJEqual && triItJ->more() )
350     {
351       const SMDS_MeshElement* FJ = triItJ->next();
352       if ( EqualTriangles( FJ, FI ))
353         FJEqual = FJ;
354     }
355     if ( FJEqual )
356     {
357       removeTmpElement( FI );
358       removeTmpElement( FJEqual );
359       myRemovedTrias.insert( FI );
360       myRemovedTrias.insert( FJEqual );
361     }
362   }
363
364   // set the common apex node to pyramids and triangles merged with J
365   vector< const SMDS_MeshNode* > nodes;
366   inverseElems.assign( TStdElemIterator( Nrem->GetInverseElementIterator()), itEnd );
367   for ( size_t i = 0; i < inverseElems.size(); ++i )
368   {
369     const SMDS_MeshElement* elem = inverseElems[i];
370     nodes.assign( elem->begin_nodes(), elem->end_nodes() );
371     nodes[ elem->GetType() == SMDSAbs_Volume ? PYRAM_APEX : TRIA_APEX ] = CommonNode;
372     GetMeshDS()->ChangeElementNodes( elem, &nodes[0], nodes.size());
373   }
374   ASSERT( Nrem->NbInverseElements() == 0 );
375   GetMeshDS()->RemoveFreeNode( Nrem,
376                                GetMeshDS()->MeshElements( Nrem->getshapeId()),
377                                /*fromGroups=*/false);
378 }
379
380 //================================================================================
381 /*!
382  * \brief Merges adjacent pyramids
383  */
384 //================================================================================
385
386 void StdMeshers_QuadToTriaAdaptor::MergeAdjacent(const SMDS_MeshElement*    PrmI,
387                                                  set<const SMDS_MeshNode*>& nodesToMove,
388                                                  const bool                 isRecursion)
389 {
390   TIDSortedElemSet adjacentPyrams;
391   bool mergedPyrams = false;
392   for ( int k=0; k<4; k++ ) // loop on 4 base nodes of PrmI
393   {
394     const SMDS_MeshNode*   n = PrmI->GetNode(k);
395     SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
396     while ( vIt->more() )
397     {
398       const SMDS_MeshElement* PrmJ = vIt->next();
399       if ( PrmJ == PrmI || PrmJ->NbCornerNodes() != 5 || !adjacentPyrams.insert( PrmJ ).second  )
400         continue;
401       if ( TooCloseAdjacent( PrmI, PrmJ, GetMesh()->HasShapeToMesh() ))
402       {
403         MergePiramids( PrmI, PrmJ, nodesToMove );
404         mergedPyrams = true;
405         // container of inverse elements can change
406         // vIt = n->GetInverseElementIterator( SMDSAbs_Volume ); -- iterator re-implemented
407       }
408     }
409   }
410   if ( mergedPyrams && !isRecursion )
411   {
412     TIDSortedElemSet::iterator prm;
413     for (prm = adjacentPyrams.begin(); prm != adjacentPyrams.end(); ++prm)
414       MergeAdjacent( *prm, nodesToMove, true );
415   }
416 }
417
418 //================================================================================
419 /*!
420  * \brief Constructor
421  */
422 //================================================================================
423
424 StdMeshers_QuadToTriaAdaptor::StdMeshers_QuadToTriaAdaptor():
425   myElemSearcher(0)
426 {
427 }
428
429 //================================================================================
430 /*!
431  * \brief Destructor
432  */
433 //================================================================================
434
435 StdMeshers_QuadToTriaAdaptor::~StdMeshers_QuadToTriaAdaptor()
436 {
437   // temporary faces are deleted by ~SMESH_ProxyMesh()
438   if ( myElemSearcher ) delete myElemSearcher;
439   myElemSearcher=0;
440 }
441
442 //=======================================================================
443 //function : FindBestPoint
444 //purpose  : Return a point P laying on the line (PC,V) so that triangle
445 //           (P, P1, P2) to be equilateral as much as possible
446 //           V - normal to (P1,P2,PC)
447 //=======================================================================
448
449 static gp_Pnt FindBestPoint(const gp_Pnt& P1, const gp_Pnt& P2,
450                             const gp_Pnt& PC, const gp_Vec& V)
451 {
452   gp_Pnt Pbest = PC;
453   const double a2 = P1.SquareDistance(P2);
454   const double b2 = P1.SquareDistance(PC);
455   const double c2 = P2.SquareDistance(PC);
456   if ( a2 < ( b2 + Sqrt( 4 * b2 * c2 ) + c2 ) / 4 ) // ( a < (b+c)/2 )
457     return Pbest;
458   else {
459     // find shift along V in order a to became equal to (b+c)/2
460     const double Vsize = V.Magnitude();
461     if ( fabs( Vsize ) > std::numeric_limits<double>::min() )
462     {
463       const double shift = sqrt( a2 + (b2-c2)*(b2-c2)/16/a2 - (b2+c2)/2 );
464       Pbest.ChangeCoord() += shift * V.XYZ() / Vsize;
465     }
466   }
467   return Pbest;
468 }
469
470 //=======================================================================
471 //function : HasIntersection3
472 //purpose  : Find intersection point between a triangle (P1,P2,P3)
473 //           and a segment [PC,P]
474 //=======================================================================
475
476 static bool HasIntersection3(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
477                              const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3)
478 {
479   const double EPSILON = 1e-6;
480   double segLen = P.Distance( PC );
481
482   gp_XYZ  orig = PC.XYZ();
483   gp_XYZ   dir = ( P.XYZ() - PC.XYZ() ) / segLen;
484   gp_XYZ vert0 = P1.XYZ();
485   gp_XYZ vert1 = P2.XYZ();
486   gp_XYZ vert2 = P3.XYZ();
487
488   /* calculate distance from vert0 to ray origin */
489   gp_XYZ  tvec = orig - vert0;
490
491   gp_XYZ edge1 = vert1 - vert0;
492   gp_XYZ edge2 = vert2 - vert0;
493
494   /* begin calculating determinant - also used to calculate U parameter */
495   gp_XYZ pvec = dir ^ edge2;
496
497   /* if determinant is near zero, ray lies in plane of triangle */
498   double det = edge1 * pvec;
499
500   if (det > -EPSILON && det < EPSILON)
501     return false;
502
503   /* calculate U parameter and test bounds */
504   double u = ( tvec * pvec ) / det;
505   //if (u < 0.0 || u > 1.0)
506   if (u < -EPSILON || u > 1.0 + EPSILON)
507     return false;
508
509   /* prepare to test V parameter */
510   gp_XYZ qvec = tvec ^ edge1;
511
512   /* calculate V parameter and test bounds */
513   double v = (dir * qvec) / det;
514   //if ( v < 0.0 || u + v > 1.0 )
515   if ( v < -EPSILON || u + v > 1.0 + EPSILON)
516     return false;
517
518   /* calculate t, ray intersects triangle */
519   double t = (edge2 * qvec) / det;
520
521   Pint = orig + dir * t;
522
523   return ( t > 0.  &&  t < segLen );
524 }
525
526 //=======================================================================
527 //function : HasIntersection
528 //purpose  : Auxilare for CheckIntersection()
529 //=======================================================================
530
531 static bool HasIntersection(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
532                             TColgp_SequenceOfPnt& aContour)
533 {
534   if ( aContour.Length() == 3 ) {
535     return HasIntersection3( P, PC, Pint, aContour(1), aContour(2), aContour(3) );
536   }
537   else {
538     bool check = false;
539     if( (aContour(1).SquareDistance(aContour(2)) > 1.e-12) &&
540         (aContour(1).SquareDistance(aContour(3)) > 1.e-12) &&
541         (aContour(2).SquareDistance(aContour(3)) > 1.e-12) ) {
542       check = HasIntersection3( P, PC, Pint, aContour(1), aContour(2), aContour(3) );
543     }
544     if(check) return true;
545     if( (aContour(1).SquareDistance(aContour(4)) > 1.e-12) &&
546         (aContour(1).SquareDistance(aContour(3)) > 1.e-12) &&
547         (aContour(4).SquareDistance(aContour(3)) > 1.e-12) ) {
548       check = HasIntersection3( P, PC, Pint, aContour(1), aContour(3), aContour(4) );
549     }
550     if(check) return true;
551   }
552
553   return false;
554 }
555
556 //================================================================================
557 /*!
558  * \brief Return allowed height of a pyramid
559  *  \param Papex - optimal pyramid apex
560  *  \param PC - gravity center of a quadrangle
561  *  \param PN - four nodes of the quadrangle
562  *  \param aMesh - mesh
563  *  \param NotCheckedFace - the quadrangle face
564  *  \param Shape - the shape being meshed
565  *  \retval false if mesh invalidity detected
566  */
567 //================================================================================
568
569 bool StdMeshers_QuadToTriaAdaptor::LimitHeight (gp_Pnt&                             Papex,
570                                                 const gp_Pnt&                       PC,
571                                                 const TColgp_Array1OfPnt&           PN,
572                                                 const vector<const SMDS_MeshNode*>& FNodes,
573                                                 SMESH_Mesh&                         aMesh,
574                                                 const SMDS_MeshElement*             NotCheckedFace,
575                                                 const bool                          UseApexRay,
576                                                 const TopoDS_Shape&                 Shape)
577 {
578   if ( !myElemSearcher )
579     myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *aMesh.GetMeshDS() );
580   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
581
582   // Find intersection of faces with (P,PC) segment elongated 3 times
583
584   double height = Papex.Distance( PC );
585   gp_Ax1 line( PC, gp_Vec( PC, Papex ));
586   gp_Pnt Pint, Ptest;
587   vector< const SMDS_MeshElement* > suspectFaces;
588   TColgp_SequenceOfPnt aContour;
589
590   if ( UseApexRay )
591   {
592     double idealHeight = height;
593     const SMDS_MeshElement* intFace = 0;
594
595     // find intersection closest to PC
596     Ptest = PC.XYZ() + line.Direction().XYZ() * height * 3;
597
598     searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces );
599     for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
600     {
601       const SMDS_MeshElement* face = suspectFaces[iF];
602       if ( face == NotCheckedFace ) continue;
603
604       aContour.Clear();
605       for ( int i = 0, nb = face->NbCornerNodes(); i < nb; ++i )
606         aContour.Append( SMESH_TNodeXYZ( face->GetNode(i) ));
607
608       if ( HasIntersection( Ptest, PC, Pint, aContour ))
609       {
610         double dInt = PC.Distance( Pint ) / 3.;
611         if ( dInt < height )
612         {
613           height = dInt;
614           intFace = face;
615         }
616       }
617     }
618     if ( height < 1e-2 * idealHeight && intFace )
619       return overlapError( aMesh, NotCheckedFace, intFace, Shape );
620   }
621
622   // Find faces intersecting triangular facets of the pyramid (issue 23212)
623
624   gp_XYZ center   = PC.XYZ() + line.Direction().XYZ() * height * 0.5;
625   double diameter = Max( PN(1).Distance(PN(3)), PN(2).Distance(PN(4)));
626   suspectFaces.clear();
627   searcher->GetElementsInSphere( center, diameter * 0.6, SMDSAbs_Face, suspectFaces);
628
629   const double upShift = 1.5;
630   Ptest = PC.XYZ() + line.Direction().XYZ() * height * upShift; // tmp apex
631
632   for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
633   {
634     const SMDS_MeshElement* face = suspectFaces[iF];
635     if ( face == NotCheckedFace ) continue;
636     if ( face->GetNodeIndex( FNodes[0] ) >= 0 ||
637          face->GetNodeIndex( FNodes[1] ) >= 0 ||
638          face->GetNodeIndex( FNodes[2] ) >= 0 ||
639          face->GetNodeIndex( FNodes[3] ) >= 0 )
640       continue; // neighbor face of the quadrangle
641
642     // limit height using points of intersection of face links with pyramid facets
643     int   nbN = face->NbCornerNodes();
644     gp_Pnt P1 = SMESH_TNodeXYZ( face->GetNode( nbN-1 )); // 1st link end
645     for ( int i = 0; i < nbN; ++i )
646     {
647       gp_Pnt P2 = SMESH_TNodeXYZ( face->GetNode(i) );    // 2nd link end
648
649       for ( int iN = 1; iN <= 4; ++iN ) // loop on pyramid facets
650       {
651         if ( HasIntersection3( P1, P2, Pint, PN(iN), PN(iN+1), Ptest ))
652         {
653           height = Min( height, gp_Vec( PC, Pint ) * line.Direction() );
654           //Ptest = PC.XYZ() + line.Direction().XYZ() * height * upShift; // new tmp apex
655         }
656       }
657       P1 = P2;
658     }
659   }
660
661   Papex  = PC.XYZ() + line.Direction().XYZ() * height;
662
663   return true;
664 }
665
666 //================================================================================
667 /*!
668  * \brief Prepare data for the given face
669  *  \param PN - coordinates of face nodes
670  *  \param VN - cross products of vectors (PC-PN(i)) ^ (PC-PN(i+1))
671  *  \param FNodes - face nodes
672  *  \param PC - gravity center of nodes
673  *  \param VNorm - face normal (sum of VN)
674  *  \param volumes - two volumes sharing the given face, the first is in VNorm direction
675  *  \retval int - 0 if given face is not quad,
676  *                1 if given face is quad,
677  *                2 if given face is degenerate quad (two nodes are coincided)
678  */
679 //================================================================================
680
681 int StdMeshers_QuadToTriaAdaptor::Preparation(const SMDS_MeshElement*       face,
682                                               TColgp_Array1OfPnt&           PN,
683                                               TColgp_Array1OfVec&           VN,
684                                               vector<const SMDS_MeshNode*>& FNodes,
685                                               gp_Pnt&                       PC,
686                                               gp_Vec&                       VNorm,
687                                               const SMDS_MeshElement**      volumes)
688 {
689   if( face->NbCornerNodes() != 4 )
690   {
691     return NOT_QUAD;
692   }
693
694   int i = 0;
695   gp_XYZ xyzC(0., 0., 0.);
696   for ( i = 0; i < 4; ++i )
697   {
698     gp_XYZ p = SMESH_TNodeXYZ( FNodes[i] = face->GetNode(i) );
699     PN.SetValue( i+1, p );
700     xyzC += p;
701   }
702   PC = xyzC/4;
703
704   int nbp = 4;
705
706   int j = 0;
707   for(i=1; i<4; i++) {
708     j = i+1;
709     for(; j<=4; j++) {
710       if( PN(i).Distance(PN(j)) < 1.e-6 )
711         break;
712     }
713     if(j<=4) break;
714   }
715   //int deg_num = IsDegenarate(PN);
716   //if(deg_num>0) {
717   bool hasdeg = false;
718   if(i<4) {
719     //cout<<"find degeneration"<<endl;
720     hasdeg = true;
721     gp_Pnt Pdeg = PN(i);
722
723     list< const SMDS_MeshNode* >::iterator itdg = myDegNodes.begin();
724     const SMDS_MeshNode* DegNode = 0;
725     for(; itdg!=myDegNodes.end(); itdg++) {
726       const SMDS_MeshNode* N = (*itdg);
727       gp_Pnt Ptmp(N->X(),N->Y(),N->Z());
728       if(Pdeg.Distance(Ptmp)<1.e-6) {
729         DegNode = N;
730         //DegNode = const_cast<SMDS_MeshNode*>(N);
731         break;
732       }
733     }
734     if(!DegNode) {
735       DegNode = FNodes[i-1];
736       myDegNodes.push_back(DegNode);
737     }
738     else {
739       FNodes[i-1] = DegNode;
740     }
741     for(i=j; i<4; i++) {
742       PN.SetValue(i,PN.Value(i+1));
743       FNodes[i-1] = FNodes[i];
744     }
745     nbp = 3;
746   }
747
748   PN.SetValue(nbp+1,PN(1));
749   FNodes[nbp] = FNodes[0];
750   // find normal direction
751   gp_Vec V1(PC,PN(nbp));
752   gp_Vec V2(PC,PN(1));
753   VNorm = V1.Crossed(V2);
754   VN.SetValue(nbp,VNorm);
755   for(i=1; i<nbp; i++) {
756     V1 = gp_Vec(PC,PN(i));
757     V2 = gp_Vec(PC,PN(i+1));
758     gp_Vec Vtmp = V1.Crossed(V2);
759     VN.SetValue(i,Vtmp);
760     VNorm += Vtmp;
761   }
762
763   // find volumes sharing the face
764   if ( volumes )
765   {
766     volumes[0] = volumes[1] = 0;
767     SMDS_ElemIteratorPtr vIt = FNodes[0]->GetInverseElementIterator( SMDSAbs_Volume );
768     while ( vIt->more() )
769     {
770       const SMDS_MeshElement* vol = vIt->next();
771       bool volSharesAllNodes = true;
772       for ( int i = 1; i < face->NbNodes() && volSharesAllNodes; ++i )
773         volSharesAllNodes = ( vol->GetNodeIndex( FNodes[i] ) >= 0 );
774       if ( volSharesAllNodes )
775         volumes[ volumes[0] ? 1 : 0 ] = vol;
776       // we could additionally check that vol has all FNodes in its one face using SMDS_VolumeTool
777     }
778     // define volume position relating to the face normal
779     if ( volumes[0] )
780     {
781       // get volume gc
782       SMDS_ElemIteratorPtr nodeIt = volumes[0]->nodesIterator();
783       gp_XYZ volGC(0,0,0);
784       volGC = accumulate( TXyzIterator(nodeIt), TXyzIterator(), volGC ) / volumes[0]->NbNodes();
785
786       if ( VNorm * gp_Vec( PC, volGC ) < 0 )
787         swap( volumes[0], volumes[1] );
788     }
789   }
790
791   //cout<<"  VNorm("<<VNorm.X()<<","<<VNorm.Y()<<","<<VNorm.Z()<<")"<<endl;
792   return hasdeg ? DEGEN_QUAD : QUAD;
793 }
794
795
796 //=======================================================================
797 //function : Compute
798 //purpose  :
799 //=======================================================================
800
801 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh&         aMesh,
802                                            const TopoDS_Shape& aShape,
803                                            SMESH_ProxyMesh*    aProxyMesh)
804 {
805   SMESH_ProxyMesh::setMesh( aMesh );
806
807   if ( aShape.ShapeType() != TopAbs_SOLID &&
808        aShape.ShapeType() != TopAbs_SHELL )
809     return false;
810
811   myShape = aShape;
812
813   vector<const SMDS_MeshElement*> myPyramids;
814
815   const SMESHDS_SubMesh * aSubMeshDSFace;
816   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
817   SMESH_MesherHelper helper(aMesh);
818   helper.IsQuadraticSubMesh(aShape);
819   helper.SetElementsOnShape( true );
820
821   if ( myElemSearcher ) delete myElemSearcher;
822   vector< SMDS_ElemIteratorPtr > itVec;
823   if ( aProxyMesh )
824   {
825     itVec.push_back( aProxyMesh->GetFaces( aShape ));
826   }
827   else
828   {
829     for ( TopExp_Explorer exp(aShape,TopAbs_FACE); exp.More(); exp.Next() )
830       if (( aSubMeshDSFace = meshDS->MeshElements( exp.Current() )))
831         itVec.push_back( aSubMeshDSFace->GetElements() );
832   }
833   typedef
834     SMDS_IteratorOnIterators< const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIter;
835   SMDS_ElemIteratorPtr faceIt( new TIter( itVec ));
836   myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS, faceIt );
837
838   TColgp_Array1OfPnt PN(1,5);
839   TColgp_Array1OfVec VN(1,4);
840   vector<const SMDS_MeshNode*> FNodes(5);
841   gp_Pnt PC;
842   gp_Vec VNorm;
843
844   for ( TopExp_Explorer exp(aShape,TopAbs_FACE); exp.More(); exp.Next() )
845   {
846     const TopoDS_Shape& aShapeFace = exp.Current();
847     if ( aProxyMesh )
848       aSubMeshDSFace = aProxyMesh->GetSubMesh( aShapeFace );
849     else
850       aSubMeshDSFace = meshDS->MeshElements( aShapeFace );
851
852     vector<const SMDS_MeshElement*> trias, quads;
853     bool hasNewTrias = false;
854
855     if ( aSubMeshDSFace )
856     {
857       bool isRev = false;
858       if ( helper.NbAncestors( aShapeFace, aMesh, aShape.ShapeType() ) > 1 )
859         isRev = helper.IsReversedSubMesh( TopoDS::Face(aShapeFace) );
860
861       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
862       while ( iteratorElem->more() ) // loop on elements on a geometrical face
863       {
864         const SMDS_MeshElement* face = iteratorElem->next();
865         // preparation step to get face info
866         int stat = Preparation(face, PN, VN, FNodes, PC, VNorm);
867         switch ( stat )
868         {
869         case NOT_QUAD:
870
871           trias.push_back( face );
872           break;
873
874         case DEGEN_QUAD:
875           {
876             // degenerate face
877             // add triangles to result map
878             SMDS_MeshFace* NewFace;
879             if(!isRev)
880               NewFace = meshDS->AddFace( FNodes[0], FNodes[1], FNodes[2] );
881             else
882               NewFace = meshDS->AddFace( FNodes[0], FNodes[2], FNodes[1] );
883             storeTmpElement( NewFace );
884             trias.push_back ( NewFace );
885             quads.push_back( face );
886             hasNewTrias = true;
887             break;
888           }
889
890         case QUAD:
891           {
892             if(!isRev) VNorm.Reverse();
893             double xc = 0., yc = 0., zc = 0.;
894             int i = 1;
895             for(; i<=4; i++) {
896               gp_Pnt Pbest;
897               if(!isRev)
898                 Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i).Reversed());
899               else
900                 Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i));
901               xc += Pbest.X();
902               yc += Pbest.Y();
903               zc += Pbest.Z();
904             }
905             gp_Pnt PCbest(xc/4., yc/4., zc/4.);
906
907             // check PCbest
908             double height = PCbest.Distance(PC);
909             if ( height < 1.e-6 ) {
910               // create new PCbest using a bit shift along VNorm
911               PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
912             }
913             else {
914               // check possible intersection with other faces
915               if ( !LimitHeight( PCbest, PC, PN, FNodes, aMesh, face, /*UseApexRay=*/true, aShape ))
916                 return false;
917             }
918             // create node for PCbest
919             SMDS_MeshNode* NewNode = helper.AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
920
921             // add triangles to result map
922             for(i=0; i<4; i++)
923             {
924               trias.push_back ( meshDS->AddFace( NewNode, FNodes[i], FNodes[i+1] ));
925               storeTmpElement( trias.back() );
926             }
927             // create a pyramid
928             if ( isRev ) swap( FNodes[1], FNodes[3]);
929             SMDS_MeshVolume* aPyram =
930               helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
931             myPyramids.push_back(aPyram);
932
933             quads.push_back( face );
934             hasNewTrias = true;
935             break;
936
937           } // case QUAD:
938
939         } // switch ( stat )
940       } // end loop on elements on a face submesh
941
942       bool sourceSubMeshIsProxy = false;
943       if ( aProxyMesh )
944       {
945         // move proxy sub-mesh from other proxy mesh to this
946         sourceSubMeshIsProxy = takeProxySubMesh( aShapeFace, aProxyMesh );
947         // move also tmp elements added in mesh
948         takeTmpElemsInMesh( aProxyMesh );
949       }
950       if ( hasNewTrias )
951       {
952         SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh( aShapeFace );
953         prxSubMesh->ChangeElements( trias.begin(), trias.end() );
954
955         // delete tmp quadrangles removed from aProxyMesh
956         if ( sourceSubMeshIsProxy )
957         {
958           for ( unsigned i = 0; i < quads.size(); ++i )
959             removeTmpElement( quads[i] );
960
961           delete myElemSearcher;
962           myElemSearcher =
963             SMESH_MeshAlgos::GetElementSearcher( *meshDS, aProxyMesh->GetFaces(aShape));
964         }
965       }
966     }
967   } // end for(TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
968
969   return Compute2ndPart(aMesh, myPyramids);
970 }
971
972 //================================================================================
973 /*!
974  * \brief Computes pyramids in mesh with no shape
975  */
976 //================================================================================
977
978 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh)
979 {
980   SMESH_ProxyMesh::setMesh( aMesh );
981   SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Triangle );
982   SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Quad_Triangle );
983   if ( aMesh.NbQuadrangles() < 1 )
984     return false;
985
986   // find if there is a group of faces identified as skin faces, with normal going outside the volume
987   std::string groupName = "skinFaces";
988   SMESHDS_GroupBase* groupDS = 0;
989   SMESH_Mesh::GroupIteratorPtr groupIt = aMesh.GetGroups();
990   while ( groupIt->more() )
991   {
992     groupDS = 0;
993     SMESH_Group * group = groupIt->next();
994     if ( !group ) continue;
995     groupDS = group->GetGroupDS();
996     if ( !groupDS || groupDS->IsEmpty() )
997     {
998       groupDS = 0;
999       continue;
1000     }
1001     if (groupDS->GetType() != SMDSAbs_Face)
1002     {
1003       groupDS = 0;
1004       continue;
1005     }
1006     std::string grpName = group->GetName();
1007     if (grpName == groupName)
1008     {
1009       break;
1010     }
1011     else
1012       groupDS = 0;
1013   }
1014
1015   vector<const SMDS_MeshElement*> myPyramids;
1016   SMESH_MesherHelper helper(aMesh);
1017   helper.IsQuadraticSubMesh(aMesh.GetShapeToMesh());
1018   helper.SetElementsOnShape( true );
1019
1020   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1021   SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh();
1022
1023   if ( !myElemSearcher )
1024     myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS );
1025   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
1026
1027   TColgp_Array1OfPnt PN(1,5);
1028   TColgp_Array1OfVec VN(1,4);
1029   vector<const SMDS_MeshNode*> FNodes(5);
1030   TColgp_SequenceOfPnt aContour;
1031
1032   SMDS_FaceIteratorPtr fIt = meshDS->facesIterator(/*idInceasingOrder=*/true);
1033   while( fIt->more())
1034   {
1035     const SMDS_MeshElement* face = fIt->next();
1036     if ( !face ) continue;
1037     // retrieve needed information about a face
1038     gp_Pnt PC;
1039     gp_Vec VNorm;
1040     const SMDS_MeshElement* volumes[2];
1041     int what = Preparation(face, PN, VN, FNodes, PC, VNorm, volumes);
1042     if ( what == NOT_QUAD )
1043       continue;
1044     if ( volumes[0] && volumes[1] )
1045       continue; // face is shared by two volumes - no space for a pyramid
1046
1047     if ( what == DEGEN_QUAD )
1048     {
1049       // degenerate face
1050       // add a triangle to the proxy mesh
1051       SMDS_MeshFace* NewFace;
1052
1053       // check orientation
1054       double tmp = PN(1).Distance(PN(2)) + PN(2).Distance(PN(3));
1055       // far points in VNorm direction
1056       gp_Pnt Ptmp1 = PC.XYZ() + VNorm.XYZ() * tmp * 1.e6;
1057       gp_Pnt Ptmp2 = PC.XYZ() - VNorm.XYZ() * tmp * 1.e6;
1058       // check intersection for Ptmp1 and Ptmp2
1059       bool IsRev = false;
1060       bool IsOK1 = false;
1061       bool IsOK2 = false;
1062       double dist1 = RealLast();
1063       double dist2 = RealLast();
1064       gp_Pnt Pres1,Pres2;
1065
1066       gp_Ax1 line( PC, VNorm );
1067       vector< const SMDS_MeshElement* > suspectFaces;
1068       searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces);
1069
1070       for ( size_t iF = 0; iF < suspectFaces.size(); ++iF ) {
1071         const SMDS_MeshElement* F = suspectFaces[iF];
1072         if ( F == face ) continue;
1073         aContour.Clear();
1074         for ( int i = 0; i < 4; ++i )
1075           aContour.Append( SMESH_TNodeXYZ( F->GetNode(i) ));
1076         gp_Pnt PPP;
1077         if ( !volumes[0] && HasIntersection( Ptmp1, PC, PPP, aContour )) {
1078           IsOK1 = true;
1079           double tmp = PC.Distance(PPP);
1080           if ( tmp < dist1 ) {
1081             Pres1 = PPP;
1082             dist1 = tmp;
1083           }
1084         }
1085         if ( !volumes[1] && HasIntersection( Ptmp2, PC, PPP, aContour )) {
1086           IsOK2 = true;
1087           double tmp = PC.Distance(PPP);
1088           if ( tmp < dist2 ) {
1089             Pres2 = PPP;
1090             dist2 = tmp;
1091           }
1092         }
1093       }
1094
1095       if( IsOK1 && !IsOK2 ) {
1096         // using existed direction
1097       }
1098       else if( !IsOK1 && IsOK2 ) {
1099         // using opposite direction
1100         IsRev = true;
1101       }
1102       else { // IsOK1 && IsOK2
1103         double tmp1 = PC.Distance(Pres1);
1104         double tmp2 = PC.Distance(Pres2);
1105         if(tmp1<tmp2) {
1106           // using existed direction
1107         }
1108         else {
1109           // using opposite direction
1110           IsRev = true;
1111         }
1112       }
1113       if(!IsRev)
1114         NewFace = meshDS->AddFace( FNodes[0], FNodes[1], FNodes[2] );
1115       else
1116         NewFace = meshDS->AddFace( FNodes[0], FNodes[2], FNodes[1] );
1117       storeTmpElement( NewFace );
1118       prxSubMesh->AddElement( NewFace );
1119       continue;
1120     }
1121
1122     // -----------------------------------
1123     // Case of non-degenerated quadrangle
1124     // -----------------------------------
1125
1126     // Find pyramid peak
1127
1128     gp_XYZ PCbest(0., 0., 0.); // pyramid peak
1129     int i = 1;
1130     for ( ; i <= 4; i++ ) {
1131       gp_Pnt Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i));
1132       PCbest += Pbest.XYZ();
1133     }
1134     PCbest /= 4;
1135
1136     double height = PC.Distance(PCbest); // pyramid height to precise
1137     if ( height < 1.e-6 ) {
1138       // create new PCbest using a bit shift along VNorm
1139       PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
1140       height = PC.Distance(PCbest);
1141       if ( height < std::numeric_limits<double>::min() )
1142         return false; // batterfly element
1143     }
1144
1145     // Restrict pyramid height by intersection with other faces
1146     gp_Vec tmpDir(PC,PCbest); tmpDir.Normalize();
1147     double tmp = PN(1).Distance(PN(3)) + PN(2).Distance(PN(4));
1148     // far points: in (PC, PCbest) direction and vice-versa
1149     gp_Pnt farPnt[2] = { PC.XYZ() + tmpDir.XYZ() * tmp * 1.e6,
1150                          PC.XYZ() - tmpDir.XYZ() * tmp * 1.e6 };
1151     // check intersection for farPnt1 and farPnt2
1152     bool   intersected[2] = { false, false };
1153     double dist2int   [2] = { RealLast(), RealLast() };
1154     gp_Pnt intPnt     [2];
1155     int    intFaceInd [2] = { 0, 0 };
1156
1157     gp_Ax1 line( PC, tmpDir );
1158     vector< const SMDS_MeshElement* > suspectFaces;
1159     searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces);
1160
1161     for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
1162     {
1163       const SMDS_MeshElement* F = suspectFaces[iF];
1164       if ( F == face ) continue;
1165       aContour.Clear();
1166       int nbN = F->NbCornerNodes();
1167       for ( i = 0; i < nbN; ++i )
1168         aContour.Append( SMESH_TNodeXYZ( F->GetNode(i) ));
1169       gp_Pnt intP;
1170       for ( int isRev = 0; isRev < 2; ++isRev )
1171       {
1172         if( !volumes[isRev] && HasIntersection(farPnt[isRev], PC, intP, aContour) )
1173         {
1174           double d = PC.Distance( intP );
1175           if ( d < dist2int[isRev] )
1176           {
1177             intersected[isRev] = true;
1178             intPnt     [isRev] = intP;
1179             dist2int   [isRev] = d;
1180             intFaceInd [isRev] = iF;
1181           }
1182         }
1183       }
1184     }
1185
1186     // if the face belong to the group of skinFaces, do not build a pyramid outside
1187     if ( groupDS && groupDS->Contains(face) )
1188     {
1189       intersected[0] = false;
1190     }
1191     else if ( intersected[0] && intersected[1] ) // check if one of pyramids is in a hole
1192     {
1193       gp_Pnt P ( PC.XYZ() + tmpDir.XYZ() * 0.5 * dist2int[0] );
1194       if ( searcher->GetPointState( P ) == TopAbs_OUT )
1195         intersected[0] = false;
1196       else
1197       {
1198         P = ( PC.XYZ() - tmpDir.XYZ() * 0.5 * dist2int[1] );
1199         if ( searcher->GetPointState( P ) == TopAbs_OUT )
1200           intersected[1] = false;
1201       }
1202     }
1203
1204     // Create one or two pyramids
1205
1206     for ( int isRev = 0; isRev < 2; ++isRev )
1207     {
1208       if ( !intersected[isRev] ) continue;
1209       double pyramidH = Min( height, dist2int[isRev]/3. );
1210       gp_Pnt    Papex = PC.XYZ() + tmpDir.XYZ() * (isRev ? -pyramidH : pyramidH);
1211       if ( pyramidH < 1e-2 * height )
1212         return overlapError( aMesh, face, suspectFaces[ intFaceInd[isRev] ] );
1213
1214       if ( !LimitHeight( Papex, PC, PN, FNodes, aMesh, face, /*UseApexRay=*/false ))
1215         return false;
1216
1217       // create node for Papex
1218       SMDS_MeshNode* NewNode = helper.AddNode( Papex.X(), Papex.Y(), Papex.Z() );
1219
1220       // add triangles to result map
1221       for ( i = 0; i < 4; i++) {
1222         SMDS_MeshFace* NewFace;
1223         if(isRev)
1224           NewFace = meshDS->AddFace( NewNode, FNodes[i], FNodes[i+1] );
1225         else
1226           NewFace = meshDS->AddFace( NewNode, FNodes[i+1], FNodes[i] );
1227         storeTmpElement( NewFace );
1228         prxSubMesh->AddElement( NewFace );
1229       }
1230       // create a pyramid
1231       SMDS_MeshVolume* aPyram;
1232       if(isRev)
1233         aPyram = helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
1234       else
1235         aPyram = helper.AddVolume( FNodes[0], FNodes[3], FNodes[2], FNodes[1], NewNode );
1236       myPyramids.push_back(aPyram);
1237     }
1238   } // end loop on all faces
1239
1240   return Compute2ndPart(aMesh, myPyramids);
1241 }
1242
1243 //================================================================================
1244 /*!
1245  * \brief Update created pyramids and faces to avoid their intersection
1246  */
1247 //================================================================================
1248
1249 bool StdMeshers_QuadToTriaAdaptor::Compute2ndPart(SMESH_Mesh&                            aMesh,
1250                                                   const vector<const SMDS_MeshElement*>& myPyramids)
1251 {
1252   if ( myPyramids.empty() )
1253     return true;
1254
1255   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1256   size_t i, j, k;
1257   //int myShapeID = myPyramids[0]->GetNode(4)->getshapeId();
1258   {
1259     SMDS_ElemIteratorPtr
1260       pyramIt( new SMDS_ElementVectorIterator( myPyramids.begin(), myPyramids.end() ));
1261     if ( myElemSearcher ) delete myElemSearcher;
1262     myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS, pyramIt );
1263   }
1264   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>( myElemSearcher );
1265
1266   set<const SMDS_MeshNode*> nodesToMove;
1267
1268   // check adjacent pyramids
1269
1270   for ( i = 0; i <  myPyramids.size(); ++i )
1271   {
1272     const SMDS_MeshElement* PrmI = myPyramids[i];
1273     MergeAdjacent( PrmI, nodesToMove );
1274   }
1275
1276   // iterate on all new pyramids
1277   vector< const SMDS_MeshElement* > suspectPyrams;
1278   for ( i = 0; i <  myPyramids.size(); ++i )
1279   {
1280     const SMDS_MeshElement*  PrmI = myPyramids[i];
1281     const SMDS_MeshNode*    apexI = PrmI->GetNode( PYRAM_APEX );
1282
1283     // compare PrmI with all the rest pyramids
1284
1285     // collect adjacent pyramids and nodes coordinates of PrmI
1286     set<const SMDS_MeshElement*> checkedPyrams;
1287     gp_Pnt PsI[5];
1288     for ( k = 0; k < 5; k++ )
1289     {
1290       const SMDS_MeshNode* n = PrmI->GetNode(k);
1291       PsI[k] = SMESH_TNodeXYZ( n );
1292       SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
1293       while ( vIt->more() )
1294       {
1295         const SMDS_MeshElement* PrmJ = vIt->next();
1296         if ( SMESH_MeshAlgos::GetCommonNodes( PrmI, PrmJ ).size() > 1 )
1297           checkedPyrams.insert( PrmJ );
1298       }
1299     }
1300
1301     // get pyramids to check
1302     gp_XYZ       PC = ( PsI[0].XYZ() + PsI[1].XYZ() + PsI[2].XYZ() + PsI[3].XYZ() ) / 4.;
1303     gp_XYZ      ray = PsI[4].XYZ() - PC;
1304     gp_XYZ   center = PC + 0.5 * ray;
1305     double diameter = Max( PsI[0].Distance(PsI[2]), PsI[1].Distance(PsI[3]));
1306     suspectPyrams.clear();
1307     searcher->GetElementsInSphere( center, diameter * 0.6, SMDSAbs_Volume, suspectPyrams);
1308
1309     // check intersection with distant pyramids
1310     for ( j = 0; j < suspectPyrams.size(); ++j )
1311     {
1312       const SMDS_MeshElement* PrmJ = suspectPyrams[j];
1313       if ( PrmJ == PrmI )
1314         continue;
1315       if ( apexI == PrmJ->GetNode( PYRAM_APEX ))
1316         continue; // pyramids PrmI and PrmJ already merged
1317       if ( !checkedPyrams.insert( PrmJ ).second )
1318         continue; // already checked
1319
1320       gp_Pnt PsJ[5];
1321       for ( k = 0; k < 5; k++ )
1322         PsJ[k] = SMESH_TNodeXYZ( PrmJ->GetNode(k) );
1323
1324       if ( ray * ( PsJ[4].XYZ() - PC ) < 0. )
1325         continue; // PrmJ is below PrmI
1326
1327       for ( k = 0; k < 4; k++ ) // loop on 4 base nodes of PrmI
1328       {
1329         gp_Pnt Pint;
1330         bool hasInt=false;
1331         for ( k = 0; k < 4  &&  !hasInt; k++ )
1332         {
1333           gp_Vec Vtmp( PsI[k], PsI[ PYRAM_APEX ]);
1334           gp_Pnt Pshift = PsI[k].XYZ() + Vtmp.XYZ() * 0.01; // base node moved a bit to apex
1335           hasInt =
1336           ( HasIntersection3( Pshift, PsI[4], Pint, PsJ[0], PsJ[1], PsJ[PYRAM_APEX]) ||
1337             HasIntersection3( Pshift, PsI[4], Pint, PsJ[1], PsJ[2], PsJ[PYRAM_APEX]) ||
1338             HasIntersection3( Pshift, PsI[4], Pint, PsJ[2], PsJ[3], PsJ[PYRAM_APEX]) ||
1339             HasIntersection3( Pshift, PsI[4], Pint, PsJ[3], PsJ[0], PsJ[PYRAM_APEX]) );
1340         }
1341         for ( k = 0; k < 4  &&  !hasInt; k++ )
1342         {
1343           gp_Vec Vtmp( PsJ[k], PsJ[ PYRAM_APEX ]);
1344           gp_Pnt Pshift = PsJ[k].XYZ() + Vtmp.XYZ() * 0.01;
1345           hasInt =
1346             ( HasIntersection3( Pshift, PsJ[4], Pint, PsI[0], PsI[1], PsI[PYRAM_APEX]) ||
1347               HasIntersection3( Pshift, PsJ[4], Pint, PsI[1], PsI[2], PsI[PYRAM_APEX]) ||
1348               HasIntersection3( Pshift, PsJ[4], Pint, PsI[2], PsI[3], PsI[PYRAM_APEX]) ||
1349               HasIntersection3( Pshift, PsJ[4], Pint, PsI[3], PsI[0], PsI[PYRAM_APEX]) );
1350         }
1351
1352         if ( hasInt )
1353         {
1354           // count common nodes of base faces of two pyramids
1355           int nbc = 0;
1356           for ( k = 0; k < 4; k++ )
1357             nbc += int ( PrmI->GetNodeIndex( PrmJ->GetNode(k) ) >= 0 );
1358
1359           if ( nbc == 4 )
1360             continue; // pyrams have a common base face
1361
1362           if ( nbc > 0 )
1363           {
1364             // Merge the two pyramids and others already merged with them
1365             MergePiramids( PrmI, PrmJ, nodesToMove );
1366           }
1367           else  // nbc==0
1368           {
1369             // decrease height of pyramids
1370             gp_XYZ PCi(0,0,0), PCj(0,0,0);
1371             for ( k = 0; k < 4; k++ ) {
1372               PCi += PsI[k].XYZ();
1373               PCj += PsJ[k].XYZ();
1374             }
1375             PCi /= 4; PCj /= 4;
1376             gp_Vec VN1(PCi,PsI[4]);
1377             gp_Vec VN2(PCj,PsJ[4]);
1378             gp_Vec VI1(PCi,Pint);
1379             gp_Vec VI2(PCj,Pint);
1380             double ang1 = fabs(VN1.Angle(VI1));
1381             double ang2 = fabs(VN2.Angle(VI2));
1382             double coef1 = 0.5 - (( ang1 < M_PI/3. ) ? cos(ang1)*0.25 : 0 );
1383             double coef2 = 0.5 - (( ang2 < M_PI/3. ) ? cos(ang2)*0.25 : 0 ); // cos(ang2) ?
1384 //             double coef2 = 0.5;
1385 //             if(ang2<PI/3)
1386 //               coef2 -= cos(ang1)*0.25;
1387
1388             VN1.Scale(coef1);
1389             VN2.Scale(coef2);
1390             SMDS_MeshNode* aNode1 = const_cast<SMDS_MeshNode*>( apexI );
1391             aNode1->setXYZ( PCi.X()+VN1.X(), PCi.Y()+VN1.Y(), PCi.Z()+VN1.Z() );
1392             SMDS_MeshNode* aNode2 = const_cast<SMDS_MeshNode*>(PrmJ->GetNode( PYRAM_APEX ));
1393             aNode2->setXYZ( PCj.X()+VN2.X(), PCj.Y()+VN2.Y(), PCj.Z()+VN2.Z() );
1394             nodesToMove.insert( aNode1 );
1395             nodesToMove.insert( aNode2 );
1396           }
1397           // fix intersections that can appear after apex movement
1398           MergeAdjacent( PrmI, nodesToMove );
1399           MergeAdjacent( PrmJ, nodesToMove );
1400
1401         } // end if(hasInt)
1402       } // loop on suspectPyrams
1403     }  // loop on 4 base nodes of PrmI
1404
1405   } // loop on all pyramids
1406
1407   if( !nodesToMove.empty() && !meshDS->IsEmbeddedMode() )
1408   {
1409     set<const SMDS_MeshNode*>::iterator n = nodesToMove.begin();
1410     for ( ; n != nodesToMove.end(); ++n )
1411       meshDS->MoveNode( *n, (*n)->X(), (*n)->Y(), (*n)->Z() );
1412   }
1413
1414   // move medium nodes of merged quadratic pyramids
1415   if ( myPyramids[0]->IsQuadratic() )
1416     UpdateQuadraticPyramids( nodesToMove, GetMeshDS() );
1417
1418   // erase removed triangles from the proxy mesh
1419   if ( !myRemovedTrias.empty() )
1420   {
1421     for ( int i = 0; i <= meshDS->MaxShapeIndex(); ++i )
1422       if ( SMESH_ProxyMesh::SubMesh* sm = findProxySubMesh(i))
1423       {
1424         vector<const SMDS_MeshElement *> faces;
1425         faces.reserve( sm->NbElements() );
1426         SMDS_ElemIteratorPtr fIt = sm->GetElements();
1427         while ( fIt->more() )
1428         {
1429           const SMDS_MeshElement* tria = fIt->next();
1430           set<const SMDS_MeshElement*>::iterator rmTria = myRemovedTrias.find( tria );
1431           if ( rmTria != myRemovedTrias.end() )
1432             myRemovedTrias.erase( rmTria );
1433           else
1434             faces.push_back( tria );
1435         }
1436         sm->ChangeElements( faces.begin(), faces.end() );
1437       }
1438   }
1439
1440   myDegNodes.clear();
1441
1442   delete myElemSearcher;
1443   myElemSearcher=0;
1444
1445   return true;
1446 }