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