Salome HOME
0020958: EDF 1529 SMESH : If some faces have been meshed with small
[modules/smesh.git] / src / StdMeshers / StdMeshers_QuadToTriaAdaptor.cxx
1 //  Copyright (C) 2007-2010  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.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
21 // File      : StdMeshers_QuadToTriaAdaptor.cxx
22 // Module    : SMESH
23 // Created   : Wen May 07 16:37:07 2008
24 // Author    : Sergey KUUL (skl)
25 //
26 #include "StdMeshers_QuadToTriaAdaptor.hxx"
27
28 #include <SMESH_Algo.hxx>
29 #include <SMESH_MesherHelper.hxx>
30
31 #include <IntAna_IntConicQuad.hxx>
32 #include <IntAna_Quadric.hxx>
33 #include <TColgp_HArray1OfPnt.hxx>
34 #include <TColgp_HArray1OfVec.hxx>
35 #include <TColgp_HSequenceOfPnt.hxx>
36 #include <TopExp_Explorer.hxx>
37 #include <TopoDS.hxx>
38 #include <gp_Lin.hxx>
39 #include <gp_Pln.hxx>
40
41 #include <numeric>
42
43 using namespace std;
44
45 enum EQuadNature { NOT_QUAD, QUAD, DEGEN_QUAD };
46
47   // std-like iterator used to get coordinates of nodes of mesh element
48 typedef SMDS_StdIterator< SMESH_MeshEditor::TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
49
50 //================================================================================
51 /*!
52  * \brief Constructor
53  */
54 //================================================================================
55
56 StdMeshers_QuadToTriaAdaptor::StdMeshers_QuadToTriaAdaptor():
57   myElemSearcher(0)
58 {
59 }
60
61 //================================================================================
62 /*!
63  * \brief Destructor
64  */
65 //================================================================================
66
67 StdMeshers_QuadToTriaAdaptor::~StdMeshers_QuadToTriaAdaptor()
68 {
69   // delete temporary faces
70   TQuad2Trias::iterator f_f = myResMap.begin(), ffEnd = myResMap.end();
71   for ( ; f_f != ffEnd; ++f_f )
72   {
73     TTriaList& fList = f_f->second;
74     TTriaList::iterator f = fList.begin(), fEnd = fList.end();
75     for ( ; f != fEnd; ++f )
76       delete *f;
77   }
78   myResMap.clear();
79
80 //   TF2PyramMap::iterator itp = myPyram2Trias.begin();
81 //   for(; itp!=myPyram2Trias.end(); itp++)
82 //     cout << itp->second << endl;
83
84   if ( myElemSearcher ) delete myElemSearcher;
85   myElemSearcher=0;
86 }
87
88
89 //=======================================================================
90 //function : FindBestPoint
91 //purpose  : Return a point P laying on the line (PC,V) so that triangle
92 //           (P, P1, P2) to be equilateral as much as possible
93 //           V - normal to (P1,P2,PC)
94 //=======================================================================
95 static gp_Pnt FindBestPoint(const gp_Pnt& P1, const gp_Pnt& P2,
96                             const gp_Pnt& PC, const gp_Vec& V)
97 {
98   double a = P1.Distance(P2);
99   double b = P1.Distance(PC);
100   double c = P2.Distance(PC);
101   if( a < (b+c)/2 )
102     return PC;
103   else {
104     // find shift along V in order a to became equal to (b+c)/2
105     double shift = sqrt( a*a + (b*b-c*c)*(b*b-c*c)/16/a/a - (b*b+c*c)/2 );
106     gp_Dir aDir(V);
107     gp_Pnt Pbest = PC.XYZ() + aDir.XYZ() * shift;
108     return Pbest;
109   }
110 }
111
112
113 //=======================================================================
114 //function : HasIntersection3
115 //purpose  : Auxilare for HasIntersection()
116 //           find intersection point between triangle (P1,P2,P3)
117 //           and segment [PC,P]
118 //=======================================================================
119 static bool HasIntersection3(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
120                              const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3)
121 {
122   //cout<<"HasIntersection3"<<endl;
123   //cout<<"  PC("<<PC.X()<<","<<PC.Y()<<","<<PC.Z()<<")"<<endl;
124   //cout<<"  P("<<P.X()<<","<<P.Y()<<","<<P.Z()<<")"<<endl;
125   //cout<<"  P1("<<P1.X()<<","<<P1.Y()<<","<<P1.Z()<<")"<<endl;
126   //cout<<"  P2("<<P2.X()<<","<<P2.Y()<<","<<P2.Z()<<")"<<endl;
127   //cout<<"  P3("<<P3.X()<<","<<P3.Y()<<","<<P3.Z()<<")"<<endl;
128   gp_Vec VP1(P1,P2);
129   gp_Vec VP2(P1,P3);
130   IntAna_Quadric IAQ(gp_Pln(P1,VP1.Crossed(VP2)));
131   IntAna_IntConicQuad IAICQ(gp_Lin(PC,gp_Dir(gp_Vec(PC,P))),IAQ);
132   if(IAICQ.IsDone()) {
133     if( IAICQ.IsInQuadric() )
134       return false;
135     if( IAICQ.NbPoints() == 1 ) {
136       gp_Pnt PIn = IAICQ.Point(1);
137       const double preci = 1.e-10 * P.Distance(PC);
138       // check if this point is internal for segment [PC,P]
139       bool IsExternal =
140         ( (PC.X()-PIn.X())*(P.X()-PIn.X()) > preci ) ||
141         ( (PC.Y()-PIn.Y())*(P.Y()-PIn.Y()) > preci ) ||
142         ( (PC.Z()-PIn.Z())*(P.Z()-PIn.Z()) > preci );
143       if(IsExternal) {
144         return false;
145       }
146       // check if this point is internal for triangle (P1,P2,P3)
147       gp_Vec V1(PIn,P1);
148       gp_Vec V2(PIn,P2);
149       gp_Vec V3(PIn,P3);
150       if( V1.Magnitude()<preci ||
151           V2.Magnitude()<preci ||
152           V3.Magnitude()<preci ) {
153         Pint = PIn;
154         return true;
155       }
156       const double angularTol = 1e-6;
157       gp_Vec VC1 = V1.Crossed(V2);
158       gp_Vec VC2 = V2.Crossed(V3);
159       gp_Vec VC3 = V3.Crossed(V1);
160       if(VC1.Magnitude()<gp::Resolution()) {
161         if(VC2.IsOpposite(VC3,angularTol)) {
162           return false;
163         }
164       }
165       else if(VC2.Magnitude()<gp::Resolution()) {
166         if(VC1.IsOpposite(VC3,angularTol)) {
167           return false;
168         }
169       }
170       else if(VC3.Magnitude()<gp::Resolution()) {
171         if(VC1.IsOpposite(VC2,angularTol)) {
172           return false;
173         }
174       }
175       else {
176         if( VC1.IsOpposite(VC2,angularTol) || VC1.IsOpposite(VC3,angularTol) ||
177             VC2.IsOpposite(VC3,angularTol) ) {
178           return false;
179         }
180       }
181       Pint = PIn;
182       return true;
183     }
184   }
185
186   return false;
187 }
188
189
190 //=======================================================================
191 //function : HasIntersection
192 //purpose  : Auxilare for CheckIntersection()
193 //=======================================================================
194
195 static bool HasIntersection(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
196                             Handle(TColgp_HSequenceOfPnt)& aContour)
197 {
198   if(aContour->Length()==3) {
199     return HasIntersection3( P, PC, Pint, aContour->Value(1),
200                              aContour->Value(2), aContour->Value(3) );
201   }
202   else {
203     bool check = false;
204     if( (aContour->Value(1).Distance(aContour->Value(2)) > 1.e-6) &&
205         (aContour->Value(1).Distance(aContour->Value(3)) > 1.e-6) &&
206         (aContour->Value(2).Distance(aContour->Value(3)) > 1.e-6) ) {
207       check = HasIntersection3( P, PC, Pint, aContour->Value(1),
208                                 aContour->Value(2), aContour->Value(3) );
209     }
210     if(check) return true;
211     if( (aContour->Value(1).Distance(aContour->Value(4)) > 1.e-6) &&
212         (aContour->Value(1).Distance(aContour->Value(3)) > 1.e-6) &&
213         (aContour->Value(4).Distance(aContour->Value(3)) > 1.e-6) ) {
214       check = HasIntersection3( P, PC, Pint, aContour->Value(1),
215                                 aContour->Value(3), aContour->Value(4) );
216     }
217     if(check) return true;
218   }
219
220   return false;
221 }
222
223 //================================================================================
224 /*!
225  * \brief Checks if a line segment (P,PC) intersects any mesh face.
226  *  \param P - first segment end
227  *  \param PC - second segment end (it is a gravity center of quadrangle)
228  *  \param Pint - (out) intersection point
229  *  \param aMesh - mesh
230  *  \param aShape - shape to check faces on
231  *  \param NotCheckedFace - not used
232  *  \retval bool - true if there is an intersection
233  */
234 //================================================================================
235
236 bool StdMeshers_QuadToTriaAdaptor::CheckIntersection (const gp_Pnt&       P,
237                                                       const gp_Pnt&       PC,
238                                                       gp_Pnt&             Pint,
239                                                       SMESH_Mesh&         aMesh,
240                                                       const TopoDS_Shape& aShape,
241                                                       const TopoDS_Shape& NotCheckedFace)
242 {
243   if ( !myElemSearcher )
244     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
245   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
246
247   //SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
248   //cout<<"    CheckIntersection: meshDS->NbFaces() = "<<meshDS->NbFaces()<<endl;
249   bool res = false;
250   double dist = RealLast(); // find intersection closest to the segment
251   gp_Pnt Pres;
252
253   gp_Ax1 line( P, gp_Vec(P,PC));
254   vector< const SMDS_MeshElement* > suspectElems;
255   searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectElems);
256   
257 //   for (TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
258 //     const TopoDS_Shape& aShapeFace = exp.Current();
259 //     if(aShapeFace==NotCheckedFace)
260 //       continue;
261 //     const SMESHDS_SubMesh * aSubMeshDSFace = meshDS->MeshElements(aShapeFace);
262 //     if ( aSubMeshDSFace ) {
263 //       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
264 //       while ( iteratorElem->more() ) { // loop on elements on a face
265 //         const SMDS_MeshElement* face = iteratorElem->next();
266   for ( int i = 0; i < suspectElems.size(); ++i )
267   {
268     const SMDS_MeshElement* face = suspectElems[i];
269     Handle(TColgp_HSequenceOfPnt) aContour = new TColgp_HSequenceOfPnt;
270     for ( int i = 0; i < face->NbCornerNodes(); ++i ) 
271       aContour->Append( SMESH_MeshEditor::TNodeXYZ( face->GetNode(i) ));
272     if( HasIntersection(P, PC, Pres, aContour) ) {
273       res = true;
274       double tmp = PC.Distance(Pres);
275       if(tmp<dist) {
276         Pint = Pres;
277         dist = tmp;
278       }
279     }
280   }
281   return res;
282 }
283
284
285 //=======================================================================
286 //function : EqualTriangles
287 //purpose  : Auxilare for Compute()
288 //=======================================================================
289 static bool EqualTriangles(const SMDS_MeshElement* F1,const SMDS_MeshElement* F2)
290 {
291   return
292     ( F1->GetNode(1)==F2->GetNode(2) && F1->GetNode(2)==F2->GetNode(1) ) ||
293     ( F1->GetNode(1)==F2->GetNode(1) && F1->GetNode(2)==F2->GetNode(2) );
294 }
295
296 //================================================================================
297 /*!
298  * \brief Prepare data for the given face
299  *  \param PN - coordinates of face nodes
300  *  \param VN - cross products of vectors (PC-PN(i)) ^ (PC-PN(i+1))
301  *  \param FNodes - face nodes
302  *  \param PC - gravity center of nodes
303  *  \param VNorm - face normal (sum of VN)
304  *  \param volumes - two volumes sharing the given face, the first is in VNorm direction
305  *  \retval int - 0 if given face is not quad,
306  *                1 if given face is quad,
307  *                2 if given face is degenerate quad (two nodes are coincided)
308  */
309 //================================================================================
310
311 int StdMeshers_QuadToTriaAdaptor::Preparation(const SMDS_MeshElement*       face,
312                                               Handle(TColgp_HArray1OfPnt)&  PN,
313                                               Handle(TColgp_HArray1OfVec)&  VN,
314                                               vector<const SMDS_MeshNode*>& FNodes,
315                                               gp_Pnt&                       PC,
316                                               gp_Vec&                       VNorm,
317                                               const SMDS_MeshElement**      volumes)
318 {
319   if( face->NbNodes() != ( face->IsQuadratic() ? 8 : 4 ))
320     if( face->NbNodes() != 4 )
321       return NOT_QUAD;
322
323   int i = 0;
324   gp_XYZ xyzC(0., 0., 0.);
325   for ( i = 0; i < 4; ++i )
326   {
327     gp_XYZ p = SMESH_MeshEditor::TNodeXYZ( FNodes[i] = face->GetNode(i) );
328     PN->SetValue( i+1, p );
329     xyzC += p;
330   }
331   PC = xyzC/4;
332   //cout<<"  PC("<<PC.X()<<","<<PC.Y()<<","<<PC.Z()<<")"<<endl;
333
334   int nbp = 4;
335
336   int j = 0;
337   for(i=1; i<4; i++) {
338     j = i+1;
339     for(; j<=4; j++) {
340       if( PN->Value(i).Distance(PN->Value(j)) < 1.e-6 )
341         break;
342     }
343     if(j<=4) break;
344   }
345   //int deg_num = IsDegenarate(PN);
346   //if(deg_num>0) {
347   bool hasdeg = false;
348   if(i<4) {
349     //cout<<"find degeneration"<<endl;
350     hasdeg = true;
351     gp_Pnt Pdeg = PN->Value(i);
352
353     list< const SMDS_MeshNode* >::iterator itdg = myDegNodes.begin();
354     const SMDS_MeshNode* DegNode = 0;
355     for(; itdg!=myDegNodes.end(); itdg++) {
356       const SMDS_MeshNode* N = (*itdg);
357       gp_Pnt Ptmp(N->X(),N->Y(),N->Z());
358       if(Pdeg.Distance(Ptmp)<1.e-6) {
359         DegNode = N;
360         //DegNode = const_cast<SMDS_MeshNode*>(N);
361         break;
362       }
363     }
364     if(!DegNode) {
365       DegNode = FNodes[i-1];
366       myDegNodes.push_back(DegNode);
367     }
368     else {
369       FNodes[i-1] = DegNode;
370     }
371     for(i=j; i<4; i++) {
372       PN->SetValue(i,PN->Value(i+1));
373       FNodes[i-1] = FNodes[i];
374     }
375     nbp = 3;
376   }
377
378   PN->SetValue(nbp+1,PN->Value(1));
379   FNodes[nbp] = FNodes[0];
380   // find normal direction
381   gp_Vec V1(PC,PN->Value(nbp));
382   gp_Vec V2(PC,PN->Value(1));
383   VNorm = V1.Crossed(V2);
384   VN->SetValue(nbp,VNorm);
385   for(i=1; i<nbp; i++) {
386     V1 = gp_Vec(PC,PN->Value(i));
387     V2 = gp_Vec(PC,PN->Value(i+1));
388     gp_Vec Vtmp = V1.Crossed(V2);
389     VN->SetValue(i,Vtmp);
390     VNorm += Vtmp;
391   }
392
393   // find volumes sharing the face
394   if ( volumes )
395   {
396     volumes[0] = volumes[1] = 0;
397     SMDS_ElemIteratorPtr vIt = FNodes[0]->GetInverseElementIterator( SMDSAbs_Volume );
398     while ( vIt->more() )
399     {
400       const SMDS_MeshElement* vol = vIt->next();
401       bool volSharesAllNodes = true;
402       for ( int i = 1; i < face->NbNodes() && volSharesAllNodes; ++i )
403         volSharesAllNodes = ( vol->GetNodeIndex( FNodes[i] ) >= 0 );
404       if ( volSharesAllNodes )
405         volumes[ volumes[0] ? 1 : 0 ] = vol;
406       // we could additionally check that vol has all FNodes in its one face using SMDS_VolumeTool
407     }
408     // define volume position relating to the face normal
409     if ( volumes[0] )
410     {
411       // get volume gc
412       SMDS_ElemIteratorPtr nodeIt = volumes[0]->nodesIterator();
413       gp_XYZ volGC(0,0,0);
414       volGC = accumulate( TXyzIterator(nodeIt), TXyzIterator(), volGC ) / volumes[0]->NbNodes();
415
416       if ( VNorm * gp_Vec( PC, volGC ) < 0 )
417         swap( volumes[0], volumes[1] );
418     }
419   }
420
421   //cout<<"  VNorm("<<VNorm.X()<<","<<VNorm.Y()<<","<<VNorm.Z()<<")"<<endl;
422   return hasdeg ? DEGEN_QUAD : QUAD;
423 }
424
425
426 //=======================================================================
427 //function : Compute
428 //purpose  : 
429 //=======================================================================
430
431 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
432 {
433   myResMap.clear();
434   myPyram2Trias.clear();
435
436   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
437   SMESH_MesherHelper helper(aMesh);
438   helper.IsQuadraticSubMesh(aShape);
439   helper.SetElementsOnShape( true );
440
441   
442
443   for (TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next())
444   {
445     const TopoDS_Shape& aShapeFace = exp.Current();
446     const SMESHDS_SubMesh * aSubMeshDSFace = meshDS->MeshElements( aShapeFace );
447     if ( aSubMeshDSFace )
448     {
449       bool isRev = SMESH_Algo::IsReversedSubMesh( TopoDS::Face(aShapeFace), meshDS );
450
451       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
452       while ( iteratorElem->more() ) // loop on elements on a geometrical face
453       {
454         const SMDS_MeshElement* face = iteratorElem->next();
455         //cout<<endl<<"================= face->GetID() = "<<face->GetID()<<endl;
456         // preparation step using face info
457         Handle(TColgp_HArray1OfPnt) PN = new TColgp_HArray1OfPnt(1,5);
458         Handle(TColgp_HArray1OfVec) VN = new TColgp_HArray1OfVec(1,4);
459         vector<const SMDS_MeshNode*> FNodes(5);
460         gp_Pnt PC;
461         gp_Vec VNorm;
462         int stat =  Preparation(face, PN, VN, FNodes, PC, VNorm);
463         if(stat==0)
464           continue;
465
466         if(stat==2)
467         {
468           // degenerate face
469           // add triangles to result map
470           SMDS_FaceOfNodes* NewFace;
471           if(!isRev)
472             NewFace = new SMDS_FaceOfNodes( FNodes[0], FNodes[1], FNodes[2] );
473           else
474             NewFace = new SMDS_FaceOfNodes( FNodes[0], FNodes[2], FNodes[1] );
475           TTriaList aList( 1, NewFace );
476           myResMap.insert(make_pair(face,aList));
477           continue;
478         }
479
480         if(!isRev) VNorm.Reverse();
481         double xc = 0., yc = 0., zc = 0.;
482         int i = 1;
483         for(; i<=4; i++) {
484           gp_Pnt Pbest;
485           if(!isRev)
486             Pbest = FindBestPoint(PN->Value(i), PN->Value(i+1), PC, VN->Value(i).Reversed());
487           else
488             Pbest = FindBestPoint(PN->Value(i), PN->Value(i+1), PC, VN->Value(i));
489           xc += Pbest.X();
490           yc += Pbest.Y();
491           zc += Pbest.Z();
492         }
493         gp_Pnt PCbest(xc/4., yc/4., zc/4.);
494
495         // check PCbest
496         double height = PCbest.Distance(PC);
497         if(height<1.e-6) {
498           // create new PCbest using a bit shift along VNorm
499           PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
500         }
501         else {
502           // check possible intersection with other faces
503           gp_Pnt Pint;
504           bool check = CheckIntersection(PCbest, PC, Pint, aMesh, aShape, aShapeFace);
505           if(check) {
506             //cout<<"--PC("<<PC.X()<<","<<PC.Y()<<","<<PC.Z()<<")"<<endl;
507             //cout<<"  PCbest("<<PCbest.X()<<","<<PCbest.Y()<<","<<PCbest.Z()<<")"<<endl;
508             double dist = PC.Distance(Pint)/3.;
509             gp_Dir aDir(gp_Vec(PC,PCbest));
510             PCbest = PC.XYZ() + aDir.XYZ() * dist;
511           }
512           else {
513             gp_Vec VB(PC,PCbest);
514             gp_Pnt PCbestTmp = PC.XYZ() + VB.XYZ() * 3.0;
515             check = CheckIntersection(PCbestTmp, PC, Pint, aMesh, aShape, aShapeFace);
516             if(check) {
517               double dist = PC.Distance(Pint)/3.;
518               if(dist<height) {
519                 gp_Dir aDir(gp_Vec(PC,PCbest));
520                 PCbest = PC.XYZ() + aDir.XYZ() * dist;
521               }
522             }
523           }
524         }
525         // create node for PCbest
526         SMDS_MeshNode* NewNode = helper.AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
527
528         // add triangles to result map
529         TTriaList& triaList = myResMap.insert( make_pair( face, TTriaList() ))->second;
530         for(i=0; i<4; i++)
531           triaList.push_back( new SMDS_FaceOfNodes( NewNode, FNodes[i], FNodes[i+1] ));
532
533         // create a pyramid
534         if ( isRev ) swap( FNodes[1], FNodes[3]);
535         SMDS_MeshVolume* aPyram =
536           helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
537         myPyram2Trias.insert(make_pair(aPyram, & triaList));
538
539       } // end loop on elements on a face submesh
540     }
541   } // end for(TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
542
543   return Compute2ndPart(aMesh);
544 }
545
546 //================================================================================
547 /*!
548  * \brief Computes pyramids in mesh with no shape
549  */
550 //================================================================================
551
552 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh)
553 {
554   myResMap.clear();
555   myPyram2Trias.clear();
556   SMESH_MesherHelper helper(aMesh);
557   helper.IsQuadraticSubMesh(aMesh.GetShapeToMesh());
558   helper.SetElementsOnShape( true );
559
560   if ( !myElemSearcher )
561     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
562   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
563
564   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
565
566   SMDS_FaceIteratorPtr fIt = meshDS->facesIterator(/*idInceasingOrder=*/true);
567   while( fIt->more()) 
568   {
569     const SMDS_MeshElement* face = fIt->next();
570     if ( !face ) continue;
571     //cout<<endl<<"================= face->GetID() = "<<face->GetID()<<endl;
572     // retrieve needed information about a face
573     Handle(TColgp_HArray1OfPnt) PN = new TColgp_HArray1OfPnt(1,5);
574     Handle(TColgp_HArray1OfVec) VN = new TColgp_HArray1OfVec(1,4);
575     vector<const SMDS_MeshNode*> FNodes(5);
576     gp_Pnt PC;
577     gp_Vec VNorm;
578     const SMDS_MeshElement* volumes[2];
579     int what = Preparation(face, PN, VN, FNodes, PC, VNorm, volumes);
580     if ( what == NOT_QUAD )
581       continue;
582     if ( volumes[0] && volumes[1] )
583       continue; // face is shared by two volumes - no space for a pyramid
584
585     if ( what == DEGEN_QUAD )
586     {
587       // degenerate face
588       // add triangles to result map
589       TTriaList aList;
590       SMDS_FaceOfNodes* NewFace;
591       // check orientation
592
593       double tmp = PN->Value(1).Distance(PN->Value(2)) + PN->Value(2).Distance(PN->Value(3));
594       // far points in VNorm direction
595       gp_Pnt Ptmp1 = PC.XYZ() + VNorm.XYZ() * tmp * 1.e6;
596       gp_Pnt Ptmp2 = PC.XYZ() - VNorm.XYZ() * tmp * 1.e6;
597       // check intersection for Ptmp1 and Ptmp2
598       bool IsRev = false;
599       bool IsOK1 = false;
600       bool IsOK2 = false;
601       double dist1 = RealLast();
602       double dist2 = RealLast();
603       gp_Pnt Pres1,Pres2;
604
605       gp_Ax1 line( PC, VNorm );
606       vector< const SMDS_MeshElement* > suspectElems;
607       searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectElems);
608
609       for ( int iF = 0; iF < suspectElems.size(); ++iF ) {
610         const SMDS_MeshElement* F = suspectElems[iF];
611         if(F==face) continue;
612         Handle(TColgp_HSequenceOfPnt) aContour = new TColgp_HSequenceOfPnt;
613         for ( int i = 0; i < 4; ++i )
614           aContour->Append( SMESH_MeshEditor::TNodeXYZ( F->GetNode(i) ));
615         gp_Pnt PPP;
616         if( !volumes[0] && HasIntersection(Ptmp1, PC, PPP, aContour) ) {
617           IsOK1 = true;
618           double tmp = PC.Distance(PPP);
619           if(tmp<dist1) {
620             Pres1 = PPP;
621             dist1 = tmp;
622           }
623         }
624         if( !volumes[1] && HasIntersection(Ptmp2, PC, PPP, aContour) ) {
625           IsOK2 = true;
626           double tmp = PC.Distance(PPP);
627           if(tmp<dist2) {
628             Pres2 = PPP;
629             dist2 = tmp;
630           }
631         }
632       }
633
634       if( IsOK1 && !IsOK2 ) {
635         // using existed direction
636       }
637       else if( !IsOK1 && IsOK2 ) {
638         // using opposite direction
639         IsRev = true;
640       }
641       else { // IsOK1 && IsOK2
642         double tmp1 = PC.Distance(Pres1);
643         double tmp2 = PC.Distance(Pres2);
644         if(tmp1<tmp2) {
645           // using existed direction
646         }
647         else {
648           // using opposite direction
649           IsRev = true;
650         }
651       }
652       if(!IsRev)
653         NewFace = new SMDS_FaceOfNodes( FNodes[0], FNodes[1], FNodes[2] );
654       else
655         NewFace = new SMDS_FaceOfNodes( FNodes[0], FNodes[2], FNodes[1] );
656       aList.push_back(NewFace);
657       myResMap.insert(make_pair(face,aList));
658       continue;
659     }
660
661     // Find pyramid peak
662
663     gp_XYZ PCbest(0., 0., 0.); // pyramid peak
664     int i = 1;
665     for(; i<=4; i++) {
666       gp_Pnt Pbest = FindBestPoint(PN->Value(i), PN->Value(i+1), PC, VN->Value(i));
667       PCbest += Pbest.XYZ();
668     }
669     PCbest /= 4;
670
671     double height = PC.Distance(PCbest); // pyramid height to precise
672     if(height<1.e-6) {
673       // create new PCbest using a bit shift along VNorm
674       PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
675       height = PC.Distance(PCbest);
676     }
677     //cout<<"  PCbest("<<PCbest.X()<<","<<PCbest.Y()<<","<<PCbest.Z()<<")"<<endl;
678
679     // Restrict pyramid height by intersection with other faces
680     gp_Vec tmpDir(PC,PCbest); tmpDir.Normalize();
681     double tmp = PN->Value(1).Distance(PN->Value(3)) + PN->Value(2).Distance(PN->Value(4));
682     // far points: in (PC, PCbest) direction and vice-versa
683     gp_Pnt farPnt[2] = { PC.XYZ() + tmpDir.XYZ() * tmp * 1.e6,
684                          PC.XYZ() - tmpDir.XYZ() * tmp * 1.e6 };
685     // check intersection for farPnt1 and farPnt2
686     bool   intersected[2] = { false, false };
687     double dist       [2] = { RealLast(), RealLast() };
688     gp_Pnt intPnt[2];
689
690     gp_Ax1 line( PC, tmpDir );
691     vector< const SMDS_MeshElement* > suspectElems;
692     searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectElems);
693
694     for ( int iF = 0; iF < suspectElems.size(); ++iF )
695     {
696       const SMDS_MeshElement* F = suspectElems[iF];
697       if(F==face) continue;
698       Handle(TColgp_HSequenceOfPnt) aContour = new TColgp_HSequenceOfPnt;
699       int nbN = F->NbNodes() / ( F->IsQuadratic() ? 2 : 1 );
700       for ( i = 0; i < nbN; ++i )
701         aContour->Append( SMESH_MeshEditor::TNodeXYZ( F->GetNode(i) ));
702       gp_Pnt intP;
703       for ( int isRev = 0; isRev < 2; ++isRev )
704       {
705         if( !volumes[isRev] && HasIntersection(farPnt[isRev], PC, intP, aContour) ) {
706           intersected[isRev] = true;
707           double d = PC.Distance( intP );
708           if( d < dist[isRev] )
709           {
710             intPnt[isRev] = intP;
711             dist  [isRev] = d;
712           }
713         }
714       }
715     }
716
717     // Create one or two pyramids
718
719     for ( int isRev = 0; isRev < 2; ++isRev )
720     {
721       if( !intersected[isRev] ) continue;
722       double pyramidH = Min( height, PC.Distance(intPnt[isRev])/3.);
723       PCbest = PC.XYZ() + tmpDir.XYZ() * (isRev ? -pyramidH : pyramidH);
724
725       // create node for PCbest
726       SMDS_MeshNode* NewNode = helper.AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
727
728       // add triangles to result map
729       TTriaList& aList = myResMap.insert( make_pair( face, TTriaList()))->second;
730       for(i=0; i<4; i++) {
731         SMDS_FaceOfNodes* NewFace;
732         if(isRev)
733           NewFace = new SMDS_FaceOfNodes( NewNode, FNodes[i], FNodes[i+1] );
734         else
735           NewFace = new SMDS_FaceOfNodes( NewNode, FNodes[i+1], FNodes[i] );
736         aList.push_back(NewFace);
737       }
738       // create a pyramid
739       SMDS_MeshVolume* aPyram;
740       if(isRev)
741         aPyram = helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
742       else
743         aPyram = helper.AddVolume( FNodes[0], FNodes[3], FNodes[2], FNodes[1], NewNode );
744       myPyram2Trias.insert(make_pair(aPyram, & aList));
745     }
746   } // end loop on all faces
747
748   return Compute2ndPart(aMesh);
749 }
750
751 //================================================================================
752 /*!
753  * \brief Update created pyramids and faces to avoid their intersection
754  */
755 //================================================================================
756
757 bool StdMeshers_QuadToTriaAdaptor::Compute2ndPart(SMESH_Mesh& aMesh)
758 {
759   cout << "Compute2ndPart(), nb pyramids = " << myPyram2Trias.size() << endl;
760   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
761
762   // check intersections between created pyramids
763
764   if(myPyram2Trias.empty())
765     return true;
766
767   int k = 0;
768
769   // for each pyramid store list of merged pyramids with their faces
770   typedef map< const SMDS_MeshElement*, list< TPyram2Trias::iterator > > TPyram2Merged;
771   TPyram2Merged MergesInfo;
772
773   if ( !myElemSearcher )
774     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
775   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
776
777   // iterate on all pyramids
778   TPyram2Trias::iterator itPi = myPyram2Trias.begin(), itPEnd = myPyram2Trias.end();
779   for ( ; itPi != itPEnd; ++itPi )
780   {
781     const SMDS_MeshElement* PrmI = itPi->first;
782     TPyram2Merged::iterator pMergesI = MergesInfo.find( PrmI );
783
784     TXyzIterator xyzIt( PrmI->nodesIterator() );
785     vector<gp_Pnt> PsI( xyzIt, TXyzIterator() );
786
787     // compare PrmI with all the rest pyramids
788
789     bool NeedMove = false;
790
791     bool hasInt = false;
792     for(k=0; k<4 && !hasInt; k++) // loop on 4 base nodes of PrmI
793     {
794       gp_Vec Vtmp(PsI[k],PsI[4]);
795       gp_Pnt Pshift = PsI[k].XYZ() + Vtmp.XYZ() * 0.01; // base node moved a bit to apex
796
797       gp_Ax1 line( PsI[k], Vtmp );
798       vector< const SMDS_MeshElement* > suspectPyrams;
799       searcher->GetElementsNearLine( line, SMDSAbs_Volume, suspectPyrams);
800
801       for ( int j = 0; j < suspectPyrams.size(); ++j )
802       {
803         const SMDS_MeshElement* PrmJ = suspectPyrams[j];
804         if ( PrmJ == PrmI || PrmJ->NbCornerNodes() != 5 ) continue;
805
806         TPyram2Trias::iterator itPj = myPyram2Trias.find( PrmJ );
807         if ( itPj == myPyram2Trias.end() ) continue; // pyramid from other SOLID
808
809         // check if two pyramids already merged
810         TPyram2Merged::iterator pMergesJ = MergesInfo.find( PrmJ );
811         if ( pMergesJ != MergesInfo.end() &&
812              find(pMergesJ->second.begin(),pMergesJ->second.end(), itPi )!=pMergesJ->second.end())
813           continue;
814         
815         xyzIt = TXyzIterator( PrmJ->nodesIterator() );
816         vector<gp_Pnt> PsJ( xyzIt, TXyzIterator() );
817
818         gp_Pnt Pint;
819         hasInt = 
820           ( HasIntersection3( Pshift, PsI[4], Pint, PsJ[0], PsJ[1], PsJ[4]) ||
821             HasIntersection3( Pshift, PsI[4], Pint, PsJ[1], PsJ[2], PsJ[4]) ||
822             HasIntersection3( Pshift, PsI[4], Pint, PsJ[2], PsJ[3], PsJ[4]) ||
823             HasIntersection3( Pshift, PsI[4], Pint, PsJ[3], PsJ[0], PsJ[4]) );
824
825         for(k=0; k<4 && !hasInt; k++) {
826           gp_Vec Vtmp(PsJ[k],PsJ[4]);
827           gp_Pnt Pshift = PsJ[k].XYZ() + Vtmp.XYZ() * 0.01;
828           hasInt = 
829             ( HasIntersection3( Pshift, PsJ[4], Pint, PsI[0], PsI[1], PsI[4]) ||
830               HasIntersection3( Pshift, PsJ[4], Pint, PsI[1], PsI[2], PsI[4]) ||
831               HasIntersection3( Pshift, PsJ[4], Pint, PsI[2], PsI[3], PsI[4]) ||
832               HasIntersection3( Pshift, PsJ[4], Pint, PsI[3], PsI[0], PsI[4]) );
833         }
834         if ( hasInt ) {
835           // count common nodes of base faces of two pyramids
836           int nbc = 0;
837           for(k=0; k<4; k++)
838             nbc += int ( PrmI->GetNodeIndex( PrmJ->GetNode(k) ) >= 0 );
839
840           if ( nbc == 4 )
841             continue; // pyrams have a common base face
842
843           if(nbc>0)
844           {
845             cout << "Merge pyram " << PrmI->GetID() <<" to " << PrmJ->GetID() << endl;
846             // Merge the two pyramids and others already merged with them
847
848             // initialize merge info of pyramids
849             if ( pMergesI == MergesInfo.end() ) // first merge of PrmI
850             {
851               pMergesI = MergesInfo.insert( make_pair( PrmI, list<TPyram2Trias::iterator >())).first;
852               pMergesI->second.push_back( itPi );
853             }
854             if ( pMergesJ == MergesInfo.end() ) // first merge of PrmJ
855             {
856               pMergesJ = MergesInfo.insert( make_pair( PrmJ, list<TPyram2Trias::iterator >())).first;
857               pMergesJ->second.push_back( itPj );
858             }
859             int nbI = pMergesI->second.size(), nbJ = pMergesJ->second.size();
860
861             // an apex node to make common to all merged pyramids
862             SMDS_MeshNode* CommonNode = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
863             CommonNode->setXYZ( ( nbI*PsI[4].X() + nbJ*PsJ[4].X() ) / (nbI+nbJ),
864                                 ( nbI*PsI[4].Y() + nbJ*PsJ[4].Y() ) / (nbI+nbJ),
865                                 ( nbI*PsI[4].Z() + nbJ*PsJ[4].Z() ) / (nbI+nbJ) );
866             NeedMove = true;
867             const SMDS_MeshNode* Nrem = PrmJ->GetNode(4); // node to remove
868
869             list< TPyram2Trias::iterator >& aMergesI = pMergesI->second;
870             list< TPyram2Trias::iterator >& aMergesJ = pMergesJ->second;
871
872             // find and remove coincided faces of merged pyramids
873             list< TPyram2Trias::iterator >::iterator itPttI, itPttJ;
874             TTriaList::iterator trI, trJ;
875             for ( itPttI = aMergesI.begin(); itPttI != aMergesI.end(); ++itPttI )
876             {
877               TTriaList* triaListI = (*itPttI)->second;
878               for ( trI = triaListI->begin(); trI != triaListI->end(); )
879               {
880                 const SMDS_FaceOfNodes* FI = *trI;
881
882                 for ( itPttJ = aMergesJ.begin(); itPttJ != aMergesJ.end() && FI; ++itPttJ )
883                 {
884                   TTriaList* triaListJ = (*itPttJ)->second;
885                   for ( trJ = triaListJ->begin(); trJ != triaListJ->end();  )
886                   {
887                     const SMDS_FaceOfNodes* FJ = *trJ;
888
889                     if( EqualTriangles(FI,FJ) )
890                     {
891                       delete FI;
892                       delete FJ;
893                       FI = FJ = 0;
894                       trI = triaListI->erase( trI );
895                       trJ = triaListJ->erase( trJ ); 
896                       break; // only one triangle of a pyramid can coincide with another pyramid
897                     }
898                     ++trJ;
899                   }
900                 }
901                 if ( FI ) ++trI; // increament if triangle not deleted
902               }
903             }
904
905             // set the common apex node to pyramids and triangles merged with J
906             for ( itPttJ = aMergesJ.begin(); itPttJ != aMergesJ.end(); ++itPttJ )
907             {
908               const SMDS_MeshElement* Prm = (*itPttJ)->first;
909               TTriaList*         triaList = (*itPttJ)->second;
910
911               vector< const SMDS_MeshNode* > nodes( Prm->begin_nodes(), Prm->end_nodes() );
912               nodes[4] = CommonNode;
913               meshDS->ChangeElementNodes( Prm, &nodes[0], nodes.size());
914
915               for ( TTriaList::iterator trIt = triaList->begin(); trIt != triaList->end(); ++trIt )
916               {
917                 SMDS_FaceOfNodes* Ftria = const_cast< SMDS_FaceOfNodes*>( *trIt );
918                 const SMDS_MeshNode* NF[3] = { CommonNode, Ftria->GetNode(1), Ftria->GetNode(2)};
919                 Ftria->ChangeNodes(NF, 3);
920               }
921             }
922
923             // join MergesInfo of merged pyramids
924             for ( k = 0, itPttI = aMergesI.begin(); k < nbI; ++itPttI, ++k )
925             {
926               const SMDS_MeshElement* PrmI = (*itPttI)->first;
927               list< TPyram2Trias::iterator >& merges = MergesInfo[ PrmI ];
928               merges.insert( merges.end(), aMergesJ.begin(), aMergesJ.end() );
929             }
930             for ( k = 0, itPttJ = aMergesJ.begin(); k < nbJ; ++itPttJ, ++k )
931             {
932               const SMDS_MeshElement* PrmJ = (*itPttJ)->first;
933               list< TPyram2Trias::iterator >& merges = MergesInfo[ PrmJ ];
934               merges.insert( merges.end(), aMergesI.begin(), aMergesI.end() );
935             }
936
937             // removing node
938             meshDS->RemoveNode(Nrem);
939           }
940           else { // nbc==0
941
942             // decrease height of pyramids
943             gp_XYZ PC1(0,0,0), PC2(0,0,0);
944             for(k=0; k<4; k++) {
945               PC1 += PsI[k].XYZ();
946               PC2 += PsJ[k].XYZ();
947             }
948             PC1 /= 4; PC2 /= 4; 
949             gp_Vec VN1(PC1,PsI[4]);
950             gp_Vec VI1(PC1,Pint);
951             gp_Vec VN2(PC2,PsJ[4]);
952             gp_Vec VI2(PC2,Pint);
953             double ang1 = fabs(VN1.Angle(VI1));
954             double ang2 = fabs(VN2.Angle(VI2));
955             double h1,h2;
956             if(ang1>PI/3.)
957               h1 = VI1.Magnitude()/2;
958             else
959               h1 = VI1.Magnitude()*cos(ang1);
960             if(ang2>PI/3.)
961               h2 = VI2.Magnitude()/2;
962             else
963               h2 = VI2.Magnitude()*cos(ang2);
964             double coef1 = 0.5;
965             if(ang1<PI/3)
966               coef1 -= cos(ang1)*0.25;
967             double coef2 = 0.5;
968             if(ang2<PI/3)
969               coef2 -= cos(ang1)*0.25;
970
971             VN1.Scale(coef1);
972             VN2.Scale(coef2);
973             SMDS_MeshNode* aNode1 = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
974             aNode1->setXYZ( PC1.X()+VN1.X(), PC1.Y()+VN1.Y(), PC1.Z()+VN1.Z() );
975             SMDS_MeshNode* aNode2 = const_cast<SMDS_MeshNode*>(PrmJ->GetNode(4));
976             aNode2->setXYZ( PC2.X()+VN2.X(), PC2.Y()+VN2.Y(), PC2.Z()+VN2.Z() );
977             NeedMove = true;
978           }
979         } // end if(hasInt)
980       } // loop on suspectPyrams
981     }  // loop on 4 base nodes of PrmI
982     if( NeedMove && !meshDS->IsEmbeddedMode() )
983     {
984       const SMDS_MeshNode* apex = PrmI->GetNode( 4 );
985       meshDS->MoveNode( apex, apex->X(), apex->Y(), apex->Z() );
986     }
987   } // loop on all pyramids
988
989   // rebind triangles of pyramids sharing the same base quadrangle to the first
990   // entrance of the base quadrangle
991   TQuad2Trias::iterator q2t = myResMap.begin(), q2tPrev = q2t;
992   for ( ++q2t; q2t != myResMap.end(); ++q2t, ++q2tPrev )
993   {
994     if ( q2t->first == q2tPrev->first )
995       q2tPrev->second.splice( q2tPrev->second.end(), q2t->second );
996   }
997
998   myPyram2Trias.clear(); // no more needed
999   myDegNodes.clear();
1000
1001   delete myElemSearcher;
1002   myElemSearcher=0;
1003
1004   cout << "END Compute2ndPart()" << endl;
1005   return true;
1006 }
1007
1008 //================================================================================
1009 /*!
1010  * \brief Return list of created triangles for given face
1011  */
1012 //================================================================================
1013
1014 const list<const SMDS_FaceOfNodes* >* StdMeshers_QuadToTriaAdaptor::GetTriangles (const SMDS_MeshElement* aQuad)
1015 {
1016   TQuad2Trias::iterator it = myResMap.find(aQuad);
1017   if( it != myResMap.end() ) {
1018     return & it->second;
1019   }
1020   return 0;
1021 }